@runtypelabs/persona 4.14.0 → 4.15.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/README.md +4 -4
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
- package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-QJ4LV2KW.js +1 -0
- package/dist/codegen.cjs +12 -11
- package/dist/codegen.js +14 -13
- package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
- package/dist/context-mentions.cjs +11 -8
- package/dist/context-mentions.d.cts +241 -16
- package/dist/context-mentions.d.ts +241 -16
- package/dist/context-mentions.js +11 -8
- package/dist/index.cjs +67 -66
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +301 -41
- package/dist/index.d.ts +301 -41
- package/dist/index.global.js +59 -56
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +67 -66
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +241 -16
- package/dist/smart-dom-reader.d.ts +241 -16
- package/dist/theme-editor-preview.cjs +66 -66
- package/dist/theme-editor-preview.d.cts +255 -17
- package/dist/theme-editor-preview.d.ts +255 -17
- package/dist/theme-editor-preview.js +56 -56
- package/dist/theme-editor.cjs +5 -5
- package/dist/theme-editor.d.cts +242 -17
- package/dist/theme-editor.d.ts +242 -17
- package/dist/theme-editor.js +7 -7
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +38 -0
- package/dist/theme-reference.d.ts +38 -0
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/ask-user-question-tool.ts +10 -7
- package/src/components/artifact-preview.ts +1 -1
- package/src/components/composer-parts.test.ts +103 -4
- package/src/components/composer-parts.ts +53 -15
- package/src/components/messages.ts +5 -2
- package/src/components/panel.ts +31 -5
- package/src/components/pill-composer-builder.test.ts +18 -0
- package/src/components/suggestions.test.ts +233 -0
- package/src/components/suggestions.ts +463 -81
- package/src/components/widget-view.ts +4 -0
- package/src/defaults.ts +5 -3
- package/src/generated/runtype-openapi-contract.ts +17 -0
- package/src/index-core.ts +18 -2
- package/src/launcher-global.ts +1 -1
- package/src/plugins/types.ts +71 -3
- package/src/presets.ts +3 -3
- package/src/session.ts +10 -8
- package/src/styles/widget-styles.test.ts +162 -0
- package/src/styles/widget.css +430 -0
- package/src/suggest-replies-tool.test.ts +233 -2
- package/src/suggest-replies-tool.ts +115 -39
- package/src/theme-editor/preview-utils.test.ts +34 -0
- package/src/theme-editor/preview-utils.ts +77 -2
- package/src/theme-editor/sections.test.ts +33 -0
- package/src/theme-editor/sections.ts +53 -5
- package/src/theme-reference.ts +9 -2
- package/src/types/theme.ts +32 -0
- package/src/types.ts +152 -16
- package/src/ui.detached-panel.test.ts +1 -1
- package/src/ui.suggest-replies.test.ts +1066 -1
- package/src/ui.ts +268 -20
- package/src/utils/artifact-file.test.ts +1 -1
- package/src/utils/code-generators.test.ts +40 -0
- package/src/utils/code-generators.ts +22 -0
- package/src/utils/config-merge.test.ts +24 -0
- package/src/utils/icons.test.ts +26 -0
- package/src/utils/icons.ts +8 -0
- package/src/utils/theme.test.ts +79 -0
- package/src/utils/tokens.ts +64 -0
- package/dist/chunk-MMUPR2JW.js +0 -1
package/dist/index.global.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
|
-
"use strict";var AgentWidget=(()=>{var
|
|
2
|
-
\r `.includes(e[o]);)o++};return s()},
|
|
3
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],a=t[o+1];if(!
|
|
4
|
-
`):e};var
|
|
1
|
+
"use strict";var AgentWidget=(()=>{var Wb=Object.create;var Qs=Object.defineProperty;var Hb=Object.getOwnPropertyDescriptor;var Bb=Object.getOwnPropertyNames;var Db=Object.getPrototypeOf,Fb=Object.prototype.hasOwnProperty;var Ba=(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 Ob=(e,t)=>()=>(e&&(t=e(e=0)),t);var am=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sm=(e,t)=>{for(var n in t)Qs(e,n,{get:t[n],enumerable:!0})},im=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Bb(t))!Fb.call(e,r)&&r!==n&&Qs(e,r,{get:()=>t[r],enumerable:!(o=Hb(t,r))||o.enumerable});return e};var xo=(e,t,n)=>(n=e!=null?Wb(Db(e)):{},im(t||!e||!e.__esModule?Qs(n,"default",{value:e,enumerable:!0}):n,e)),Nb=e=>im(Qs({},"__esModule",{value:!0}),e);var md=am(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.Allow=xe.ALL=xe.COLLECTION=xe.ATOM=xe.SPECIAL=xe.INF=xe._INFINITY=xe.INFINITY=xe.NAN=xe.BOOL=xe.NULL=xe.OBJ=xe.ARR=xe.NUM=xe.STR=void 0;xe.STR=1;xe.NUM=2;xe.ARR=4;xe.OBJ=8;xe.NULL=16;xe.BOOL=32;xe.NAN=64;xe.INFINITY=128;xe._INFINITY=256;xe.INF=xe.INFINITY|xe._INFINITY;xe.SPECIAL=xe.NULL|xe.BOOL|xe.INF|xe.NAN;xe.ATOM=xe.STR|xe.NUM|xe.SPECIAL;xe.COLLECTION=xe.ARR|xe.OBJ;xe.ALL=xe.ATOM|xe.COLLECTION;xe.Allow={STR:xe.STR,NUM:xe.NUM,ARR:xe.ARR,OBJ:xe.OBJ,NULL:xe.NULL,BOOL:xe.BOOL,NAN:xe.NAN,INFINITY:xe.INFINITY,_INFINITY:xe._INFINITY,INF:xe.INF,SPECIAL:xe.SPECIAL,ATOM:xe.ATOM,COLLECTION:xe.COLLECTION,ALL:xe.ALL};xe.default=xe.Allow});var oi=am(_t=>{"use strict";var ix=_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]})),lx=_t&&_t.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&ix(t,e,n)};Object.defineProperty(_t,"__esModule",{value:!0});_t.Allow=_t.MalformedJSON=_t.PartialJSON=_t.parseJSON=_t.parse=void 0;var Yt=md();Object.defineProperty(_t,"Allow",{enumerable:!0,get:function(){return Yt.Allow}});lx(md(),_t);var ti=class extends Error{};_t.PartialJSON=ti;var ni=class extends Error{};_t.MalformedJSON=ni;function km(e,t=Yt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return dx(e.trim(),t)}_t.parseJSON=km;var dx=(e,t)=>{let n=e.length,o=0,r=g=>{throw new ti(`${g} at position ${o}`)},a=g=>{throw new ni(`${g} at position ${o}`)},s=()=>(u(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?c():e.substring(o,o+4)==="null"||Yt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Yt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Yt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Yt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Yt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Yt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):d()),l=()=>{let g=o,f=!1;for(o++;o<n&&(e[o]!=='"'||f&&e[o-1]==="\\");)f=e[o]==="\\"?!f:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(g,++o-Number(f)))}catch(h){a(String(h))}else if(Yt.Allow.STR&t)try{return JSON.parse(e.substring(g,o-Number(f))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},p=()=>{o++,u();let g={};try{for(;e[o]!=="}";){if(u(),o>=n&&Yt.Allow.OBJ&t)return g;let f=l();u(),o++;try{let h=s();g[f]=h}catch(h){if(Yt.Allow.OBJ&t)return g;throw h}u(),e[o]===","&&o++}}catch{if(Yt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},c=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),u(),e[o]===","&&o++}catch{if(Yt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},d=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Yt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(f))}}let g=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(Yt.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,o))}catch{e.substring(g,o)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(h){a(String(h))}}},u=()=>{for(;o<n&&`
|
|
2
|
+
\r `.includes(e[o]);)o++};return s()},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(!gm(r)||mm.test(r)||!mm.test(a))continue;let s=hm(r).length;if(s<1)continue;let l=Kb(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let c=t[p];if(c.trim()===""||!gm(c))break;let d=Gb(Xb(hm(c),s));t[p]!==d&&(t[p]=d,n=!0)}o=p-1}return n?t.join(`
|
|
4
|
+
`):e};var bm="var(--persona-md-table-scroll-fade, 24px)",xm=new WeakSet;function Cm(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 vm(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":bm),e.style.setProperty("--persona-fade-r",r<=1?"0px":bm)}function cd(e){xm.has(e)||(xm.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&vm(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(vm)}var Ln="webmcp:",pd=new Map,wm=e=>{pd.clear();for(let t of e){let n=t.title?.trim();n&&pd.set(t.name,n)}},Oa=e=>pd.get(ei(e)),Zs={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ud=null,Sm=e=>{ud=e};function Mm(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}:${Jb(t.join(""))}`}function Am(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 Jb(e){let t=Am(e,0).toString(36),n=Am(e,2654435761).toString(36);return`${t}.${n}`}var Br=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 Zs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}wm(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=Yb(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return kn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return kn(h?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let a=ei(t),s;try{s=await r.getTools()}catch(h){let S=h instanceof Error?h.message:String(h);return kn(`Failed to read WebMCP registry: ${S}`)}wm(s);let l=s.find(h=>h.name===a);if(!l)return kn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return kn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return kn("Aborted by cancel()");let p=Oa(a),c={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return kn("User declined the tool call.");if(o?.aborted)return kn("Aborted by cancel()");let d=new AbortController,u=!1,g=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await r.executeTool(l,nx(n),{signal:d.signal});return Zb(h)}catch(h){if(u)return kn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return kn("Aborted by cancel()");let S=h instanceof Error?h.message:String(h);return kn(S)}finally{clearTimeout(g),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(ud?await ud():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Zs.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,Zs.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??ex;try{return await n(t)}catch(o){return Zs.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=>Qb(t,o))}},ei=e=>e.startsWith(Ln)?e.slice(Ln.length):e,vo=e=>e.startsWith(Ln),Qb=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Yb=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Zb=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:ox(t)}]}},kn=e=>({isError:!0,content:[{type:"text",text:e}]}),ex=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=tx(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)},Pb=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Rb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ib=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function on(e){return e==="card"?"collapsed":e}function bo(e){return e.split(";",1)[0].trim().toLowerCase()}function Wb(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(bo(r)===t)return{mode:on(a),selector:bo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(bo(r)===o)return{mode:on(a),selector:o}}function sd(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:on(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?bo(t.file.mimeType):void 0,p=l?Wb(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:on(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:on(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:on(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:on(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:on(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Bn(e,t){return sd(e,t).mode}function Ra(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Hb="agent_",Bb="flow_";function am(e){return e.startsWith(Hb)?{kind:"agentId",agentId:e}:e.startsWith(Bb)?{kind:"flowId",flowId:e}:null}function sm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let c=am(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=am(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var xo=ho(Ys(),1);var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var lm=()=>document.createDocumentFragment(),Be=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},Kn=(...e)=>e.filter(Boolean).join(" ");var Wa="ask_user_question",Ia=8,Rr="data-persona-ask-sheet-for",_b="Other",Ub="Other\u2026",cm="Type your own answer here",pm="Send",qb="Next",Vb="Back",zb="Submit all",$b="Skip",jb=3,ld="data-ask-current-index",dd="data-ask-question-count",um="data-ask-answers",cd="data-ask-grouped",fm="data-ask-layout",Gb=e=>e.layout==="pills"?"pills":"rows",Kb=e=>e.getAttribute(fm)==="pills"?"pills":"rows",dm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Xn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Wa,Zs=e=>e?.features?.askUserQuestion??{},Jn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),a=(0,xo.parse)(r,xo.STR|xo.OBJ|xo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},Ha=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ia&&!dm&&(dm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ia}.`)),t.slice(0,Ia)},Xb=e=>Ha(e)[0]??null,Jb=(e,t)=>Ha(e)[t]??null,gm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},hm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Qb=(e,t,n,o)=>{let a=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),n==="rows"){let s=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let c=b("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=hm(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Yb=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Zb=(e,t,n,o)=>{let a=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<jb;d++)a.appendChild(Yb(o));return a}if(p.forEach((d,u)=>{a.appendChild(Qb(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?_b:Ub;if(o==="rows"){let u=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=b("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??cm,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=hm(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??d,a.appendChild(u)}}return a},ym=(e,t)=>{let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??cm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=b("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??pm,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},ex=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},tx=(e,t,n)=>{let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Vb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=b("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??$b,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??zb:n.nextLabel??qb,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Yo=e=>{let t=e.getAttribute(um);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},bm=(e,t)=>{e.setAttribute(um,JSON.stringify(t))},xn=e=>{let t=Number(e.getAttribute(ld)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},nx=(e,t)=>{e.setAttribute(ld,String(Math.max(0,Math.floor(t))))},Ir=e=>{let t=Number(e.getAttribute(dd)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(cd)==="true",ox=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},rx=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ei=(e,t)=>{let{payload:n}=Jn(t),o=Ha(n),r=Yo(e),a={},s=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(s.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),s.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(a[c]=r[p]))}),a},xm=e=>{let t=Yo(e),n=xn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},vm=e=>{if(!vo(e))return;let t=Yo(e),n=xn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},pd=(e,t,n)=>{let o=Zs(n),r=Kb(e),{payload:a,complete:s}=Jn(t),l=vo(e),p=xn(e),c=Ir(e),d=l?Jb(a,p):Xb(a),u=!!d?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof d?.question=="string"?d.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let A=e.querySelector('[data-ask-pill-list="true"]');if(A){let M=Zb(d,o,s,r);A.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(ym(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!E?e.appendChild(ex(o)):(!u||l)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=tx(p,c,o);k?k.replaceWith(M):e.appendChild(M)}else k&&k.remove();xm(e),vm(e)},ax=(e,t,n)=>{let o=Zs(t),r=Gb(o),a=e.toolCall.id,s=Ha(n),l=Math.max(1,s.length),p=l>1,c=ox(e,s),d=p?rx(e,l):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Rr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(dd,String(l)),u.setAttribute(ld,String(d)),u.setAttribute(cd,p?"true":"false"),u.setAttribute(fm,r),bm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),gm(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=b("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=b("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(ym(o,r)),pd(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sx=(e,t,n)=>{let{payload:o}=Jn(t),r=Math.max(1,Ha(o).length);r>Ir(e)&&(e.setAttribute(dd,String(r)),r>1&&!vo(e)&&e.setAttribute(cd,"true")),pd(e,t,n)},Cm=(e,t)=>{let n=b("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=Zs(t);gm(n,o);let r=b("span","persona-ask-stub-label"),{complete:a}=Jn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wr=(e,t,n)=>{if(!n||!Xn(e)||Zs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Rr}]`).forEach(c=>{c.getAttribute(Rr)!==r&&c.remove()});let s=n.querySelector(`[${Rr}="${mm(r)}"]`);if(s){sx(s,e,t);return}let{payload:l}=Jn(e),p=ax(e,t,l);n.appendChild(p)},Co=(e,t)=>{if(!e)return;let n=t?`[${Rr}="${mm(t)}"]`:`[${Rr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},ud=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),wo=(e,t)=>{let n=Yo(e),o=xn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,bm(e,n),xm(e),vm(e)},ti=(e,t,n,o)=>{let r=Ir(e),a=Math.max(0,Math.min(r-1,o));nx(e,a),pd(e,t,n)};var kn="suggest_replies";var fd={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ni={name:kn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:fd,origin:"sdk",annotations:{readOnlyHint:!0}},md=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ba=e=>e.variant==="tool"&&e.toolCall?.name===kn,gd=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},oi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ba(n))continue;let o=gd(n.toolCall?.args);return o.length>0?o:null}return null},wm=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var hd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ia,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},yd={name:Wa,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:hd,origin:"sdk",annotations:{readOnlyHint:!0}},Hr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(yd),wm(e)&&t.push(ni),t};var Qn=ho(Ys(),1),ri=e=>e.replace(/\\n/g,`
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
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,"\\"),Eo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Wx=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},zm=e=>e.status==="complete"?Wx(e):e.status==="pending"?"Waiting":"",Hx=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var $m=e=>e.status==="complete"?Hx(e):"Using tool...",ci=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},za=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 ci(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 ci(t)},Md=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=za(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ui=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Va(o,n.slice(a,s.index),[]),s[1]!==void 0?Va(o,s[1],["bold"]):s[2]!==void 0?Va(o,s[2],["italic"]):s[3]!==void 0&&Va(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Va(o,n.slice(a),[]),o},Va=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bx=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
11
11
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(s);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{let e=dx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ci=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Qn.parse)(n,Qn.STR|Qn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Mm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ri(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ri(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Qn.parse)(a,Qn.STR|Qn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Tm="4.14.0";var Zo=Tm;var px="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function ux(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var xd=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function fx(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Em=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function mx(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Em(n);if(!Em(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Oa(e);return Oa(t)!==null&&s===null?t:e}var er=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??px,this.headers={"Content-Type":"application/json","X-Persona-Version":Zo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??fx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Pr(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=sm(o,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(r)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(xd).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...s,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(d),signal:t.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?rm(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,c=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,d=!1,u;for(let g=0;;g++){if(u=await o({...a&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ui}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let c=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(s,c,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(xd).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(xd).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=P=>{let U=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,x=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,H=P.tools?P.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...P,reasoning:U,toolCall:x,tools:H}},g=P=>{if(P.role!=="assistant"||P.variant)return!0;let U=Array.isArray(P.contentParts)&&P.contentParts.length>0,x=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||U||x||!!P.stopReason},f=P=>{g(P)&&n({type:"message",message:u(P)})},h=null,A=null,E={current:null},k={current:null},M=null,S="",C=new Map,T=new Map,W=new Map,w=new Map,D=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},O=P=>{if(P==null)return null;try{return String(P)}catch{return null}},q=P=>O(P.stepId??P.step_id??P.step??P.parentId??P.flowStepId??P.flow_step_id),Q=P=>O(P.callId??P.call_id??P.requestId??P.request_id??P.toolCallId??P.tool_call_id??P.stepId??P.step_id),de=o,be=!1,De=()=>{if(h)return h;let P,U="",x=M;return!be&&de?(P=de,be=!0,U=r??""):de&&x?P=`${de}_${x}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:P,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},ie=(P,U)=>{F.lastId=U,P&&F.byStep.set(P,U)},ge=(P,U)=>{let x=P.reasoningId??P.id,H=q(P);if(x){let B=String(x);return ie(H,B),B}if(H){let B=F.byStep.get(H);if(B)return F.lastId=B,B}if(F.lastId&&!U)return F.lastId;if(!U)return null;let R=`reason-${d()}`;return ie(H,R),R},ne=P=>{let U=w.get(P);if(U)return U;let x={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:P,status:"streaming",chunks:[]}};return w.set(P,x),f(x),x},le=(P,U)=>{j.lastId=U,P&&j.byCall.set(P,U)},Z=new Set,me=new Map,Ae=new Set,we=new Map,Se=P=>{if(!P)return!1;let U=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return U==="emit_artifact_markdown"||U==="emit_artifact_component"},mt=(P,U)=>{let x=P.toolId??P.id,H=Q(P);if(x){let B=String(x);return le(H,B),B}if(H){let B=j.byCall.get(H);if(B)return j.lastId=B,B}if(j.lastId&&!U)return j.lastId;if(!U)return null;let R=`tool-${d()}`;return le(H,R),R},We=P=>{let U=D.get(P);if(U)return U;let x={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:P,status:"pending"}};return D.set(P,x),f(x),x},_e=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let U=Number(P);if(!Number.isNaN(U)&&Number.isFinite(U))return U;let x=Date.parse(P);if(!Number.isNaN(x))return x}return Date.now()},Xe=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},$e=new Map,Me=new Map,ke=new Map,Je=(P,U,x)=>{let H=ke.get(P);H||(H=[],ke.set(P,H));let R=0,B=H.length;for(;R<B;){let _=R+B>>>1;H[_].seq<U?R=_+1:B=_}H[R]?.seq===U?H[R]={seq:U,text:x}:H.splice(R,0,{seq:U,text:x});let K="";for(let _=0;_<H.length;_++)K+=H[_].text;return K},Dt=(P,U)=>{let x=Xe(U),H=Me.get(P.id),R=mx(H,x);P.rawContent=R;let B=$e.get(P.id),K=Re=>{let Qe=P.content??"";Re.trim()!==""&&(Qe.trim().length===0||Re.startsWith(Qe)||Re.trimStart().startsWith(Qe.trim()))&&(P.content=Re)},_=()=>{if(B){let Re=B.close?.();Re instanceof Promise&&Re.catch(()=>{})}$e.delete(P.id),Me.delete(P.id),P.streaming=!1,f(P)};if(!B){K(x),_();return}let $=Oa(R);if($!==null&&$.trim()!==""){K($),_();return}let Y=Re=>{let Qe=typeof Re=="string"?Re:Re?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let rt=B.getExtractedText();return rt!==null&&rt.trim()!==""?rt:x},je;try{je=B.processChunk(R)}catch{K(x),_();return}if(je instanceof Promise){je.then(Re=>{K(Y(Re)),_()}).catch(()=>{K(x),_()});return}K(Y(je)),_()},Wt=null,Kt=(P,U,x,H)=>{P.rawContent=U,$e.has(P.id)||$e.set(P.id,this.createStreamParser());let R=$e.get(P.id),B=U.trim().startsWith("{")||U.trim().startsWith("[");if(B&&Me.set(P.id,U),R.__isPlainTextParser===!0){P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P);return}let _=R.processChunk(U);if(_ instanceof Promise)_.then($=>{let Y=typeof $=="string"?$:$?.text??null;Y!==null&&Y.trim()!==""?(P.content=Y,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}).catch(()=>{P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P)});else{let $=typeof _=="string"?_:_?.text??null;$!==null&&$.trim()!==""?(P.content=$,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}},wt=(P,U)=>{let x=U??P.content;if(x==null||x===""){P.streaming=!1,f(P);return}let R=Me.get(P.id)??Xe(x);P.rawContent=R;let B=$e.get(P.id),K=null,_=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Oa(R)),K===null)){let $=B.processChunk(R);$ instanceof Promise?(_=!0,$.then(Y=>{let je=typeof Y=="string"?Y:Y?.text??null;je!==null&&(P.content=je,P.streaming=!1,$e.delete(P.id),Me.delete(P.id),f(P))}).catch(()=>{})):K=typeof $=="string"?$:$?.text??null}if(!_){K!==null&&K.trim()!==""?P.content=K:Me.has(P.id)||(P.content=Xe(x));let $=$e.get(P.id);if($){let Y=$.close?.();Y instanceof Promise&&Y.catch(()=>{}),$e.delete(P.id)}Me.delete(P.id),P.streaming=!1,f(P)}},He=(P,U,x)=>{let H=T.get(P);if(H)return H;let R={id:`nested-${U}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:U}};return T.set(P,R),f(R),R},ce=[],et,Pe=new Map,ue=0,ae="agent",Le=!1,it=null,pe=null,ve=new Map,ee=this.config.iterationDisplay??"separate";for(et=()=>{for(let P=0;P<ce.length;P++){let U=ce[P].payloadType,x=ce[P].payload;if(!Le&&ae!=="flow"&&typeof x.stepType=="string"&&(ae="flow"),U==="reasoning_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R),He(H,R,"reasoning");continue}let B=ge(x,!0)??`reason-${d()}`,K=ne(B);K.reasoning=K.reasoning??{id:B,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??_e(x.startedAt??x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(U==="reasoning_delta"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let _=T.get(H),$=x.reasoningText??x.text??x.delta??"";$&&x.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String($)),f(_));continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=ne(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??_e(x.startedAt??x.timestamp);let K=x.reasoningText??x.text??x.delta??"";if(K&&x.hidden!==!0){let _=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(_!==void 0){let $=Je(R,_,String(K));B.reasoning.chunks=[$]}else B.reasoning.chunks.push(String(K))}if(B.reasoning.status=x.done?"complete":"streaming",x.done){B.reasoning.completedAt=_e(x.completedAt??x.timestamp);let _=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-_)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(U==="reasoning_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let $=T.get(H);if($.reasoning){let Y=typeof x.text=="string"?x.text:"";Y&&$.reasoning.chunks.length===0&&$.reasoning.chunks.push(Y),$.reasoning.status="complete",$.streaming=!1,f($)}C.delete(H),T.delete(H);continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=typeof x.text=="string"?x.text:"";!w.get(R)&&(B||x.scope==="loop")&&ne(R);let K=w.get(R);if(K?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),B&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(B),K.reasoning.status="complete",K.reasoning.completedAt=_e(x.completedAt??x.timestamp);let $=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-$),K.streaming=!1,f(K)}let _=q(x);_&&F.byStep.delete(_)}else if(U==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(ue=x.iteration);let H=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??mt(x,!0)??`tool-${d()}`,R=x.toolName??x.name;if(Se(R)){Z.add(H);continue}le(Q(x),H);let B=We(H),K=B.toolCall??{id:H,status:"pending"};K.name=R??K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=K.startedAt??_e(x.startedAt??x.timestamp),K.completedAt=void 0,K.durationMs=void 0,B.toolCall=K,B.streaming=!0,x.executionId&&(B.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(B)}else if(U==="tool_output_delta"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H))continue;let R=We(H),B=R.toolCall??{id:H,status:"running"};B.startedAt=B.startedAt??_e(x.startedAt??x.timestamp);let K=x.text??x.delta??x.message??"";K&&(B.chunks=B.chunks??[],B.chunks.push(String(K))),B.status="running",R.toolCall=B,R.streaming=!0;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R)}else if(U==="tool_complete"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H)){Z.delete(H);continue}let R=We(H),B=R.toolCall??{id:H,status:"running"};B.status="complete",x.result!==void 0&&(B.result=x.result),typeof x.duration=="number"&&(B.duration=x.duration),B.completedAt=_e(x.completedAt??x.timestamp);let K=x.duration??x.executionTime;if(typeof K=="number")B.durationMs=K;else{let Y=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-Y)}R.toolCall=B,R.streaming=!1;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R);let $=Q(x);$&&j.byCall.delete($)}else if(U==="await"&&x.toolName){let H=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,R=H??x.toolId??`local-${d()}`,B=We(R),K=x.toolName,_=x.origin==="webmcp"&&!yo(K)?`webmcp:${K}`:K,$=yo(_),Y=B.toolCall??{id:R,status:"pending"};Y.name=_,Y.args=x.parameters,Y.status=$?"running":"complete",Y.chunks=Y.chunks??[],Y.startedAt=Y.startedAt??_e(x.startedAt??x.timestamp??x.awaitedAt),$?(Y.completedAt=void 0,Y.duration=void 0,Y.durationMs=void 0):Y.completedAt=Y.completedAt??Y.startedAt,B.toolCall=Y,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:x.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(B)}else if(U==="text_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R);continue}let B=h;B&&(ae==="flow"?(wt(B),Wt=B):(B.streaming=!1,f(B)),h=null),M=typeof x.id=="string"?x.id:M,S=""}else if(U==="text_delta"){let H=typeof x.id=="string"?x.id:null,R=H?C.get(H):void 0;if(H&&R){let K=typeof x.delta=="string"?x.delta:"",_=(W.get(H)??"")+K;if(W.set(H,_),_.trim()==="")continue;let $=He(H,R);$.agentMetadata={...$.agentMetadata,executionId:x.executionId,parentToolId:R},Kt($,_,K,void 0);continue}if(M=typeof x.id=="string"?x.id:M,ae==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(S+=K,S.trim()==="")continue;let _=De();_.agentMetadata={executionId:x.executionId,iteration:x.iteration},Kt(_,S,K,void 0),A=_;continue}let B=De();B.content+=x.delta??"",B.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:it??void 0,agentName:pe?.agentName},A=B,f(B)}else if(U==="text_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)){let B=T.get(H);B&&wt(B),C.delete(H),W.delete(H),T.delete(H);continue}let R=h;R&&(ae==="flow"?(wt(R),Wt=R):((R.content??"")===""&&typeof x.text=="string"&&(R.content=x.text),R.streaming=!1,f(R)),h=null),M=null,S=""}else if(U==="step_complete"){let H=x.stepType,R=x.executionType;if(H==="tool"||R==="context")continue;if(x.success===!1){let B=x.error,K=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let B=Wt;Wt=null;let K=x.stopReason,_=x.result?.response;if(B)K&&(B.stopReason=K),_!=null?Dt(B,_):B.streaming!==!1&&($e.delete(B.id),Me.delete(B.id),B.streaming=!1,f(B));else{let $=_!=null&&_!=="";if($||K){let Y=De();K&&(Y.stopReason=K),$?wt(Y,_):(Y.streaming=!1,f(Y))}}continue}}else if(U==="execution_start")ae=x.kind==="flow"?"flow":"agent",Le=!0,ae==="agent"&&(pe={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:_e(x.startedAt)});else if(U==="turn_start"){let H=typeof x.iteration=="number"?x.iteration:ue;if(H!==ue){if(pe&&(pe.currentIteration=H),ee==="separate"&&H>1){let R=h;R&&(R.streaming=!1,f(R),ve.set(H-1,R),h=null)}ue=H}it=typeof x.id=="string"?x.id:null,A=null}else if(U==="tool_input_delta"){let H=x.toolCallId??j.lastId;if(H){let R=D.get(H);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(x.delta??""),f(R))}}else{if(U==="tool_input_complete")continue;if(U==="turn_complete"){let H=x.stopReason,R=h??A;if(H&&R!==null){let B=x.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=H,f(R))}it===x.id&&(it=null)}else if(U==="media_start"){let H=String(x.id);Pe.set(H,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(U==="media_delta"){let H=Pe.get(String(x.id));H&&typeof x.delta=="string"&&H.parts.push(x.delta)}else if(U==="media_complete"){let H=String(x.id),R=Pe.get(H);Pe.delete(H);let B=(typeof x.mediaType=="string"?x.mediaType:void 0)??R?.mediaType??"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,_=typeof x.url=="string"?x.url:R&&R.parts.length>0?R.parts.join(""):void 0,$=null;if(K)$={type:"media",data:K,mediaType:B};else if(_){let Qe=B.toLowerCase();$={type:Qe==="image"||Qe.startsWith("image/")?"image-url":"file-url",url:_,mediaType:B}}let Y=x.toolCallId??R?.toolCallId,je=$?[$]:[],Re=[];for(let Qe of je){if(!Qe||typeof Qe!="object")continue;let rt=Qe,G=typeof rt.type=="string"?rt.type:void 0,Ue=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",he=null,qe="";if(G==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;qe=Ue.length>0?Ue:"application/octet-stream",he=`data:${qe};base64,${Fe}`}else if(G==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else if(G==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else continue;if(he)if(G==="image-url"||qe.startsWith("image/"))Re.push({type:"image",image:he,...qe.includes("/")?{mimeType:qe}:{}});else if(qe.startsWith("audio/"))Re.push({type:"audio",audio:he,mimeType:qe});else if(qe.startsWith("video/"))Re.push({type:"video",video:he,mimeType:qe});else{let Fe=qe||"application/octet-stream";Re.push({type:"file",data:he,mimeType:Fe,filename:ux(Fe)})}}if(Re.length>0){let Qe=d(),rt=Y,Ue={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Qe}`:String(Qe)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Qe,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ue}};f(Ue);let he=h;he&&(he.streaming=!1,f(he)),h=null,E.current=null}}else if(U==="execution_complete"){let H=x.kind??ae;H==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=_e(x.completedAt),pe.stopReason=x.stopReason);let R=h;R&&(H==="flow"&&R.streaming!==!1?wt(R):(R.streaming=!1,f(R)),h=null),M=null,S="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(U==="execution_error"){let H=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(U!=="ping"){if(U==="approval_start"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="step_await"&&x.awaitReason==="approval_required"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="approval_complete"){let H=x.approvalId;if(H){let B={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:x.decision??"approved",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(B)}}else if(U==="artifact_start"||U==="artifact_delta"||U==="artifact_update"||U==="artifact_complete"){if(U==="artifact_start"){let H=x.artifactType,R=String(x.id),B=typeof x.title=="string"?x.title:void 0,K=x.file,_;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(_={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:R,artifactType:H,title:B,component:typeof x.component=="string"?x.component:void 0,..._?{file:_}:{}});let $=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(we.set(R,{markdown:"",title:B,file:_,...$?{props:$}:{}}),!Ae.has(R)){Ae.add(R);let Y=Bn(this.config.features?.artifacts,{artifactType:H,..._?{file:_}:{}}),je=typeof x.component=="string"?x.component:void 0,Re={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ra(Y,{artifactId:R,title:B,artifactType:H,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};me.set(R,Re),f(Re)}}else if(U==="artifact_delta"){let H=String(x.id),R=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:H,artDelta:R});let B=we.get(H);B&&(B.markdown+=R)}else if(U==="artifact_update"){let H=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:H,component:typeof x.component=="string"?x.component:void 0});let R=we.get(String(x.id));R&&(R.props={...R.props??{},...H})}else if(U==="artifact_complete"){let H=String(x.id);n({type:"artifact_complete",id:H});let R=me.get(H);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let K=we.get(H);K?.markdown&&(B.props.markdown=K.markdown),K?.file&&(B.props.file=K.file),B.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(B.props.componentProps=K.props)}R.rawContent=JSON.stringify(B)}catch{}we.delete(H),f(R),me.delete(H)}}}else if(U==="transcript_insert"){let H=x.message;if(!H||typeof H!="object")continue;let R=String(H.id??`msg-${d()}`),B=H.role,_={id:R,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:d()};if(f(_),_.rawContent)try{let Y=JSON.parse(_.rawContent)?.props?.artifactId;typeof Y=="string"&&Ae.add(Y)}catch{}h=null,E.current=null,$e.delete(R),Me.delete(R)}else if(U==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let H=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(H)});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(U==="step_error"||U==="dispatch_error"||U==="flow_error"){let H=null;if(x.error instanceof Error)H=x.error;else if(U==="dispatch_error"){let R=x.message??x.error;R!=null&&R!==""&&(H=new Error(String(R)))}else{let R=x.error;typeof R=="string"&&R!==""?H=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(H=new Error(String(R.message??R)))}if(H){n({type:"error",error:H});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:P,value:U}=await a.read();if(P)break;l+=s.decode(U,{stream:!0});let x=l.split(`
|
|
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(`
|
|
13
13
|
|
|
14
|
-
`);l=
|
|
15
|
-
`),B="message",K="",_=null;for(let Re of R)Re.startsWith("event:")?B=Re.replace("event:","").trim():Re.startsWith("data:")?K+=Re.replace("data:","").trim():Re.startsWith("id:")&&(_=Re.slice(3).trim());let $=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!K){$();continue}let Y;try{Y=JSON.parse(K)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let je=B!=="message"?B:Y.type??"message";if(this.onSSEEvent?.(je,Y),this.parseSSEEvent){E.current=h;let Re=await this.handleCustomSSEEvent(Y,n,E,f,d,k);if(E.current&&E.current!==h&&(h=E.current),Re){$();continue}}ce.push({payloadType:je,payload:Y}),et(),$()}}et()}};function km(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Br(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function So(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function mi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Rm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Mo(e){return{type:"text",text:e}}function Im(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Wm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Hm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Bm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gx=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Yn=[...Bm,...gx];function hx(e){return Bm.includes(e)||e.startsWith("image/")}function gi(e){return hx(e.type)}async function Dm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;gi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Fm(e,t=Yn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function yx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Om(e,t){let n=yx(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var hi=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var Nm=16e3,bx=24e3,xx=4096,vx=1380533830;function Cx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vx?new Uint8Array(e,44):new Uint8Array(e)}function wx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Na=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Nm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:Nm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new hi(bx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${wx(o)}/ws/agents/${encodeURIComponent(t)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor(xx,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Cx(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var tr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function To(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Na(e.runtype);case"browser":if(!tr.isSupported())throw new Error("Browser speech recognition not supported");return new tr(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function yi(e){if(e?.type==="custom"&&e.custom)return To({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return To({type:"runtype",runtype:e.runtype});if(tr.isSupported())return To({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _a(e){try{return yi(e),!0}catch{return!1}}function Dr(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Eo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Dr(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var nr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function vd(e){if(!e)return"";let t=Ax(e);return _m(t!==null?t:e)}function Ax(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function _m(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
14
|
+
`);l=b.pop()??"";for(let W of b){let B=W.split(`
|
|
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,`
|
|
16
16
|
`),t=t.replace(/\n{2,}/g,`
|
|
17
|
-
`),t.trim()}var
|
|
17
|
+
`),t.trim()}var kd=null,lg=e=>{kd=e},Ld=()=>kd?kd():import("./runtype-tts-entry");var Yx=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Zx(e,t){return Yx.some(n=>e[n]!==t[n])}function Pd(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 Ua=e=>({isError:!0,content:[{type:"text",text:e}]}),zm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,$m=e=>yo(e)||e===kn,Fr=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new nr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(yo(n.name)||n.name===kn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new er(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wd().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return _a(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Eo.isSupported()?new Eo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return wd().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(s&&n)return a&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=To(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!Ex(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=o,this.client=new er(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:a,id:s,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=t,f={id:s??(n==="user"?Br():n==="assistant"?So():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,A={id:p??(r==="user"?Br():r==="assistant"?So():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(A)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
|
|
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(`
|
|
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(Mo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(Mo(s)),c.push(...r.contentParts),t.contentParts=c}else a&&(t.llmContent=s);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Br(),a=So();this.activeAssistantMessageId=null;let s=n?.contentParts&&mi(n.contentParts)?fi:"",l={id:r,role:"user",content:o||s,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:a},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=Ad(d,this.config.errorMessage);if(g){let f={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=So();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let s=Ad(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let a of this.messages)a.streaming&&a.id!==o&&(a.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(a=>a.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=s??{};c.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=d[f],A=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[a]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==kn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let u=`${t}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let g=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===kn)return{dedupeKey:u,resumeKey:f,output:md(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let A=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),E;if(!A)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await A}catch(k){let M=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));return M||this.callbacks.onError?.(k instanceof Error?k:new Error(String(k))),this.markWebMcpToolComplete(p,Ua(M?"Aborted by cancel()":zm(k)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ua("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(t,p,{signal:a.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===kn?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let d of l)this.markWebMcpToolComplete(d.toolMessage,Ua("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(h)}catch(A){this.callbacks.onError?.(A instanceof Error?A:new Error(String(A)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===kn,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=md():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ua("Aborted by cancel()"),s);return}let A=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,A,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let A=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||A||p.aborted)&&this.markWebMcpToolComplete(t,Ua(A||p.aborted?"Aborted by cancel()":zm(h)),s),A||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Bn(this.config.features?.artifacts,t),r=Ra(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(s=>s.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Bn(this.config.features?.artifacts,n),a=Ra(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==a&&(o.rawContent=a,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Vm(),qm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Ad(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=So(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=vd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Dr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=vd(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,u=n.approval;s.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&$m(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),g=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&$m(f)&&r.toolCall?.status==="complete";(u||g||h)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var Sd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Md=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Ed=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var kd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Ld=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Pd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Rd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Id=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Wd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Hd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Bd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Dd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Fd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Od=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Nd=[["path",{d:"M20 6 9 17l-5-5"}]];var _d=[["path",{d:"m6 9 6 6 6-6"}]];var Ud=[["path",{d:"m15 18-6-6 6-6"}]];var qd=[["path",{d:"m9 18 6-6-6-6"}]];var Vd=[["path",{d:"m18 15-6-6-6 6"}]];var bi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var zd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var $d=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var vi=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Gd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Xd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Jd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Qd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Yd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Zd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var ec=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var tc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var nc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var oc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var rc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var ac=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var sc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var ic=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var lc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Ai=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var dc=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var cc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var pc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var uc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var fc=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var mc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Si=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var gc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var yc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var bc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var xc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var Mi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var vc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Cc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var wc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Ac=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Sc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Mc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Tc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Ec=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var kc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Lc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Pc=[["path",{d:"M5 12h14"}]];var Rc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Ic=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Wc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Hc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Dc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Fc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Oc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Nc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var _c=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Uc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var qc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Vc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var zc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var $c=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var jc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Gc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Kc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Xc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Jc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Ti=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Qc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Yc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Zc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var ep=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Ei=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var tp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var np=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var op=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var rp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var ap=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var sp=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var ip=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var lp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var dp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var cp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var ki=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var pp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var up=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var fp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var mp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var gp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var hp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var yp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var bp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var kx={activity:Sd,"arrow-down":Md,"arrow-up":Ld,"arrow-up-right":kd,bot:Hd,"chevron-down":_d,"chevron-up":Vd,"chevron-right":qd,"chevron-left":Ud,check:Nd,clipboard:$d,"clipboard-copy":zd,"code-xml":vi,copy:Gd,file:oc,"file-code":ec,"file-spreadsheet":tc,"file-text":nc,"image-plus":gc,loader:vc,"loader-circle":Mi,mic:kc,paperclip:Hc,"refresh-cw":qc,search:$c,send:jc,"shield-alert":Xc,"shield-check":Jc,"shield-x":Ti,square:tp,"thumbs-down":sp,"thumbs-up":ip,upload:up,"volume-2":mp,x:yp,user:fp,mail:wc,phone:Oc,calendar:Fd,clock:jd,building:Bd,"map-pin":Ac,lock:Cc,key:bc,"credit-card":Kd,"at-sign":Pd,hash:pc,globe:cc,link:xc,"circle-check":bi,"circle-x":xi,"triangle-alert":ki,info:yc,ban:Rd,shield:Qc,"arrow-left":Td,"arrow-right":Ed,"external-link":Yd,ellipsis:wi,"ellipsis-vertical":Ci,menu:Mc,house:Si,plus:_c,minus:Pc,pencil:Dc,trash:cp,"trash-2":dp,save:zc,download:Jd,share:Kc,funnel:Ai,settings:Gc,"rotate-cw":Vc,maximize:Sc,minimize:Lc,"shopping-cart":Zc,"shopping-bag":Yc,package:Wc,truck:pp,tag:ap,gift:dc,receipt:Uc,wallet:hp,store:op,"dollar-sign":Xd,percent:Fc,play:Nc,pause:Bc,"volume-x":gp,camera:Od,image:hc,film:ac,headphones:uc,"message-circle":Tc,"message-square":Ec,bell:Id,heart:fc,star:np,eye:Zd,"eye-off":Qd,bookmark:Wd,"calendar-days":Dd,history:mc,timer:lp,folder:lc,"folder-open":ic,files:rc,sparkles:Ei,zap:bp,sun:rp,moon:Ic,flag:sc,monitor:Rc,smartphone:ep},oe=(e,t=24,n="currentColor",o=2)=>{let r=kx[e];return r?Lx(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Lx(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var Li={allowedTypes:Yn,maxFileSize:10*1024*1024,maxFiles:4};function Px(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Rx(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var or=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Li.allowedTypes,maxFileSize:t.maxFileSize??Li.maxFileSize,maxFiles:t.maxFiles??Li.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Li.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Fm(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Dm(n),a=gi(n)?URL.createObjectURL(n):null,s={id:Px(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=gi(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let s=b("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=b("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=Rx(t.file.type),p=oe(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=b("span");c.textContent=Om(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",s.appendChild(c),o.appendChild(s)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let a=oe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var jm=/\s/;function Ix(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
|
|
24
|
-
`:o===""||
|
|
25
|
-
`||s==="\uFFFC"||!r&&
|
|
26
|
-
`).some(
|
|
27
|
-
`)[0]).startsWith(C.trigger):!1),a=(S,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:C}))}catch{}},s=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=e.textarea,d=null,u=null,g=null,f=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=wp().then(C=>(l=C.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:d??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:M,emit:a}),l)).catch(C=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",C),p===S&&(p=null),null));return p=S,S},A=()=>{eg().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:W=>qa(W,{render:t.renderMentionToken}),onMentionRemoved:W=>l?.untrackMention(W)});d=C.input,u=C.destroy;let T=c;T.replaceWith(C.element),c=C.element,f={next:C.element,prev:T},g?.(C.element,T),l?l.rebindComposer(C.input):p&&p.then(W=>W?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&A();let E=[],k=new Map;for(let S of n){if(!S.showButton)continue;let C=Qm({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(S.trigger))}});E.push(C),k.set(S.trigger,C.button)}let M=(S,C,T)=>{let W=k.get(C);W&&(W.setAttribute("aria-expanded",S?"true":"false"),S?W.setAttribute("aria-controls",T):W.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!Km(S))return;let C=c,T=C.selectionStart??0;Gm(C.value,T,n)&&h().then(W=>W?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!f){let C=c,T=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||T)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await h())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{wp().catch(()=>{})},onComposerSwap:S=>{g=S,f&&S(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let S of E)S.wrapper.remove();s.remove()}}}var ng=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];ng(a)&&ng(r)?n[o]=Va(a,r):n[o]=r}return n}var pn="min(440px, calc(100vw - 24px))",Ri="440px",Ux={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:pn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},st={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ux,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function og(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function Or(e){return e?{...st,...e,theme:og(st.theme,e.theme),darkTheme:og(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,a=st.features?.scrollBehavior,s=e.features?.scrollBehavior,l=st.features?.streamAnimation,p=e.features?.streamAnimation,c=st.features?.askUserQuestion,d=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},A=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...st.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...A!==void 0?{askUserQuestion:A}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}var Ii="16px",Wi="transparent",Ap={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Sp={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Mp={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:pn,maxWidth:Ri,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ii,canvasBackground:Wi},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Qt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Qt(e,o):o}function Hi(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=Qt(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Tp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function rg(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=rg(a,r):n[o]=r}return n}function qx(e,t){return t?rg(e,t):e}function za(e,t={}){let n={palette:Ap,semantic:Sp,components:Mp},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:qx(n.components,e?.components)};if(t.validate!==!1){let r=Tp(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Bi(e){let t=Hi(e),n={};for(let[w,D]of Object.entries(t)){let F=w.replace(/\./g,"-");n[`--persona-${F}`]=D.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Ii,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Wi,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=e.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let g=c?.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let f=c?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let D=Qt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=D}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Qt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let h=c?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Qt(e,h.background)??h.background));let A=n["--persona-surface"],E=n["--persona-container"],k=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",C=!E||E===A,T=C?k:E,W=C?M:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??T,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??W,C&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??T,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??T,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??T,n}var ag={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Vx={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},sg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$a=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",zx=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":$a()},Di=e=>zx(e),$x=e=>za(e),jx=e=>za({...e,palette:{...e?.palette,colors:{...Vx.colors,...e?.palette?.colors}}},{validate:!1}),ko=e=>{let t=Di(e),n=sg(e?.theme),o=sg(e?.darkTheme);return t==="dark"?jx(Va(n??{},o??{})):$x(n)},Gx=e=>Bi(e),rr=(e,t)=>{let n=ko(t),o=Gx(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Di(t))},Nr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e($a())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e($a());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Dn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function ig(e){let t=Dn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Fi(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
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===""||fg.test(o)}function av(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 rv(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
|
|
25
|
+
`||s==="\uFFFC"||!r&&fg.test(s))return null;a--}return null}function mg(e,t,n){for(let o of n){let r=av(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function gg(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function hg(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Gt=1e5,Fi=Gt+1;var sv=8,iv=8,Ep=10,kp=new WeakMap,yg=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,lv=e=>{let t=e.getRootNode?.();return yg(t)?t:e.ownerDocument.body},Lp=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ut(e){kp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=sv,viewportPadding:s=iv}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,g=!1,f=!1,h=!1,S=()=>(typeof o=="function"?o():o).trim(),k=()=>{u?.(),u=null,c?.remove(),c=null,d=null},P=()=>{if(!c)return;let K=l(),D=p(),q=t.getBoundingClientRect(),Y=c.getBoundingClientRect(),de=K.documentElement.clientWidth||D.innerWidth,be=K.documentElement.clientHeight||D.innerHeight,pe=de-s-Y.width,te=q.left+q.width/2-Y.width/2,me=Lp(te,s,pe),oe=q.top-s,le=be-s-q.bottom,Z=Y.height+a,he=oe>=Z||oe>=le?"top":"bottom",Ce=he==="top"?q.top-a-Y.height:q.bottom+a,ve=be-s-Y.height,we=Lp(Ce,s,ve),Ee=q.left+q.width/2,ke=Math.max(Ep,Y.width-Ep),Se=Lp(Ee-me,Ep,ke);c.dataset.placement=he,c.style.left=`${me}px`,c.style.top=`${we}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${Se}px`)},M=()=>{if(h||!r||c||!t.isConnected)return;let K=S(),D=lv(t);if(!K||!D)return;let q=l(),Y=p();c=q.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Fi),d=q.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=K,c.appendChild(d);let de=q.createElement("span");de.className="persona-control-tooltip__arrow",c.appendChild(de),D.appendChild(c),P(),c.dataset.state="open";let be=()=>{if(!t.isConnected){k();return}d&&(d.textContent=S()),P()};Y.addEventListener("scroll",be,!0),Y.addEventListener("resize",be);let pe=t.getRootNode(),te=yg(pe)?pe:q.documentElement,me=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||k()});me?.observe(te,{childList:!0,subtree:!0}),u=()=>{Y.removeEventListener("scroll",be,!0),Y.removeEventListener("resize",be),me?.disconnect()}},A=()=>{g||f?M():k()},C=()=>{let K=p();(!K.matchMedia||!K.matchMedia("(hover: none)").matches)&&(g=!0,A())},E=()=>{g=!1,A()},R=()=>{f=!0,A()},w=()=>{f=!1,A()},H=K=>{K.key==="Escape"&&(g=!1,f=!1,k())};n.addEventListener("mouseenter",C),n.addEventListener("mouseleave",E),t.addEventListener("focus",R),t.addEventListener("blur",w),t.addEventListener("keydown",H);let F={get isOpen(){return c!==null},show:M,hide:k,reposition:P,destroy:()=>{h||(h=!0,k(),n.removeEventListener("mouseenter",C),n.removeEventListener("mouseleave",E),t.removeEventListener("focus",R),t.removeEventListener("blur",w),t.removeEventListener("keydown",H),kp.delete(t))}};return kp.set(t,F),F}function bg(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,a=Math.round(r*.6),s=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=x("div","persona-send-button-wrapper"),c=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),d=ae(s,a,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),Ut({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:dv,load:cv}=Ir({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),xg=dv,Pp=cv;var{setLoader:pv,load:uv}=Ir({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),vg=pv,Cg=uv;function Xa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ie("span",{className:Qn("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=x("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ie("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function wg(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=hg(t).filter(A=>A.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(A=>A.sources.some(C=>typeof C.matchCommand=="function")),r=A=>o.some(C=>C.trigger?C.position==="line-start"?A.split(`
|
|
26
|
+
`).some(R=>R.startsWith(C.trigger)):(C.position==="anywhere"?A:A.split(`
|
|
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(`
|
|
28
28
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
29
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
30
|
-
`).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:g,elapsedMs:p,content:()=>c?"":d,surface:n};try{let
|
|
29
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Za(e){let t=kg(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 Wo(e){switch(Za(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=kg(e.path);return t?t.toUpperCase():"File"}}}function Lg(e){let t=e.markdown??"";return e.file?{filename:Nn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:zi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Bp="http://www.w3.org/2000/svg";function Pg(e){let t=document.createElementNS(Bp,"svg");t.setAttribute("class",Qn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Bp,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Bp,"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 Ho=(e,t,n)=>{let o=n;for(let r of t){let a=x("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function Rg(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)),Ho(e,t,0)}var Dp="persona-artifact-status-label",Ig="persona-artifact-status-detail",Wg="data-artifact-status-label",Fp=new Map,Hg=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function $r(e){e&&Fp.delete(e)}function vv(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Wo(t):e.artifactType==="component"?"Component":"Document"}function jr(e,t,n){let o=vv(e),r=`Generating ${o.toLowerCase()}...`,a=t?.statusLabel;if(typeof a=="string")return{label:a};if(typeof a!="function")return{label:r};let s=e.id,l=Fp.get(s);e.status!=="complete"&&l===void 0&&(l=Hg(),Fp.set(s,l));let p=l===void 0?0:Math.max(0,Hg()-l),c=e.artifactType==="component",d=!c&&typeof e.markdown=="string"?e.markdown:"",u=c?0:d.length,g=c||d===""?0:d.split(`
|
|
30
|
+
`).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:g,elapsedMs:p,content:()=>c?"":d,surface:n};try{let S=a(h);return typeof S=="string"?{label:S}:S&&typeof S=="object"&&typeof S.label=="string"?{label:S.label,detail:typeof S.detail=="string"?S.detail:void 0}:{label:r}}catch{return{label:r}}}function Cv(e){e.className=Dp,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 cr(e,t,n){let o=e.querySelector(`:scope > .${Dp}`);o||(o=x("span",Dp),e.appendChild(o)),o.getAttribute(Wg)!==t.label&&(Cv(o),Rg(o,t.label,n),o.setAttribute(Wg,t.label));let r=e.querySelector(`:scope > .${Ig}`),a=t.detail;a?(r||(r=x("span",Ig),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var wv={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"},Av=15e4,$i={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 Sv(e,t){let n=(e||"").trim().toLowerCase();if(n&&$i[n])return $i[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if($i[r])return $i[r]}}return null}function ji(e,t){let n=[],o=0,r=0,a=s=>{s>r&&n.push({type:"plain",value:e.slice(r,s)})};for(;o<e.length;){let s=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);if(p&&p.index===o&&p[0].length>0){a(o);let c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var Mv=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"]),Tv=[{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=>Mv.has(e)?"keyword":"plain"}];function Bg(e){return ji(e,Tv)}var Ev=[{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 kv(e){let t=ji(e,Ev);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 Lv=[{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 Dg(e){let t=ji(e,Lv),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 Pv=[{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 Rv(e){let t=[],n=(a,s)=>{s&&t.push({type:a,value:s})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let s=e.indexOf("-->",r+4),l=s===-1?o:s+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let s=e.indexOf(">",r),l=s===-1?o:s+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let s=e.indexOf(">",r),l=s===-1?o:s+1,p=e.slice(r,l);for(let d of ji(p,Pv))t.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),g=new RegExp("</\\s*"+d+"\\s*>","i").exec(e.slice(r)),f=g?r+g.index:o,h=e.slice(r,f),S=d==="script"?Bg(h):Dg(h);for(let k of S)t.push(k);r=f}continue}let a=e.indexOf("<",r);if(a===r)n("plain",e[r]),r+=1;else{let s=a===-1?o:a;n("plain",e.slice(r,s)),r=s}}return t}function Iv(e,t){switch(t){case"html":return Rv(e);case"css":return Dg(e);case"js":return Bg(e);case"json":return kv(e)}}function Wv(e){let t=Lm(),n=x("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=wv[r];if(s){let l=x("span",s);l.textContent=a,n.appendChild(l)}else n.appendChild(document.createTextNode(a))};for(let r of e){let a=r.value.split(`
|
|
31
31
|
`);for(let s=0;s<a.length;s+=1)s>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
32
|
-
`)),n=b("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function hg(e,t,n){let o=e.length<=Qx?Yx(t,n):null,r=o?sv(e,o):[{type:"plain",value:e}];return iv(r)}function Ro(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=b("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Pi)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");s.appendChild(E)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let E=oe(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let A=document.createElement("span");A.textContent=f.label,h.appendChild(A),h.addEventListener("click",E=>{E.stopPropagation(),d(),n(f.id)}),s.appendChild(h)}let l=null;function p(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function c(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){s.classList.add("persona-hidden"),l?.(),l=null}function u(){s.classList.contains("persona-hidden")?c():d()}function g(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:c,hide:d,toggle:u,destroy:g}}function Mt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=b("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=oe(t,o??16,"currentColor",r??2);if(c&&p.appendChild(c),s&&p.addEventListener("click",s),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Zn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,s&&(c+=" "+s);let d=b("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=oe(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=b("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[g,f]of Object.entries(p))d.setAttribute(g,f);return d}function qr(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=b("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===s?"true":"false")}for(let d of t){let u;d.icon?u=Mt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{s=d.id,p(),o(d.id)}}):(u=b("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{s=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===s?"true":"false"),l.push({id:d.id,btn:u}),a.appendChild(u)}function c(d){s=d,p()}return{element:a,setSelected:c}}function _i(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=b("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let d=b("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=oe(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=Ro({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:a,portal:s});return s||c.appendChild(g.element),c.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var Ui="persona-artifact-custom-action-btn";function Vr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Ui+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+Ui+(n?" persona-artifact-doc-icon-btn":"");o=b("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Zn({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-copy-btn":"")}):o=Mt({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ga(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function yg(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Dn(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,c=n?Lo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&d.setAttribute("data-open-artifact",a);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let g=document.createElement("div");g.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let A=t?.config?.features?.artifacts,E={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},k=Ur(E,A,"card");ar(h,k,A)}else a&&_r(a),h.textContent=c;if(g.append(f,h),d.append(u,g),s==="complete"){let A=t?.config?.features?.artifacts?.cardActions;if(A&&A.length>0){let k={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let M of A)try{if(M.visible===void 0||M.visible(k)){let S=Vr(M);S.setAttribute("data-artifact-custom-action",M.id),S.className=`${S.className} persona-flex-shrink-0`,d.append(S)}}catch{}}let E=Zn({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",a),d.append(E)}return d}var qi=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>yg(e,t)});if(l)return l}return yg(e,t)};var Io=new WeakMap;function Pp(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let a=Io.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function wg(e){return Io.has(e)}function lv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let s=e.componentProps,l=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let a=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...a?{file:a}:{},...r?{presentation:r}:{}}}function bg(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Dn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function dv(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var xg=180,cv=240,pv=.8,uv=300,fv=500,mv="cubic-bezier(0.2, 0, 0, 1)",vg=240,gv=.35;function hv(e,t,n){let{swap:o,onSettled:r}=n,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:xg,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let k of s)k.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let c=Math.abs(t-p),d=Math.round(Math.min(fv,Math.max(uv,cv+c*pv))),u=Math.round(d*gv),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:vg,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:mv});e.style.height=`${p}px`;let A=!1,E=()=>{A||(A=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(d,u+vg)+120)},xg)}function yv(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ka="--persona-artifact-inline-body-height";function bv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,c,d,u=t?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let g=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:g,completeDisplay:f}}function Cg(e,t){let n=lv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=yv(o),p=o?.inlineActions??[],c=bv(o),d=c.completeDisplay==="card",u=null,g=n,f=b("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let h=ne=>qi(dv(ne),t),A=ne=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Ka),f.replaceChildren(h(ne)),Io.set(f,le=>{f.replaceChildren(h(le))})};if(d&&n.status==="complete")return A(n),f;let E=Vi(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),k=b("div","persona-artifact-inline-body");k.appendChild(E.el);let M=ne=>{let le=ne.status!=="complete",Z=le?c.streamingHeight:c.completeHeight,me=typeof Z=="number";me?f.style.setProperty(Ka,`${Z}px`):f.style.removeProperty(Ka);let Ae=!!E.el.querySelector(".persona-code-pre"),we=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",Ae),k.classList.toggle("persona-artifact-inline-body--sized",me&&we),k.classList.toggle("persona-artifact-inline-body--cap",!le&&!we&&typeof c.completeHeight=="number")},S=n.status,C=(ne,le)=>{S!=="complete"&&ne.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Ka,`${c.completeHeight}px`):f.style.removeProperty(Ka),Sg(k,le?.suppressTransition?"none":c.transition,ne.id,()=>{E.update(ne),M(ne)})):E.update(ne),M(ne),S=ne.status};M(n);let T=c.overflow==="clip"&&s&&!!n.id;if(T&&(k.setAttribute("data-expand-artifact-inline",n.id),k.setAttribute("role","button"),k.setAttribute("tabindex","0"),k.classList.add("persona-cursor-pointer"),k.setAttribute("aria-label",`Open ${bg(n).title} in panel`)),!r)return f.appendChild(k),Io.set(f,C),f;let W=b("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=b("div","persona-artifact-inline-chrome-lead"),D=b("span","persona-flex persona-items-center persona-flex-shrink-0"),F=oe("file-text",16,"currentColor",2);F&&D.appendChild(F);let j=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=b("span","persona-artifact-inline-type");w.append(D,j,O);let q=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,be=l?qr({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:de(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==de()&&(u=le,E.update(g),M(g))}}):null,De=a?Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let ie=s?Mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ie&&n.id&&ie.setAttribute("data-expand-artifact-inline",n.id),q.appendChild(Q),be&&q.appendChild(be.element),De&&q.appendChild(De),ie&&q.appendChild(ie),W.append(w,q),f.append(W,k);let ge=ne=>{let{title:le,typeLabel:Z}=bg(ne);j.textContent=le,j.title=le,T&&k.setAttribute("aria-label",`Open ${le} in panel`);let me=ne.status!=="complete";if(me){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let Ae=Ur(ne,o,"inline-chrome");ar(O,Ae,o)}else _r(ne.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(De&&De.classList.toggle("persona-hidden",me),be){let Ae=ne.artifactType==="markdown"?ne.file:void 0,we=!1;if(!me&&Ae&&c.viewMode!=="source"){let Se=ja(Ae);Se==="markdown"?we=!0:(Se==="html"||Se==="svg")&&(we=o?.filePreview?.enabled!==!1)}be.element.classList.toggle("persona-hidden",!we),be.setSelected(de())}if(Q.replaceChildren(),!me&&p.length>0){let Ae=Ga(ne);if(Ae)for(let we of p)try{if(we.visible===void 0||we.visible(Ae)){let Se=Vr(we,{documentChrome:!0});Se.setAttribute("data-artifact-custom-action",we.id),Se.classList.add("persona-flex-shrink-0"),Q.appendChild(Se)}}catch{}}};return ge(n),Io.set(f,(ne,le)=>{if(d&&S!=="complete"&&ne.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;S="complete";let me=ne,Ae=!1,we=Se=>{me=Se,Ae=!0};Io.set(f,we),hv(f,Z,{swap:()=>{A(me),Ae=!1,Io.set(f,we)},onSettled:()=>{Ae?A(me):Io.set(f,Se=>{f.replaceChildren(h(Se))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(u=null),g=ne,C(ne,le),ge(ne)}),f}var Ag=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Cg(e,t)});if(l)return l}return Cg(e,t)};var Rp=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Ln=new Rp;Ln.register("PersonaArtifactCard",qi,{bubbleChrome:!1});Ln.register("PersonaArtifactInline",Ag,{bubbleChrome:!1});function Xa(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Fi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Ip=!1;function xv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Sg(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof r!="function"||Ip||a){o();return}Ip=!0;let s=xv(n);e.style.setProperty("view-transition-name",s);let l=()=>{Ip=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var vv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Cv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function wv(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Av(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Sv=220;function Mv(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Tv(e){return`
|
|
33
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Ev(e,t,n){let o=b("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=b("div","persona-artifact-frame-loading-indicator");r.appendChild(dg());let a=null;return n.label!==!1&&(a=b("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function kv(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(S=>clearTimeout(S)),c.clear()},u=(S,C)=>{let T=setTimeout(()=>{c.delete(T),S()},C);c.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let S=Ev(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Sv))},A=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",M)},E=()=>{if(p||(p=!0,A(),d(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?u(h,S):h()};function k(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&E()}function M(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",k):t.addEventListener("load",M),()=>{p=!0,d(),A(),g()}}function Vi(e,t){let{config:n}=t,o=t.registry??Ln,r=t.bodyLayout,a=n.markdown?Qo(n.markdown):null,s=Lr(n.sanitize),l=e,p=!1,c=ie=>{let ge=Gn()!==null;a&&!ge&&!p&&(p=!0,kr(()=>De(l)));let ne=a?a(ie):Hn(ie);return a&&ge&&s?s(ne):ne},d=b("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},A=null,E=null,k=null,M=!1,S=()=>{A=null,E=null,k=null,M=!1},C=null,T=null,W=()=>{C=null,T=null},w=40,D=0,F=ie=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ie()):setTimeout(ie,0),j=ie=>ie.scrollHeight-ie.clientHeight-ie.scrollTop<=w,O=ie=>{if(!r)return;let ge=ie.scrollHeight-ie.clientHeight>1,ne=ie.scrollHeight-ie.clientHeight-ie.scrollTop;ie.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ie.scrollTop>1),ie.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ne>1)},q=ie=>{D||(D=F(()=>{D=0,ie.scrollTop=ie.scrollHeight,O(ie)}))},Q=(ie,ge,ne,le)=>{let Z=!!r,me=ne.id+"|"+(Z?"w":"p");if(!A||k!==me||A.parentElement!==d){h(),W(),d.replaceChildren();let Se=b("pre",vv+" persona-code-pre"),mt=b("code","persona-code");if(Se.appendChild(mt),Z){let We=b("div","persona-artifact-source-window");if(We.appendChild(Se),d.appendChild(We),!(r?.overflow==="clip")&&typeof We.addEventListener=="function"){let Xe=()=>We.scrollHeight-We.clientHeight>1;We.addEventListener("scroll",()=>{j(We)&&(M=!1),O(We)},{passive:!0}),We.addEventListener("wheel",$e=>{Xe()&&$e.deltaY<0&&(M=!0)},{passive:!0}),We.addEventListener("touchmove",()=>{Xe()&&(M=!0)},{passive:!0})}A=We}else d.appendChild(Se),A=Se;E=mt,k=me}let Ae=Z?A:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",le),Ae.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let we=Ae?j(Ae):!0;if(E.replaceChildren(hg(ie,ge?.language,ge?.path)),Ae){let Se=ne.status!=="complete";le&&Se&&r?.followOutput&&!M&&we?q(Ae):Se||(M=!1),O(Ae)}},de=ie=>{h(),S(),W(),d.replaceChildren();let ge=b("div",Cv);ge.innerHTML=c(ie),d.appendChild(ge)},be=ie=>{let ge=ie.id,ne=n.features?.artifacts,le=Ur(ie,ne,"status-body");if(C&&T===ge&&C.parentElement===d){let Ae=C.querySelector(".persona-artifact-status-view-text");Ae&&ar(Ae,le,ne);return}h(),S(),d.replaceChildren();let Z=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");ar(me,le,ne),Z.appendChild(me),d.appendChild(Z),C=Z,T=ge},De=ie=>{l=ie;let ge=t.resolveViewMode?.(ie)??r?.viewMode??"rendered",ne=ie.artifactType==="markdown"?ie.file:void 0,le=ie.status!=="complete";le||_r(ie.id);let Z=le?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){be(ie);return}if(ne){let we=Fi(ie.markdown??""),Se=ja(ne),mt=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ge==="rendered"&&mt&&(Se==="html"||Se==="svg")){let _e=ie.id+"\0"+we;if(u&&g===_e&&u.parentElement===d)return;S(),W(),h(),d.replaceChildren();let Xe=n.features?.artifacts?.filePreview,$e=Xe?.iframeSandbox??"allow-scripts";!Xe?.dangerouslyAllowSameOrigin&&$e.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),$e=$e.split(/\s+/).filter(Wt=>Wt&&Wt!=="allow-same-origin").join(" "));let Me=Av(Xe?.loading),ke=b("div","persona-artifact-frame"),Je=b("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",$e),Je.setAttribute("data-artifact-id",ie.id);let Dt=null;Me.enabled&&Me.injectReadySignal?(Dt=Mv(),Je.srcdoc=we+Tv(Dt)):Je.srcdoc=we,ke.appendChild(Je),d.appendChild(ke),Me.enabled&&(f=kv(ke,Je,Dt,Me,ie.id,n)),u=ke,g=_e;return}if(h(),!le&&Se==="markdown"&&ge==="rendered"){de(we);return}Q(we,{language:ne.language,path:ne.path},ie,me);return}if(ie.artifactType==="markdown"){if(ge==="source"){h(),Q(ie.markdown??"",void 0,ie,me);return}de(ie.markdown??"");return}h(),S(),W(),d.replaceChildren();let Ae=ie.component?o.get(ie.component):void 0;if(Ae){let Se={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let mt=Ae(ie.props??{},Se);if(mt){d.appendChild(mt);return}}catch{}}d.appendChild(wv(ie))};return De(e),{el:d,update(ie){De(ie)}}}var Mg=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,f,h={}){g=d(g);let A=u(f),E=c(g,A,h),k=r(E,()=>l(E,g,A,M=>M.morphStyle==="innerHTML"?(a(M,g,A),Array.from(g.childNodes)):o(M,g,A)));return E.pantry.remove(),k}function o(g,f,h){let A=u(f);return a(g,A,h,f,f.nextSibling),Array.from(A.childNodes)}function r(g,f){if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:A,selectionStart:E,selectionEnd:k}=h,M=f();return A&&A!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${A}"]`),h?.focus()),h&&!h.selectionEnd&&k&&h.setSelectionRange(E,k),M}let a=(function(){function g(C,T,W,w=null,D=null){T instanceof HTMLTemplateElement&&W instanceof HTMLTemplateElement&&(T=T.content,W=W.content),w||(w=T.firstChild);for(let F of W.childNodes){if(w&&w!=D){let O=h(C,F,w,D);if(O){O!==w&&E(C,w,O),s(O,F,C),w=O.nextSibling;continue}}if(F instanceof Element){let O=F.getAttribute("id");if(C.persistentIds.has(O)){let q=k(T,O,w,C);s(q,F,C),w=q.nextSibling;continue}}let j=f(T,F,w,C);j&&(w=j.nextSibling)}for(;w&&w!=D;){let F=w;w=w.nextSibling,A(C,F)}}function f(C,T,W,w){if(w.callbacks.beforeNodeAdded(T)===!1)return null;if(w.idMap.has(T)){let D=document.createElement(T.tagName);return C.insertBefore(D,W),s(D,T,w),w.callbacks.afterNodeAdded(D),D}else{let D=document.importNode(T,!0);return C.insertBefore(D,W),w.callbacks.afterNodeAdded(D),D}}let h=(function(){function C(w,D,F,j){let O=null,q=D.nextSibling,Q=0,de=F;for(;de&&de!=j;){if(W(de,D)){if(T(w,de,D))return de;O===null&&(w.idMap.has(de)||(O=de))}if(O===null&&q&&W(de,q)&&(Q++,q=q.nextSibling,Q>=2&&(O=void 0)),w.activeElementAndParents.includes(de))break;de=de.nextSibling}return O||null}function T(w,D,F){let j=w.idMap.get(D),O=w.idMap.get(F);if(!O||!j)return!1;for(let q of j)if(O.has(q))return!0;return!1}function W(w,D){let F=w,j=D;return F.nodeType===j.nodeType&&F.tagName===j.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===j.getAttribute?.("id"))}return C})();function A(C,T){if(C.idMap.has(T))S(C.pantry,T,null);else{if(C.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),C.callbacks.afterNodeRemoved(T)}}function E(C,T,W){let w=T;for(;w&&w!==W;){let D=w;w=w.nextSibling,A(C,D)}return w}function k(C,T,W,w){let D=w.target.getAttribute?.("id")===T&&w.target||w.target.querySelector(`[id="${T}"]`)||w.pantry.querySelector(`[id="${T}"]`);return M(D,w),S(C,D,W),D}function M(C,T){let W=C.getAttribute("id");for(;C=C.parentNode;){let w=T.idMap.get(C);w&&(w.delete(W),w.size||T.idMap.delete(C))}}function S(C,T,W){if(C.moveBefore)try{C.moveBefore(T,W)}catch{C.insertBefore(T,W)}else C.insertBefore(T,W)}return g})(),s=(function(){function g(M,S,C){return C.ignoreActive&&M===document.activeElement?null:(C.callbacks.beforeNodeMorphed(M,S)===!1||(M instanceof HTMLHeadElement&&C.head.ignore||(M instanceof HTMLHeadElement&&C.head.style!=="morph"?p(M,S,C):(f(M,S,C),k(M,C)||a(C,M,S))),C.callbacks.afterNodeMorphed(M,S)),M)}function f(M,S,C){let T=S.nodeType;if(T===1){let W=M,w=S,D=W.attributes,F=w.attributes;for(let j of F)E(j.name,W,"update",C)||W.getAttribute(j.name)!==j.value&&W.setAttribute(j.name,j.value);for(let j=D.length-1;0<=j;j--){let O=D[j];if(O&&!w.hasAttribute(O.name)){if(E(O.name,W,"remove",C))continue;W.removeAttribute(O.name)}}k(W,C)||h(W,w,C)}(T===8||T===3)&&M.nodeValue!==S.nodeValue&&(M.nodeValue=S.nodeValue)}function h(M,S,C){if(M instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let T=S.value,W=M.value;A(M,S,"checked",C),A(M,S,"disabled",C),S.hasAttribute("value")?W!==T&&(E("value",M,"update",C)||(M.setAttribute("value",T),M.value=T)):E("value",M,"remove",C)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)A(M,S,"selected",C);else if(M instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let T=S.value,W=M.value;if(E("value",M,"update",C))return;T!==W&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function A(M,S,C,T){let W=S[C],w=M[C];if(W!==w){let D=E(C,M,"update",T);D||(M[C]=S[C]),W?D||M.setAttribute(C,""):E(C,M,"remove",T)||M.removeAttribute(C)}}function E(M,S,C,T){return M==="value"&&T.ignoreActiveValue&&S===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,S,C)===!1}function k(M,S){return!!S.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,A){if(g.head.block){let E=f.querySelector("head"),k=h.querySelector("head");if(E&&k){let M=p(E,k,g);return Promise.all(M).then(()=>{let S=Object.assign(g,{head:{block:!1,ignore:!0}});return A(S)})}}return A(g)}function p(g,f,h){let A=[],E=[],k=[],M=[],S=new Map;for(let T of f.children)S.set(T.outerHTML,T);for(let T of g.children){let W=S.has(T.outerHTML),w=h.head.shouldReAppend(T),D=h.head.shouldPreserve(T);W||D?w?E.push(T):(S.delete(T.outerHTML),k.push(T)):h.head.style==="append"?w&&(E.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&E.push(T)}M.push(...S.values());let C=[];for(let T of M){let W=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(W)!==!1){if("href"in W&&W.href||"src"in W&&W.src){let w,D=new Promise(function(F){w=F});W.addEventListener("load",function(){w()}),C.push(D)}g.appendChild(W),h.callbacks.afterNodeAdded(W),A.push(W)}}for(let T of E)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:A,kept:k,removed:E}),C}let c=(function(){function g(C,T,W){let{persistentIds:w,idMap:D}=M(C,T),F=f(W),j=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(j))throw`Do not understand how to morph style ${j}`;return{target:C,newContent:T,config:F,morphStyle:j,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:D,persistentIds:w,pantry:h(),activeElementAndParents:A(C),callbacks:F.callbacks,head:F.head}}function f(C){let T=Object.assign({},t);return Object.assign(T,C),T.callbacks=Object.assign({},t.callbacks,C.callbacks),T.head=Object.assign({},t.head,C.head),T}function h(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function A(C){let T=[],W=document.activeElement;if(W?.tagName!=="BODY"&&C.contains(W))for(;W&&(T.push(W),W!==C);)W=W.parentElement;return T}function E(C){let T=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&T.push(C),T}function k(C,T,W,w){for(let D of w){let F=D.getAttribute("id");if(T.has(F)){let j=D;for(;j;){let O=C.get(j);if(O==null&&(O=new Set,C.set(j,O)),O.add(F),j===W)break;j=j.parentElement}}}}function M(C,T){let W=E(C),w=E(T),D=S(W,w),F=new Map;k(F,D,C,W);let j=T.__idiomorphRoot||T;return k(F,D,j,w),{persistentIds:D,idMap:F}}function S(C,T){let W=new Set,w=new Map;for(let{id:F,tagName:j}of C)w.has(F)?W.add(F):w.set(F,j);let D=new Set;for(let{id:F,tagName:j}of T)D.has(F)?W.add(F):w.get(F)===j&&D.add(F);for(let F of W)D.delete(F);return D}return g})(),{normalizeElement:d,normalizeParent:u}=(function(){let g=new WeakSet;function f(k){return k instanceof Document?k.documentElement:k}function h(k){if(k==null)return document.createElement("div");if(typeof k=="string")return h(E(k));if(g.has(k))return k;if(k instanceof Node){if(k.parentNode)return new A(k);{let M=document.createElement("div");return M.append(k),M}}else{let M=document.createElement("div");for(let S of[...k])M.append(S);return M}}class A{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)M.push(S),S=S.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(M)&&S.push(C);let T=C.querySelectorAll(M);for(let W=0;W<T.length;W++)S.push(T[W])}return S},[])}insertBefore(M,S){return this.realParentNode.insertBefore(M,S)}moveBefore(M,S){return this.realParentNode.moveBefore(M,S)}get __idiomorphRoot(){return this.originalNode}}function E(k){let M=new DOMParser,S=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=M.parseFromString(k,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let T=C.firstChild;return T&&g.add(T),T}}else{let T=M.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return g.add(T),T}}return{normalizeElement:f,normalizeParent:h}})();return{morph:n,defaults:t}})();var zi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Mg.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let s=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var Tg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Wp={index:-1,draft:""};function Eg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function kg(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Lg(){return new Map}function Pg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Rg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Ig(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Wg(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function $i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Fn(e)-e.scrollTop<=t}function ji(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=e,d=n-o;return s||Math.abs(d)<a?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Gi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Hg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Bg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Dg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ja={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lv=["pre","code","a","script","style"],Ki=e=>({type:e?.type??Ja.type,placeholder:e?.placeholder??Ja.placeholder,speed:e?.speed??Ja.speed,duration:e?.duration??Ja.duration,buffer:e?.buffer??Ja.buffer}),Og=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Qa=new Map;for(let e of Og)Qa.set(e.name,e);var sr=e=>{Qa.set(e.name,e)},Dp=e=>{Og.some(t=>t.name===e)||Qa.delete(e)},Fp=()=>Array.from(Qa.keys()),zr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Qa.get(e)??null,Xi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
|
|
34
|
-
`);return a<0?"":e.slice(0,a)}return e},Pv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Rv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Hp=/\s/,Iv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Wv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(Hp.test(a[l])){let p=l;for(;p<a.length&&Hp.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<a.length&&!Hp.test(a[c]);)p.appendChild(Pv(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},Hv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(Rv(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Ya=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??Lv).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Iv(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?Wv:Hv;for(let u of l)d(u,n,c);return r.innerHTML},Ji=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Za=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Fg=new WeakMap,Bv=(e,t)=>{if(!e.styles)return;let n=Fg.get(t);if(n||(n=new Set,Fg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Bp=new WeakMap,Dv=(e,t)=>{if(!e.onAttach)return;let n=Bp.get(t);if(n||(n=new Map,Bp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ng=e=>{let t=Bp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Qi=(e,t)=>{Bv(e,t),Dv(e,t)};function Op(e,t=Gt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var es=0,Ho=null;function Np(e=document){if(es++,es===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ho={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,es=Math.max(0,es-1),es===0&&Ho)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ho.originalOverflow,n.style.position=Ho.originalPosition,n.style.top=Ho.originalTop,n.style.width=Ho.originalWidth,o.scrollTo(0,Ho.scrollY),Ho=null}}}var ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",Bo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",rn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ts.side,width:t?.width??ts.width,animate:t?.animate??ts.animate,reveal:t?.reveal??ts.reveal,maxHeight:t?.maxHeight??ts.maxHeight}};var Pn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Fv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Yi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Fv,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=b("div",o),c=s.closeButtonTooltipText??"Close chat",d=s.closeButtonShowTooltip??!0,u=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Be("button",{className:Kn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Yt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),A=oe(u,a,"currentColor",1);return A?(A.style.display="block",h.appendChild(A)):h.textContent=g,p.appendChild(h),Ut({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??c,enabled:d}),{button:h,wrapper:p}},Ov="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Zi=(e,t={})=>{let{wrapperClassName:n=Ov,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",c=s.iconColor??"",d=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",A=s.paddingY??"",E=s.tooltipText??"Clear chat",k=s.showTooltip??!0,M=b("div",n),S=!!(u||g),C=Be("button",{className:Kn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:l,width:l,color:c||Yt.actionIconColor,backgroundColor:d||void 0,border:S?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:A||void 0,paddingBottom:A||void 0}}),T=oe(p,r,"currentColor",1);return T&&(T.style.display="block",C.appendChild(T)),M.appendChild(C),Ut({anchor:C,trigger:M,text:()=>C.getAttribute("aria-label")??E,enabled:k}),{button:C,wrapper:M}};var Yt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},eo=e=>{let{config:t,showClose:n=!0}=e,o=Be("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},a=r.headerIconSize??"48px",s=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=Be("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let T=parseFloat(a)||24,W=oe(p,T*.6,"currentColor",1);W?c.replaceChildren(W):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=b("img");T.src=t.launcher.iconUrl,T.alt="",T.className="persona-rounded-xl persona-object-cover",T.style.height=a,T.style.width=a,c.replaceChildren(T)}else c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Be("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Yt.titleColor}}),g=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Yt.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,A=f.placement??"inline",E=null,k=null;if(h){let W=Zi(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=W.button,k=W.wrapper,A==="top-right"&&(k.style.right="48px"),A==="inline"&&o.appendChild(k)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:C}=Yi(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:E,clearChatButtonWrapper:k}},ir=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var _p=e=>{let t=eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Nv(e,t,n){if(t?.length)for(let o of t){let r=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=oe(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=b("div","persona-relative");a.appendChild(r);let s=Ro({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-left"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Up=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=_i({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Yt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=b("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Yt.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),Nv(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let S=r.onTitleClick;c.addEventListener("click",C=>{C.target.closest("button")||S()}),c.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),S())})}let M=r?.titleRowHover;M&&(c.style.borderRadius=M.borderRadius??"10px",c.style.padding=M.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=M.background??"",c.style.borderColor=M.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=s.closeButtonSize??"32px",g=b("div",""),f=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=s.closeButtonColor||Yt.actionIconColor;let h=s.closeButtonIconName??"x",A=oe(h,"28px","currentColor",1);A?f.appendChild(A):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let E=b("div");E.style.display="none";let k=b("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:d,headerSubtitle:k,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},el={default:_p,minimal:Up},qp=e=>el[e]??el.default,$r=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=b("div");l.style.display="none";let p=b("span"),c=b("span"),d=b("button");d.style.display="none";let u=b("div");return u.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=qp(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var tl=e=>{let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let s=parseFloat(t.style.maxHeight);return Number.isFinite(s)&&s>0?s:n*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let s=Math.min(t.scrollHeight,r());t.style.height=`${s}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},nl=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",c=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,u=t.size??"40px",g=t.backgroundColor,f=t.textColor,h=b("div","persona-send-button-wrapper"),A=Be("button",{className:Kn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,k=null;if(n){let C=parseFloat(u)||24,T=f?.trim()||"currentColor";r?(E=oe(r,C,T,2),E?A.appendChild(E):A.textContent=o):A.textContent=o,k=oe(a,C,T,2)}else A.textContent=p;A.setAttribute("aria-label",s),h.appendChild(A),Ut({anchor:A,trigger:h,text:()=>A.getAttribute("aria-label")??"",enabled:d});let M="send";return{button:A,wrapper:h,setMode:C=>{if(C===M)return;M=C;let T=C==="stop"?l:s;if(A.setAttribute("aria-label",T),n){if(E&&k){let W=C==="stop"?k:E;A.replaceChildren(W)}}else A.textContent=C==="stop"?c:p}}},ol=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,c=parseFloat(p)||24,d=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,g=b("div","persona-send-button-wrapper"),f=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:d||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),A=oe(l,c,u||"currentColor",1.5);A?f.appendChild(A):f.textContent="\u{1F3A4}",g.appendChild(f);let E=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return Ut({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??E,enabled:k}),{button:f,wrapper:g}},rl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Yn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),c=b("div","persona-send-button-wrapper"),d=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1"}}),u=oe(a,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",f=>{f.preventDefault(),r.click()}),c.appendChild(d);let g=t.buttonTooltipText??"Attach file";return Ut({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??g}),{button:d,wrapper:c,input:r,previewsContainer:o}},al=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let a=t.idleText??"Online";if(t.idleLink){let s=b("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},sl=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var jr=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=sl(),r=Be("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=tl(t);s();let l=nl(t),p=ol(t),c=rl(t),d=al(t);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(a);let u=Be("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(g,f),r.append(u),r.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};var _g=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),a=oe("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Ug=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=sl(),r=al(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=tl(t);a.style.maxHeight="100px",s();let l=nl(t),p=ol(t),c=rl(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Be("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),d.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),c&&d.append(c.input),d.append(u,a,g),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:l.setMode}};var qg=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(Bo(e)){let d=e?.launcher?.composerBar??{},u=b("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Gt);let g=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",u.appendChild(g);let f=b("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Gt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!t){let d=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return d.style.width=g,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=e?.launcher??{},a=r.position&&Pn[r.position]?Pn[r.position]:Pn["bottom-right"],s=b("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Gt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??pn;return l.style.width=c,l.style.maxWidth=c,s.appendChild(l),{wrapper:s,panel:l}},_v=(e,t)=>{let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Yi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let C=Zi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=C.button,l=C.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Be("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let d=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),f=b("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let E=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),k=Ug({config:e}),{root:M,textNode:S}=_g();return n.append(p,r,c,E),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:p,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:M,peekTextNode:S}},Vg=(e,t=!0)=>{if(Bo(e))return _v(e,t);let n=Be("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,a=o?$r(e,o,{showClose:t}):eo({config:e,showClose:t}),s=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let l=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Et(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=b("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(c,d);let f=jr({config:e}),h=e?.layout?.showFooter!==!1;r?ir(n,a,e):(a.header.style.display="none",ir(n,a,e)),n.append(s);let A=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),n.append(f.footer),n.append(A),{container:n,body:s,messagesWrapper:d,composerOverlay:A,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Vp=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
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=`
|
|
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 Ua=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 S=s.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let S=s.subtitle??"Here to help you get answers fast";c.textContent=S,c.setAttribute("title",S)}let d=n.querySelector(".persona-flex-col");d&&(s.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let S=s.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let C=parseFloat(S)||24,T=oe(s.agentIconName,C*.6,"var(--persona-text-inverse, #ffffff)",2);T?(u.appendChild(T),u.style.display=""):(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let S=s.agentIconSize??"40px";g.style.height=S,g.style.width=S,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let S=s.callToActionIconSize??"32px";f.style.height=S,f.style.width=S,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let C=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,C=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",s.callToActionIconName){let T=parseFloat(S)||24,W=Math.max(T-C,8),w=oe(s.callToActionIconName,W,"currentColor",2);w?f.appendChild(w):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Pn[s.position]?Pn[s.position]:Pn["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${A} ${h}`,l||(n.style.zIndex=String(s.zIndex??Gt));let k="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=s.border??k,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=s.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var zg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=qg(e),a=Vg(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},c={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:l,header:p,composer:c,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},zp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Vp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Vp(e,n);return{instance:r,element:r.element}};var Uv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},qv=(e,t)=>{if(!e)return null;let n=Uv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Vv=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},zv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$p=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},jp=320,Kg=320,$v=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),jv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Gv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Kv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Xv=e=>{if(!e||e.length===0)return null;let t=Be("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Be("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=b("span","persona-mention-chip-icon"),a=oe(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Jv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(qa(o.ref,{readonly:!0,render:t}))}return n},$g="\uE000",jg="\uE001",Qv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${$g}${r}:${g}${jg}`,s=t.map((g,f)=>g.kind==="text"?g.text:a(f)).join(""),l=n(s);if(!t.every((g,f)=>g.kind==="text"||l.includes(a(f)))){e.replaceChildren(Jv(t,o));return}e.innerHTML=l;let c=new RegExp(`${$g}${r}:(\\d+)${jg}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let g=d.nextNode();g;g=d.nextNode())u.push(g);for(let g of u){let f=g;for(let h=c.exec(f.data);h;h=c.exec(f.data)){let A=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),A?.kind==="mention"&&E.parentNode?.insertBefore(qa(A.ref,{readonly:!0,render:o}),E),f=E}}},Yv=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let c=b("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${jp}px`,c.style.maxHeight=`${Kg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&s())}),c.addEventListener("load",()=>{d=!0}),zv(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},Zv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$p(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},eC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$p(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,r.style.maxHeight=`${Kg}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},tC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$p(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},lr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Gp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:lr};if(t){let r=t(o);if(r!==null)return r}return lr()},nC=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Gg=(e,t,n="div")=>{let o=b(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Kp=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Xp=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){let h=b("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let l=t.visibility??"hover",p=t.align??"right",c=t.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,A,E)=>{let k=Mt({icon:h,label:A,size:14,className:"persona-message-action-btn"});return k.setAttribute("data-action",E),k};return o&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Gr=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,c=s.timestamp,d=p?.show??!1,u=c?.show??!1,g=p?.position??"left",f=c?.position??"below",h=Kp(e.role,l),A=b("div",h.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(A.style.backgroundColor="transparent",A.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$v(e),k=e.content?.trim()??"",S=E.length>0&&k===fi,C=Ki(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&C.type!=="none"?zr(C.type,T):null,w=e.role==="assistant"&&W?.isAnimating?.(e)===!0,D=e.role==="assistant"&&W!==null&&(!!e.streaming||w);D&&W?.bubbleClass&&A.classList.add(W.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),D&&W&&(W.containerClass&&F.classList.add(W.containerClass),F.style.setProperty("--persona-stream-step",`${C.speed}ms`),F.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let j=D?Xi(e.content??"",C.buffer,W,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:j,message:e,streaming:!!e.streaming,raw:e.rawContent});return D&&W?.wrap==="char"?Ya(Z,"char",e.id,{skipTags:W.skipTags}):D&&W?.wrap==="word"?Ya(Z,"word",e.id,{skipTags:W.skipTags}):Z},q=null;if(S?(q=document.createElement("div"),q.innerHTML=O(),q.style.display="none",F.appendChild(q)):e.contentSegments?.length?Qv(F,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=O(),D&&W?.useCaret&&!S&&k){let Z=Ji(),me=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=me[me.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(Z,Ae.nextSibling);else{let we=F.lastElementChild;we?we.appendChild(Z):F.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=Gg(e,c,"span");Z.classList.add("persona-timestamp-inline");let me=F.lastElementChild;me?me.appendChild(Z):F.appendChild(Z)}if(E.length>0){let Z=Yv(E,!S&&!!k,()=>{S&&q&&(q.style.display="")});Z?A.appendChild(Z):S&&q&&(q.style.display="")}let Q=jv(e);if(Q.length>0){let Z=Zv(Q);Z&&A.appendChild(Z)}let de=Gv(e);if(de.length>0){let Z=eC(de);Z&&A.appendChild(Z)}let be=Kv(e);if(be.length>0){let Z=tC(be);Z&&A.appendChild(Z)}let De=e.contentSegments?.length?null:Xv(e.contextMentions);if(De&&A.appendChild(De),A.appendChild(F),u&&f==="below"&&e.createdAt){let Z=Gg(e,c);Z.classList.add("persona-mt-1"),A.appendChild(Z)}let ie=e.role==="assistant"?qv(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(j&&j.trim()),me=C.placeholder==="skeleton",Ae=me&&C.buffer==="line"&&Z;if(Z)Ae&&A.appendChild(Za());else if(me)A.appendChild(Za());else{let we=Gp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);we&&A.appendChild(we)}}if(ie&&e.stopReason&&!e.streaming&&(k||(F.style.display="none"),A.appendChild(Vv(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Xp(e,o,r);A.appendChild(Z)}if(!d||e.role==="system")return A;let ne=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=nC(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ne.append(A,le):ne.append(le,A),ne},Xg=(e,t,n,o,r,a)=>{let s=n??{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Gr(e,t,n,o,r,a)};var Kr=new Set,oC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),rC=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
43
|
-
`):""},
|
|
44
|
-
`);let r=
|
|
45
|
-
`):""},Qp=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},iC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=sC(e,o?.previewMaxLines??3),s=n?Sm(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},c=s;return r==="tool-name"?c=n.name?.trim()||s:r==="tool-preview"&&a&&(c=a),l&&p.activeTextTemplate?c=bd(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=bd(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},Qg=(e,t,n)=>{let o=Xr.has(e),r=n?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=oe(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Yp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&Xr.has(e.id),{summary:p,previewText:c,isActive:d}=iC(e,t),u=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",s&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),A=()=>{let O=b("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=Fa(n),O},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:Fa(n),createElapsedElement:A});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=p,g.appendChild(f));let k=a.loadingAnimation??"none",M=o.activeTextTemplate,S=o.completeTextTemplate,C=d?M:S,T=E instanceof HTMLElement,W=(O,q)=>{f.textContent="";let Q=n.name?.trim()||"tool",de=ii(O,Q),be=0;for(let De of de){let ie=De.styles.length>0?(()=>{let ge=b("span",De.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return f.appendChild(ge),ge})():f;if(De.isDuration&&d)ie.appendChild(A());else{let ge=De.isDuration?Fa(n):De.text;q?be=Po(ie,ge,be):ie.appendChild(document.createTextNode(ge))}}};if(!T)if(d&&k!=="none"){let O=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),C&&W(C,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${O}ms`),k==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),C)W(C,!0);else{let q=f.textContent||p;f.textContent="",Po(f,q,0)}}else C&&W(C,!1);let w=null;if(s){w=b("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(w),u.append(g,Q)}else u.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});aC(D,O)||(D.textContent=c),D.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,D),r;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(F.style.display=l?"":"none",o.contentBackgroundColor&&(F.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(F.style.color=o.contentTextColor),o.contentPaddingX&&(F.style.paddingLeft=o.contentPaddingX,F.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(F.style.paddingTop=o.contentPaddingY,F.style.paddingBottom=o.contentPaddingY),n.name){let O=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,F.appendChild(O)}if(n.args!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Arguments";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.args),O.append(q,Q),F.appendChild(O)}if(n.chunks&&n.chunks.length){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Activity";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=n.chunks.join(""),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Result";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.result),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,F.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",D.style.display=l?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(u,D,F),r};var dr=new Map,il=e=>{let n=(e.startsWith(En)?e.slice(En.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Yg=e=>e?.approval!==!1?e?.approval:void 0,Zg=(e,t)=>{let n=Yg(t)?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},eh=(e,t,n)=>{let o=Yg(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=oe(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},th=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Zg(e,n);eh(o,a,n),r.style.display=a?"":"none"};var ll=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=b("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return a;let s=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=oe(p,20,c,2);d&&l.appendChild(d);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),f=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",g.appendChild(f),!r){let w=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),g.appendChild(w)}u.appendChild(g);let A=n.toolType==="webmcp"||n.toolName.startsWith(En)?Pa(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...A?{displayTitle:A}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,M=E||(k?n.description:`The assistant wants to use \u201C${A??il(n.toolName)}\u201D.`),S=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=M,u.appendChild(S),n.reason){let w=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let D=b("span","persona-font-medium");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(D),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let C=o?.detailsDisplay??"collapsed",T=!!n.description&&!k,W=T||!!n.parameters;if(C!=="hidden"&&W){let w=Zg(e.id,t),D=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");D.type="button",D.setAttribute("data-expand-header","true"),D.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span");F.setAttribute("data-approval-details-label","true");let j=b("span","persona-inline-flex persona-items-center");j.setAttribute("data-approval-details-chevron","true"),D.append(F,j),eh(D,w,t),u.appendChild(D);let O=b("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",T){let q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,O.appendChild(q)}if(n.parameters){let q=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(q.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=Ao(n.parameters),O.appendChild(q)}u.appendChild(O)}if(r){let w=b("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let D=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",D.style.color=o?.approveButtonTextColor??"#ffffff",D.setAttribute("data-approval-action","approve");let F=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",D.appendChild(F));let j=document.createTextNode(o?.approveLabel??"Approve");D.appendChild(j);let O=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let q=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);q&&(q.style.marginRight="4px",O.appendChild(q));let Q=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(Q),w.append(D,O),u.appendChild(w)}return s.append(l,u),a.appendChild(s),a};function lC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function nh(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=e,u=e.container??lC(t),g=!1,f=null,h=()=>{if(!g)return;let k=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${k.width}px`),s&&(n.style.maxWidth=`${k.width}px`);let M=n.getBoundingClientRect(),S=l?.()??null,C=S!=null?k.top+S:k.top,T=o==="top-start"||o==="top-end"?C-r-M.height:k.bottom+r,w=o==="bottom-end"||o==="top-end"?k.right-M.width:k.left,D=s?.()??null;if(D!=null){let F=Math.max(k.left,k.right-M.width);w=Math.min(Math.max(k.left+D,k.left),F)}n.style.top=`${T}px`,n.style.left=`${w}px`},A=()=>{g&&(g=!1,f&&(f(),f=null),n.remove())},E=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let k=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,S=()=>{if(!t.isConnected){A(),d?.("anchor-removed");return}h()},C=W=>{let w=typeof W.composedPath=="function"?W.composedPath():[];w.includes(n)||w.includes(t)||(A(),d?.("outside"))},T=k.setTimeout(()=>{M.addEventListener("pointerdown",C,!0)},0);k.addEventListener("scroll",S,!0),k.addEventListener("resize",S),f=()=>{k.clearTimeout(T),M.removeEventListener("pointerdown",C,!0),k.removeEventListener("scroll",S,!0),k.removeEventListener("resize",S)},c?.()};return{get isOpen(){return g},open:E,close:A,toggle:()=>g?A():E(),reposition:h,destroy:A}}function oh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var dC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),rh=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},cr=(e,t)=>{rh(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},cC=e=>e?.approval!==!1?e?.approval:void 0,pC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},Zp=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uC=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(En)?Pa(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??il(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},fC=e=>{let t=b("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?il(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},mC=(e,t,n,o,r,a,s)=>{let l=b("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,g=u&&pC(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",A=b("button","persona-approval-head");A.type="button",u?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",g?"true":"false"),A.setAttribute("aria-label",g?h:f)):A.setAttribute("data-static","true");let E=b("span","persona-approval-logo"),k=oe("shield-check",16,"currentColor",2);k&&E.appendChild(k),A.appendChild(E);let M=uC(n,o);if(u){let D=b("span","persona-approval-toggle");D.setAttribute("aria-hidden","true");let F=oe("chevron-down",14,"currentColor",2);F&&D.appendChild(F),M.append(" "),M.appendChild(D)}A.appendChild(M),l.appendChild(A);let S=b("div","persona-approval-body");if(u){let D=b("div","persona-approval-details");if(D.setAttribute("data-role","params"),D.hidden=!g,c){let F=b("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,D.appendChild(F)}if(d){let F=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=Ao(n.parameters),D.appendChild(F)}S.appendChild(D)}if(n.reason){let D=b("p","persona-approval-reason");o?.reasonColor?D.style.color=o.reasonColor:o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,D.append(F,document.createTextNode(n.reason)),S.appendChild(D)}let C=b("div","persona-approval-actions"),T=null,W=D=>{o?.approveButtonColor&&(D.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(D.style.color=o.approveButtonTextColor)},w=b("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),s){let D=b("div","persona-approval-split"),F=b("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),W(F),F.append(o?.approveLabel??"Always allow",Zp("\u23CE"));let j=b("button","persona-approval-caret");j.type="button",j.setAttribute("data-action","toggle-menu"),j.setAttribute("aria-label","More options"),W(j);let O=oe("chevron-down",15,"currentColor",2);O&&j.appendChild(O),D.append(F,j),C.append(D,w),w.append(Zp("Esc"));let q=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Zp("\u2318\u23CE")),q.appendChild(Q),T=nh({anchor:D,content:q,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),Q.addEventListener("click",()=>{cr(e,t.id),r()})}else{let D=b("button","persona-approval-primary persona-approval-primary--solo");D.type="button",D.setAttribute("data-action","allow"),W(D),D.append(o?.approveLabel??"Allow"),C.append(D,w)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",D=>{let F=D.target instanceof Element?D.target.closest("[data-action]"):null;if(!F)return;let j=F.getAttribute("data-action");if(j==="toggle-params"){let O=l.querySelector('[data-role="params"]');if(O){let q=O.hidden;O.hidden=!q,A.setAttribute("aria-expanded",q?"true":"false"),A.setAttribute("aria-label",q?h:f),dr.set(t.id,q)}return}if(j==="toggle-menu"){T?.toggle();return}if(j==="always"){cr(e,t.id),r({remember:!0});return}if(j==="allow"){cr(e,t.id),r();return}if(j==="deny"){cr(e,t.id),a();return}}),l},ah=()=>{let e=dC();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=cC(s);if(l.status!=="pending"){if(cr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return fC(l)}rh(e,o.id);let c=p?.enableAlwaysAllow===!0,d=mC(e,o,l,p,r,a,c);if(c){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{oh(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),cr(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])cr(e,o);e.latestPendingApprovalId=null}}};var sh=e=>{let t=[],n=null;return{buttons:t,render:(r,a,s,l,p,c)=>{e.innerHTML="",t.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(a?a.getMessages():[])).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(h=>{let A=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");A.type="button",A.textContent=h,A.disabled=g,p?.fontFamily&&(A.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY),A.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",d&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(A),t.push(A)}),e.appendChild(u),d){let h=JSON.stringify(r);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var ns=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var os=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var gC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hC=new Set(["step_start","execution_start"]),yC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bC=new Set(["step_complete","agent_turn_complete"]),xC=new Set(["flow_complete","agent_complete"]),ih=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),dh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,pr=(e,t)=>{let n=e[t];return dh(n)?n:void 0};function eu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function dl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function vC(e,t){return typeof t.type=="string"?t.type:e}function CC(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function wC(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function lh(e){let t=pr(e,"result"),n=[pr(e,"tokens"),pr(e,"totalTokens"),t?pr(t,"tokens"):void 0,pr(e,"usage"),t?pr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=un(o.output)??un(o.outputTokens)??un(o.completionTokens);if(r!==void 0)return r}return un(e.outputTokens)??un(e.completionTokens)??(t?un(t.outputTokens)??un(t.completionTokens):void 0)}function AC(e){let t=pr(e,"result");return un(e.executionTime)??un(e.executionTimeMs)??un(e.execution_time)??un(e.duration)??(t?un(t.executionTime)??un(t.executionTimeMs):void 0)}function SC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var rs=class{constructor(t=SC){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:dl(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!dh(n)){ih.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=vC(t,n),r=this.now();if(gC.has(o)){this.startRun(r);return}if(hC.has(o)){this.run||this.startRun(r);return}if(yC.has(o)){if(!wC(o,n))return;let a=CC(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+eu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:dl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(bC.has(o)){if(!this.run)return;let a=this.run,s=lh(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+eu(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:dl(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(xC.has(o)){if(!this.run)return;let a=this.run,s=lh(n),l=s??a.exactOutputTokens+eu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:dl(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(ih.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:AC(n)??o-t.startedAt}};function Jr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var MC={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},TC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},EC=["flowName","stepName","reasoningText","text","name","tool","toolName"],kC=100;function LC(e,t){let n={...MC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return TC}function PC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function RC(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function IC(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),a=n;for(let s of r)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function WC(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function HC(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function BC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function DC(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function FC(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function tu(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Jr(c,o.classNames?.eventRow);let d=s.find(g=>g.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let g=d.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){let g=b("div",""),f=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);A&&h.appendChild(A);let E=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=o.timestampFormat??"relative";E.textContent=k==="relative"?PC(e.timestamp,n):RC(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let S=LC(e.type,o.badgeColors),C=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let T=o.descriptionFields??EC,W=IC(e.payload,T),w=null;W&&(w=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),F=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),j=oe("clipboard","12px","currentColor",1.5);return j&&F.appendChild(j),F.addEventListener("click",async O=>{O.stopPropagation(),await WC(HC(e)),F.innerHTML="";let q=oe("check","12px","currentColor",1.5);q&&F.appendChild(q),setTimeout(()=>{F.innerHTML="";let Q=oe("clipboard","12px","currentColor",1.5);Q&&F.appendChild(Q)},1500)}),f.appendChild(h),f.appendChild(E),M&&f.appendChild(M),f.appendChild(C),w&&f.appendChild(w),f.appendChild(D),f.appendChild(F),g.appendChild(f),p&&g.appendChild(FC(e,s,l)),g}}function ch(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&r){let h=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,A=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Jr(A,h?.panel);let E=[],k="",M="",S=null,C=[],T={},W=0,w=$i(),D=0,F=0,j=!1,O=null,q=!1,Q=0,de=new Set,be=new Map,De="",ie="",ge=null,ne,le,Z,me,Ae=null,we=null,Se=null;function mt(){let _=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),$=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Jr($,h?.headerBar),s){we=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),we.style.cursor="help",Ae=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",Se=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Se.style.display="none",Se.style.pointerEvents="none";let Fe=we,Ht=Se,Sl=()=>{if(!Ht.textContent)return;let ms=Fe.getBoundingClientRect(),gs=_.getBoundingClientRect();Ht.style.left=`${ms.left-gs.left}px`,Ht.style.top=`${ms.bottom-gs.top+4}px`,Ht.style.display="block"},Do=()=>{Ht.style.display="none"};we.addEventListener("mouseenter",Sl),we.addEventListener("mouseleave",Do),we.appendChild(Ae)}let Y=b("div","persona-flex-1");ne=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let je=b("option","");je.value="",je.textContent="All events (0)",ne.appendChild(je),le=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let Qe=oe("clipboard-copy","12px","currentColor",1.5);Qe&&le.appendChild(Qe);let rt=b("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),we&&$.appendChild(we),$.appendChild(Y),$.appendChild(ne),$.appendChild(le);let G=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Jr(G,h?.searchBar);let Ue=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),he=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ue&&he.appendChild(Ue),Z=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Jr(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",me=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let qe=oe("x","12px","currentColor",2);return qe&&me.appendChild(qe),G.appendChild(he),G.appendChild(Z),G.appendChild(me),_.appendChild($),_.appendChild(G),Se&&_.appendChild(Se),_}let We,_e=a.find(_=>_.renderEventStreamToolbar);_e?.renderEventStreamToolbar&&r?We=_e.renderEventStreamToolbar({config:r,defaultRenderer:()=>mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:$=>{k=$,et(),ae()},onSearchChange:$=>{M=$,et(),ae()}})??mt():We=mt();let Xe=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Xe.style.display="none";function $e(){if(!s||!Ae||!we)return;let _=s(),$=BC(_);Ae.textContent=$;let Y=DC(_);Se&&(Se.textContent=Y,Y||(Se.style.display="none")),we.setAttribute("aria-label",Y?`Throughput: ${$}, ${Y}`:`Throughput: ${$}`)}let Me=b("div","persona-flex-1 persona-min-h-0 persona-relative"),ke=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ke.style.height="100%";let Je=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Jr(Je,h?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Dt=oe(c,"14px","currentColor",2);Dt&&Je.appendChild(Dt);let Wt=b("span","");Wt.textContent=d,Je.appendChild(Wt);let Kt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Kt.style.display="none",Me.appendChild(ke),Me.appendChild(Kt),Me.appendChild(Je),A.setAttribute("tabindex","0"),A.appendChild(We),A.appendChild(Xe),A.appendChild(Me);function wt(){let _=t.getAll(),$={};for(let G of _)$[G.type]=($[G.type]||0)+1;let Y=Object.keys($).sort(),je=Y.length!==C.length||!Y.every((G,Ue)=>G===C[Ue]),Re=!je&&Y.some(G=>$[G]!==T[G]),Qe=_.length!==Object.values(T).reduce((G,Ue)=>G+Ue,0);if(!je&&!Re&&!Qe||(C=Y,T=$,!ne))return;let rt=ne.value;if(ne.options[0].textContent=`All events (${_.length})`,je){for(;ne.options.length>1;)ne.remove(1);for(let G of Y){let Ue=b("option","");Ue.value=G,Ue.textContent=`${G} (${$[G]||0})`,ne.appendChild(Ue)}rt&&Y.includes(rt)?ne.value=rt:rt&&(ne.value="",k="")}else for(let G=1;G<ne.options.length;G++){let Ue=ne.options[G];Ue.textContent=`${Ue.value} (${$[Ue.value]||0})`}}function He(){let _=t.getAll();if(k&&(_=_.filter($=>$.type===k)),M){let $=M.toLowerCase();_=_.filter(Y=>Y.type.toLowerCase().includes($)||Y.payload.toLowerCase().includes($))}return _}function ce(){return k!==""||M!==""}function et(){W=0,D=0,w.resume(),Je.style.display="none"}function Pe(_){de.has(_)?de.delete(_):de.add(_),ge=_;let $=ke.scrollTop,Y=w.isFollowing();q=!0,w.pause(),ae(),ke.scrollTop=$,Y&&w.resume(),q=!1}function ue(){return Wo(ke,50)}function ae(){F=Date.now(),j=!1,$e(),wt();let _=t.getEvictedCount();_>0?(Xe.textContent=`${_.toLocaleString()} older events truncated`,Xe.style.display=""):Xe.style.display="none",E=He();let $=E.length,Y=t.getSize()>0;$===0&&Y&&ce()?(Kt.textContent=M?`No events matching '${M}'`:"No events matching filter",Kt.style.display="",ke.style.display="none"):(Kt.style.display="none",ke.style.display=""),le&&(le.title=ce()?`Copy Filtered (${$})`:"Copy All"),p&&!w.isFollowing()&&$>W&&(D+=$-W,Wt.textContent=d?`${d}${D>0?` (${D})`:""}`:"",Je.style.display=""),W=$;let je=t.getAll(),Re=je.length>0?je[0].timestamp:0,Qe=new Set(E.map(Ue=>Ue.id));for(let Ue of de)Qe.has(Ue)||de.delete(Ue);let rt=k!==De||M!==ie,G=be.size===0&&E.length>0;if(rt||G||E.length===0){ke.innerHTML="",be.clear();let Ue=document.createDocumentFragment();for(let he=0;he<E.length;he++){let qe=tu(E[he],he,Re,u,de,Pe,a,r);be.set(E[he].id,qe),Ue.appendChild(qe)}ke.appendChild(Ue),De=k,ie=M,ge=null}else{if(ge!==null){let he=be.get(ge);if(he&&he.parentNode===ke){let qe=E.findIndex(Fe=>Fe.id===ge);if(qe>=0){let Fe=tu(E[qe],qe,Re,u,de,Pe,a,r);ke.insertBefore(Fe,he),he.remove(),be.set(ge,Fe)}}ge=null}let Ue=new Set(E.map(he=>he.id));for(let[he,qe]of be)Ue.has(he)||(qe.remove(),be.delete(he));for(let he=0;he<E.length;he++){let qe=E[he];if(!be.has(qe.id)){let Fe=tu(qe,he,Re,u,de,Pe,a,r);be.set(qe.id,Fe),ke.appendChild(Fe)}}}w.isFollowing()&&(ke.scrollTop=ke.scrollHeight)}function Le(){if(Date.now()-F>=kC){O!==null&&(cancelAnimationFrame(O),O=null),ae();return}j||(j=!0,O=requestAnimationFrame(()=>{O=null,ae()}))}let it=(_,$)=>{if(!le)return;le.innerHTML="";let Y=oe(_,"12px","currentColor",1.5);Y&&le.appendChild(Y);let je=b("span","persona-text-xs");je.textContent="Copy All",le.appendChild(je),setTimeout(()=>{le.innerHTML="";let Re=oe("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Qe=b("span","persona-text-xs");Qe.textContent="Copy All",le.appendChild(Qe),le.disabled=!1},$)},pe=async()=>{if(le){le.disabled=!0;try{let _;ce()?_=E:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let $=_.map(Y=>{try{return JSON.parse(Y.payload)}catch{return Y.payload}});await navigator.clipboard.writeText(JSON.stringify($,null,2)),it("check",1500)}catch{it("x",1500)}}},ve=()=>{ne&&(k=ne.value,et(),ae())},ee=()=>{!Z||!me||(me.style.display=Z.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{M=Z.value,et(),ae()},150))},P=()=>{!Z||!me||(Z.value="",M="",me.style.display="none",S&&clearTimeout(S),et(),ae())},U=()=>{if(q)return;let _=ke.scrollTop,{action:$,nextLastScrollTop:Y}=ji({following:w.isFollowing(),currentScrollTop:_,lastScrollTop:Q,nearBottom:ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=Y,$==="resume"?(w.resume(),D=0,Je.style.display="none"):$==="pause"&&(w.pause(),p&&(Wt.textContent=d,Je.style.display=""))},x=_=>{let $=Gi({following:w.isFollowing(),deltaY:_.deltaY,nearBottom:ue(),resumeWhenNearBottom:!0});$==="pause"?(w.pause(),p&&(Wt.textContent=d,Je.style.display="")):$==="resume"&&(w.resume(),D=0,Je.style.display="none")},H=()=>{p&&(ke.scrollTop=ke.scrollHeight,w.resume(),D=0,Je.style.display="none")},R=_=>{let $=_.target;if(!$||$.closest("button"))return;let Y=$.closest("[data-event-id]");if(!Y)return;let je=Y.getAttribute("data-event-id");je&&Pe(je)},B=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Z?.focus(),Z?.select();return}_.key==="Escape"&&(Z&&document.activeElement===Z?(P(),Z.blur(),A.focus()):o&&o())};le&&le.addEventListener("click",pe),ne&&ne.addEventListener("change",ve),Z&&Z.addEventListener("input",ee),me&&me.addEventListener("click",P),ke.addEventListener("scroll",U),ke.addEventListener("wheel",x,{passive:!0}),ke.addEventListener("click",R),Je.addEventListener("click",H),A.addEventListener("keydown",B);function K(){S&&clearTimeout(S),O!==null&&(cancelAnimationFrame(O),O=null),j=!1,be.clear(),le&&le.removeEventListener("click",pe),ne&&ne.removeEventListener("change",ve),Z&&Z.removeEventListener("input",ee),me&&me.removeEventListener("click",P),ke.removeEventListener("scroll",U),ke.removeEventListener("wheel",x),ke.removeEventListener("click",R),Je.removeEventListener("click",H),A.removeEventListener("keydown",B)}return{element:A,update:Le,destroy:K}}}function ph(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},c=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===r)f=Math.min(g+1,a.length-1);else if(u.key===o)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},d=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",c),e.addEventListener("focusin",d),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let A=h===g;f.setAttribute("aria-selected",A?"true":"false"),f.tabIndex=A||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",c),e.removeEventListener("focusin",d)}}}function uh(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),g=typeof document<"u"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),q?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let A=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");A.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&A.classList.add("persona-artifact-toolbar-document");let E=b("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=a;let k=Mt({icon:"x",label:s});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",S=qr({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ee=>{M=ee==="source"?"source":"rendered",it()}}),C=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,D=!!(W&&w&&w.length>0),F=null,j,O=null,q=null;if(r&&(T||W)&&!D){if(j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=oe("chevron-down",14,"currentColor",2);ee&&j.appendChild(ee)}}else r&&D?(F=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=Mt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(j,O)):r?j=Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(j=Mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&j.classList.add("persona-hidden"));let Q=r?Mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mt({icon:"refresh-cw",label:"Refresh"}),de=r?Mt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Mt({icon:"x",label:s}),be=Mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&be.classList.add("persona-hidden");let De=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ie=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Me.find(H=>H.id===ke)??Me[Me.length-1],P=ee?.id??null,U=ee?.artifactType==="markdown"?ee.markdown??"":"",x=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:U,jsonPayload:x,id:P}},ne=async()=>{let ee=Me.find(P=>P.id===ke)??Me[Me.length-1];try{await navigator.clipboard.writeText(Xa(ee))}catch{}};if(j.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&D){let{markdown:P,jsonPayload:U,id:x}=ge();try{await ee({actionId:"primary",artifactId:x,markdown:P,jsonPayload:U})}catch{}return}await ne()}),O&&w?.length){let ee=()=>h.closest("[data-persona-root]")??document.body,P=()=>{q=Ro({items:w.map(U=>({id:U.id,label:U.label})),onSelect:async U=>{let{markdown:x,jsonPayload:H,id:R}=ge(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:U,artifactId:R,markdown:x,jsonPayload:H}):U==="markdown"||U==="md"?await navigator.clipboard.writeText(x):U==="json"||U==="source"?await navigator.clipboard.writeText(H):await navigator.clipboard.writeText(x||H)}catch{}},anchor:F??O,position:"bottom-right",portal:ee()})};h.isConnected?P():requestAnimationFrame(P),O.addEventListener("click",U=>{U.stopPropagation(),q?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),de.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)A.replaceChildren(),F?C.append(F,Q,de):C.append(j,Q,de),C.insertBefore(De,de),C.insertBefore(be,de),A.append(S.element,le,C);else{let ee=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(j,De,be,k),A.appendChild(E),A.appendChild(ee)}l&&(A.style.paddingLeft=l,A.style.paddingRight=l);let Z=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Ae=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),we=ph(Z,{onSelect:ee=>t.onSelect(Me[ee].id)}),Se=ee=>{let P=ee.scrollWidth-ee.clientWidth,U=P>1,x=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",d&&U&&x>1),ee.classList.toggle("persona-artifact-tab-fade-end",u&&U&&x<P-1)},mt=0,We=()=>{if(mt)return;let ee=()=>{mt=0,Se(Z)};mt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};Z.addEventListener("scroll",()=>We(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Se(Z)).observe(Z);let _e=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{_e.scrollLeft=0},$e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[Z,Ae])ee.style.paddingLeft=l,ee.style.paddingRight=l;_e.style.padding=l}h.appendChild(A),h.appendChild(Z),h.appendChild(Ae),h.appendChild(_e);let Me=[],ke=null,Je=!1,Dt=!1,Wt=!0,Kt=!1,wt=null,He="",ce=null,et=!1,Pe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?M:"rendered",ue=ee=>{r||(ee&&!et?(A.insertBefore(S.element,E),et=!0):!ee&&et&&(S.element.remove(),et=!1))},ae=()=>ke&&Me.find(ee=>ee.id===ke)||Me[Me.length-1],Le=()=>{let ee=Ga(ae());if(!ee){De.replaceChildren();return}let P=ie.filter(U=>U.visible===void 0||U.visible(ee)).map(U=>Vr(U,{documentChrome:r,onClick:()=>{let x=Ga(ae());if(x)try{Promise.resolve(U.onClick(x)).catch(()=>{})}catch{}}}));De.replaceChildren(...P)},it=()=>{Le();let ee=r&&Me.length<=1,P=!!me;if(Z.classList.toggle("persona-hidden",ee||P),Ae.classList.toggle("persona-hidden",ee||!P),P&&me){let H=Me.map(R=>R.id).join("|")+" "+(ke??"");if(H!==He){He=H;let R=me({records:Me,selectedId:ke,onSelect:t.onSelect});Ae.firstElementChild!==R&&Ae.replaceChildren(R)}}else{we.beforeRender(),Z.replaceChildren();let H=[],R=-1;for(let[B,K]of Me.entries()){let _=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");_.type="button";let $=K.artifactType==="markdown"?K.file:void 0,Y=$?Dn($.path):K.title||K.id.slice(0,8),je=$?.path||K.title||Y;_.textContent=Y,_.title=je,_.setAttribute("aria-label",je),K.id===ke&&(_.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=B),_.addEventListener("click",()=>t.onSelect(K.id)),Z.appendChild(_),H.push(_)}if(we.render(H,R),R>=0&&ke!==wt){wt=ke;let B=H[R];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}Se(Z)}let U=ke&&Me.find(H=>H.id===ke)||Me[Me.length-1];if(!U){_e.replaceChildren(),ce=null,ue(!1);return}let x=U.artifactType==="markdown"?U.file:void 0;if(ue(!!x),r){let H=x?Lo(x):U.artifactType==="markdown"?"MD":U.component??"Component",R=(U.title||"Document").trim(),B=x?Dn(x.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${B} \xB7 ${H}`}else E.textContent=x?Dn(x.path):a;ce?(ce.el.parentElement!==_e&&_e.replaceChildren(ce.el),ce.update(U)):(ce=Vi(U,{config:e,resolveViewMode:Pe}),_e.replaceChildren(ce.el)),_e.classList.toggle("persona-artifact-content-flush",!!_e.querySelector(".persona-code-pre"))},pe=()=>{let ee=Me.length>0;if(h.classList.toggle("persona-hidden",!ee),g){let x=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&x&&Je?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},ve=()=>{Kt=!1,it(),pe()};return{element:h,backdrop:g,update(ee){let P=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,U=P!==ke;Me=ee.artifacts,ke=P,Me.length>0&&(Je=!0),Kt=!0,Wt&&ve(),U&&Xe()},setMobileOpen(ee){Je=ee,!ee&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(ee){ee!==Dt&&(Dt=ee,$e());let P=oe(ee?"minimize":"maximize",16,"currentColor",2);P&&be.replaceChildren(P);let U=ee?"Collapse artifacts panel":"Expand artifacts panel";be.setAttribute("aria-label",U),be.title=U},setExpandToggleVisible(ee){be.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||j.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ie=ee,Le()},setTabFade(ee){let P=c(ee);P.start===d&&P.end===u||(d=P.start,u=P.end,Se(Z))},setRenderTabBar(ee){ee!==me&&(me=ee,He="",it())},setVisible(ee){ee!==Wt&&(Wt=ee,ee&&Kt&&ve())}}}function Zt(e){return e?.features?.artifacts?.enabled===!0}function fh(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function OC(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var mh=["panel","seamless","detached"];function nu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&mh.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ou(e){return!e||!Zt(e)?!1:nu(e)==="detached"}function as(e,t){if(!Zt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),OC(e),fh(e,t);return}let n=t.features?.artifacts?.layout,o=nu(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),fh(e,t)}function ss(e,t){for(let l of mh)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=nu(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function gh(e,t){return!t||!Zt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var NC=new Set(["__proto__","prototype","constructor"]),_C=new Set(["collapsed","card","panel","inline"]),hh=new Set(["markdown","component"]),UC=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pl=e=>!NC.has(e),ru=e=>typeof e=="string"&&_C.has(e),fr=e=>Object.keys(e).length>0;function On(e,t,n,o){e.push({path:t,code:n,message:o})}var qC="Ignored because this key is not part of the persisted preference schema.",cl="Ignored an unsupported value.",VC="Expected collapsed, panel, or inline.",zC='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',yh={kind:"mode",message:cl},Qr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},$C={paneWidth:Qr,paneMaxWidth:Qr,paneMinWidth:Qr,expandedPanelWidth:Qr,resizableMinWidth:Qr,resizableMaxWidth:Qr,expandLauncherPanelWhenOpen:to,resizable:to},jC={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cl},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:yh,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:yh,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:hh,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:hh}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:$C}}}}};function bh(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:On(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:On(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:On(o,n,"invalid_value",t.message);case"mode":return ru(e)?on(e):On(o,n,"invalid_value",t.message);case"modeMap":{if(!ur(e))return On(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[s,l]of Object.entries(e)){let p=r?s:bo(s);pl(s)&&(r?r.has(s):UC.test(p))?ru(l)?a[p]=on(l):On(o,`${n}.${s}`,"invalid_value",VC):On(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":zC)}return fr(a)?a:void 0}case"object":{if(t.bareMode&&ru(e))return on(e);if(!ur(e))return On(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!pl(l)||!r.includes(l))&&On(o,a(l),"unknown_key",qC);let s={};for(let l of r){let p=t.children[l],c=bh(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&On(o,a(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=s[d];s[d]=ur(u)&&ur(c)?{...u,...c}:c}return fr(s)?s:void 0}}}function au(e){let t=[];return{preferences:(e===null?void 0:bh(e,jC,"",t))??{},issues:t}}function Yr(e){if(Array.isArray(e))return e.map(Yr);if(!ur(e))return e;let t={};for(let[n,o]of Object.entries(e))pl(n)&&o!==void 0&&(t[n]=Yr(o));return t}function xh(e,t){let n=Yr(e);for(let[o,r]of Object.entries(t)){if(!pl(o)||r===void 0)continue;let a=n[o];n[o]=ur(a)&&ur(r)?xh(a,r):Yr(r)}return n}function GC(e){let t={},n;for(let r of e){let a=au(r).preferences;n=vh(n,a.artifacts?.display),t=xh(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function KC(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},a={...o?{default:o}:{},...fr(r)?{byMediaType:r}:{}};return fr(a)?a:void 0}function vh(e,t){if(t===void 0)return e===void 0?void 0:Yr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},a=KC(n.files,t.files),s={...o?{default:o}:{},...fr(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return fr(s)?s:void 0}function su(e={},t){let n=GC(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},a={...r};if(n.artifacts.display!==void 0){let s=vh(r.display,n.artifacts.display);s!==void 0&&(a.display=s)}n.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(a.layout={...r.layout,...n.artifacts.layout}),o.artifacts=a}return o}function is(e){let t=e.preferences;return!t||!fr(t)?e:{...e,features:su(e.features??{},[t])}}function XC(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function JC(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function QC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function YC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function iu(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Ch(e,t,n,o,r,a){let s=XC(r,200),l=YC(t,n,o,200);l=Math.max(s,l);let p=JC(a);return p!==null&&(l=Math.min(l,p)),QC(e,s,l)}var wh={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},lu=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=wh[s]??wh.init;a.classList.add("persona-form-card","persona-space-y-4");let p=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=b("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let A=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${h.name}`;let E=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,A.appendChild(E);let k=h.type??"text",M;k==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=k),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${t.id}-${s}-${h.name}`,M.name=h.name,M.placeholder=h.placeholder??"",h.required&&(M.required=!0),A.appendChild(M),d.appendChild(A)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),d.appendChild(u),a.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let A=n.formEndpoint??"/form",E=new FormData(d),k={};E.forEach((M,S)=>{k[S]=M}),k.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let S=await M.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var du=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ls=new du;var Ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Sh=(e,t,n)=>{if(!Ah(e)||!Ah(t)||ZC.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=Sh(e[r],t[r],a)}return o};function ul(e,t){let n=Sh(e,t,"");return Or(n)}var Mh=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var ew=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},tw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},ds=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=ew(e),n=tw(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},cu=e=>typeof e=="string"?e:e==null?"":String(e),mr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:cu(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=cu(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:cu(n.text)}}},Th=e=>Array.isArray(e)?e.map(t=>String(t)):[],cs=e=>{let t=new Set(Th(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Th(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=s?e.parsers.reduce((c,d)=>c||d?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),o();let p={action:l,message:a.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",p)},u=c(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var nw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},ow=e=>e.map(t=>({...t,streaming:!1})),rw=e=>e.map(t=>({...t,status:"complete"})),fl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?nw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ow(n.messages):void 0,artifacts:n.artifacts?rw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Zr=ho(Ys(),1);function aw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function sw(e,t){if(!aw(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function ml(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Zr.parse)(n,Zr.STR|Zr.OBJ),a=sw(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Eh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function gl(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Ln.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function kh(){let e=ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lh(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function ps(e){let t=Lh(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function hl(e){let t=Lh(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function yl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=iw}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,f.appendChild(A),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let W=1;W<=5;W++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),w.title=c[W-1],w.dataset.rating=String(W),w.innerHTML=`
|
|
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
|
+
`):""},bh=(e,t)=>{let n=Zr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let c=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},au=(e,t)=>{let n=e.reasoning,o=x("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},a=r.expandable!==!1,s=a&&Zr.has(e.id),l=n.status!=="complete",p=HC(e,r.previewMaxLines??3),c=x("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",a&&(c.setAttribute("aria-expanded",s?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=x("div","persona-flex persona-flex-col persona-text-left"),u=x("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),S=()=>{let de=x("span","");return de.setAttribute("data-tool-elapsed",h),de.textContent=pi(n),de},k=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:pi(n),createElapsedElement:S});typeof k=="string"&&k.trim()?(u.textContent=k,d.appendChild(u)):k instanceof HTMLElement?d.appendChild(k):(u.textContent=g,d.appendChild(u));let P=x("span","persona-text-xs persona-text-persona-primary");P.textContent=zm(n),d.appendChild(P);let M=r.loadingAnimation??"none",A=f.activeTextTemplate,C=f.completeTextTemplate,E=l?A:C,R=k instanceof HTMLElement,w=(de,be)=>{u.textContent="";let pe=ui(de,""),te=0;for(let me of pe){let oe=me.styles.length>0?(()=>{let le=x("span",me.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(me.isDuration&&l)oe.appendChild(S());else{let le=me.isDuration?pi(n):me.text;be?te=Ho(oe,le,te):oe.appendChild(document.createTextNode(le))}}};if(!R&&E)if(P.style.display="none",u.style.display="",l&&M!=="none"){let de=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),M==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),w(E,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w(E,!0))}else w(E,!1);else if(!R&&l&&M!=="none"){u.style.display="";let de=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let be=u.textContent||g;u.textContent="",Ho(u,be,0)}n.status==="complete"&&(u.style.display="none")}else R||(n.status==="complete"?u.style.display="none":u.style.display="");let H=null;if(a){H=x("div","persona-flex persona-items-center");let be=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);be?H.appendChild(be):H.textContent=s?"Hide":"Show";let pe=x("div","persona-flex persona-items-center persona-ml-auto");pe.append(H),c.append(d,pe)}else c.append(d);let F=x("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","reasoning"),F.style.display="none",F.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let de=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});WC(F,de)||(F.textContent=p),F.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(c,F),o;let K=x("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");K.style.display=s?"":"none";let D=n.chunks.join(""),q=x("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return q.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),K.appendChild(q),(()=>{if(c.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let be=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);be?H.appendChild(be):H.textContent=s?"Hide":"Show"}K.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(c,F,K),o};var ea=new Set,BC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),DC=(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=Eo(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
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=`
|
|
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=W,k.forEach((D,F)=>{let j=F<W;D.classList.toggle("selected",j),D.setAttribute("aria-checked",F===W-1?"true":"false")})}),k.push(w),E.appendChild(w)}g.appendChild(E);let M=null;if(p){let W=document.createElement("div");W.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),W.appendChild(M),g.appendChild(W)}let S=document.createElement("div");S.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=l,C.addEventListener("click",()=>{n?.(),d.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=s,T.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let W=M?.value.trim()||void 0;await t(u,W),d.remove()}catch(W){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",W)}}),S.appendChild(C),S.appendChild(T),g.appendChild(S),d.appendChild(g),d}function bl(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:a="What could we do better? (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,h.appendChild(A);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,h.appendChild(E),f.appendChild(h);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=c;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=d,M.appendChild(S),M.appendChild(C);let T=document.createElement("div");T.className="persona-feedback-numbers";let W=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("persona-feedback-detractor"):O<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{g=O,W.forEach((Q,de)=>{Q.classList.toggle("selected",de===O),Q.setAttribute("aria-checked",de===O?"true":"false")})}),W.push(q),T.appendChild(q)}k.appendChild(M),k.appendChild(T),f.appendChild(k);let w=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=a,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),f.appendChild(O)}let D=document.createElement("div");D.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=l,F.addEventListener("click",()=>{n?.(),u.remove()});let j=document.createElement("button");return j.type="button",j.className="persona-feedback-btn persona-feedback-btn-submit",j.textContent=s,j.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(g,O),u.remove()}catch(O){j.disabled=!1,j.textContent=s,console.error("[NPS Feedback] Failed to submit:",O)}}),D.appendChild(F),D.appendChild(j),f.appendChild(D),u.appendChild(f),u}var ea="persona-chat-history",lw=30*1e3,dw=641,cw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function pw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let a=cw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function xl(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function uw(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var pu=e=>!e||typeof e!="object"?{}:{...e},Ph=e=>e.map(t=>({...t,streaming:!1})),Rh=(e,t,n)=>{let o=e?.markdown?Qo(e.markdown):null,r=Lr(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),a=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let d=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});d!==null&&(s=d.text,d.persist||(a.message.__skipPersist=!0),d.resubmit&&!a.streaming&&n&&n())}let p=Gn()!==null,c;if(e?.postprocessMessage){let d=e.postprocessMessage({...a,text:s,raw:l??a.text??""});c=r?r(d):d}else if(o){let d=a.streaming?Jf(s):s,u=o(d);c=r&&p?r(u):u}else c=Hn(s);return c}};function Ih(e){let t=b("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",a=e?.iconStrokeWidth??.5,s=oe(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var mw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},gw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:mw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vl=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Or(t),r=o.features;o=is(o);let a=ls.getForInstance(o.plugins),{plugin:s,teardown:l}=ah();o.components&&Ln.registerAll(o.components);let p=Mh(),d=o.persistState===!1?null:o.storageAdapter??fl(),u={},g=null,f=!1,h=i=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:v}=m;return v&&(f=!0),y}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")g=i.then(m=>h(m??{messages:[],metadata:{}}));else{let y=h(i??{messages:[],metadata:{}});y.metadata&&(u=pu(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=h({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let A=()=>u,E=i=>{u=i({...u})??{},Ol()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],M=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick],S=cs({parsers:k,handlers:M,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null});S.syncFromMetadata();let C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,W=o.autoFocusInput??!1,w=T,D=C,F=o.layout?.header?.layout,j=!1,O=()=>Bo(o),q=()=>C||O(),Q=O()?!1:C?T:!0,de=!1,be=null,De=()=>{de=!0,be&&clearTimeout(be),be=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},ie=Rh(o,S,De),ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Z=o.features?.scrollToBottom??{},me=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Se=le?new os(we):null,mt=o.features?.eventStream?.maxEvents??2e3,We=le?new ns(mt,Se):null,_e=le?new rs:null,Xe=null,$e=!1,Me=null,ke=0;Se?.open().then(()=>We?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Je={onCopy:i=>{p.emit("message:copy",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.id,"copy").catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",m)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.messageId,i.type).catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),o.messageActions?.onFeedback?.(i)}},Dt=o.statusIndicator??{},Wt=i=>i==="idle"?Dt.idleText??It.idle:i==="connecting"?Dt.connectingText??It.connecting:i==="connected"?Dt.connectedText??It.connected:i==="error"?Dt.errorText??It.error:i==="paused"?Dt.pausedText??It.paused:i==="resuming"?Dt.resumingText??It.resuming:It[i];function Kt(i,m,y,v){if(v==="idle"&&y.idleLink){i.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",i.appendChild(L)}else i.textContent=m}let wt=zg({config:o,showClose:q()}),{wrapper:He,panel:ce,pillRoot:et}=wt.shell,Pe=wt.panelElements,{container:ue,body:ae,messagesWrapper:Le,suggestions:it,textarea:pe,sendButton:ve,sendButtonWrapper:ee,composerForm:P,statusText:U,introTitle:x,introSubtitle:H,closeButton:R,iconHolder:B,headerTitle:K,headerSubtitle:_,header:$,footer:Y,actionsRow:je,rightActions:Re}=Pe,Qe=Pe.leftActions,rt=Pe.setSendButtonMode,G=Pe.micButton,Ue=Pe.micButtonWrapper,he=Pe.attachmentButton,qe=Pe.attachmentButtonWrapper,Fe=Pe.attachmentInput,Ht=Pe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ae.classList.add("persona-relative");let Sl=12,Do=()=>Z.label??"",ms=()=>Z.iconName??"arrow-down",gs=()=>Z.enabled!==!1,fn=()=>me.mode??"anchor-top",no=()=>fn()==="follow"||fn()==="anchor-top"&&pa,Eu=()=>me.anchorTopOffset??16,yy=()=>me.restorePosition??"bottom",ku=()=>me.pauseOnInteraction===!0,Lu=()=>me.showActivityWhilePinned!==!1,Pu=()=>me.announce===!0,kt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let na=b("span","persona-flex persona-items-center"),Ml=b("span",""),Fo=b("span","");Fo.setAttribute("data-persona-scroll-to-bottom-count",""),Fo.style.display="none",kt.append(na,Ml,Fo),ue.appendChild(kt);let oo=b("div","persona-stream-anchor-spacer");oo.setAttribute("aria-hidden","true"),oo.setAttribute("data-persona-anchor-spacer",""),oo.style.flexShrink="0",oo.style.pointerEvents="none",oo.style.height="0px",ae.appendChild(oo);let Oo=b("div","persona-sr-only");Oo.setAttribute("aria-live","polite"),Oo.setAttribute("aria-atomic","true"),Oo.setAttribute("role","status"),Oo.setAttribute("data-persona-live-region",""),Object.assign(Oo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ue.appendChild(Oo);let oa=null,hs=null,Ru=i=>{!Pu()||!i||(hs=i,oa===null&&(oa=setTimeout(()=>{oa=null,hs&&Pu()&&(Oo.textContent=hs),hs=null},400)))},gr=()=>{let m=Y.style.display==="none"?0:Y.offsetHeight;kt.style.bottom=`${m+Sl}px`};gr();let Iu=()=>{let i=!!Do();kt.setAttribute("aria-label",Do()||"Jump to latest"),kt.title=Do(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),na.innerHTML="";let m=oe(ms(),"14px","currentColor",2);m?(na.appendChild(m),na.style.display=""):na.style.display="none",Ml.textContent=Do(),Ml.style.display=i?"":"none"};Iu();let At=null,an=null,Wu=null,Hu=a.find(i=>i.renderHeader);if(Hu?.renderHeader){let i=Hu.renderHeader({config:o,defaultRenderer:()=>{let m=eo({config:o,showClose:q()});return ir(ue,m,o),m.header},onClose:()=>ct(!1,"user")});if(i){let m=ue.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),$=i,wt.header.element=i)}}let Tl=()=>{if(!We)return;if($e=!0,!Xe&&We&&(Xe=ch({buffer:We,getFullHistory:()=>We.getAllFromStore(),onClose:()=>ra(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Xe&&(ae.style.display="none",Y.parentNode?.insertBefore(Xe.element,Y),Xe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Yt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(y=>y&&tt.classList.add(y))}let i=()=>{if(!$e)return;let m=Date.now();m-ke>=200&&(Xe?.update(),ke=m),Me=requestAnimationFrame(i)};ke=0,Me=requestAnimationFrame(i),ln(),p.emit("eventStream:opened",{timestamp:Date.now()})},ra=()=>{if($e){if($e=!1,Xe&&Xe.element.remove(),ae.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&tt.classList.remove(m))}Me!==null&&(cancelAnimationFrame(Me),Me=null),ln(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){let i=o.features?.eventStream?.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");tt=b("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=oe("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let v=Pe.clearChatButtonWrapper,L=Pe.closeButtonWrapper,I=v||L;I&&I.parentNode===$?$.insertBefore(tt,I):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}let by=i=>{let m=o.attachments;if(!m?.enabled)return;let y=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!y){y=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let L=i.querySelector("[data-persona-composer-form]");L?.parentNode?L.parentNode.insertBefore(y,L):i.insertBefore(y,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let L=b("input");L.type="file",L.setAttribute("data-persona-composer-attachment-input",""),L.accept=(m.allowedTypes??Yn).join(","),L.multiple=(m.maxFiles??4)>1,L.style.display="none",L.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(L)}},Bu=a.find(i=>i.renderComposer);if(Bu?.renderComposer){let i=o.composer,m=Bu.renderComposer({config:o,defaultRenderer:()=>jr({config:o}).footer,onSubmit:y=>{if(!z||z.isStreaming())return;let v=y.trim(),L=At?.hasAttachments()??!1;if(!v&&!L)return;uf();let I;L&&(I=[],I.push(...At.getContentParts()),v&&I.push(Mo(v))),z.sendMessage(v,{contentParts:I}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Wu?.()}:void 0});m&&(wt.replaceComposer(m),Y=wt.composer.footer)}let xy=i=>{let m=(...fe)=>{for(let re of fe){let xe=i.querySelector(re);if(xe)return xe}return null},y=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),L=i.querySelector("[data-persona-composer-submit]"),I=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");y&&(P=y),v&&(pe=v),L&&(ve=L),I&&(G=I,Ue=I.parentElement),J&&(U=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(it=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(he=X,qe=X.parentElement),Fe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ht=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(je=se),Qe=m(".persona-widget-composer__left-actions")};by(Y),xy(Y);let ro=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(ro&&(Le.style.maxWidth=ro,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%"),ro&&P&&!O()&&(P.style.maxWidth=ro,P.style.marginLeft="auto",P.style.marginRight="auto"),ro&&it&&!O()&&(it.style.maxWidth=ro,it.style.marginLeft="auto",it.style.marginRight="auto"),ro&&Ht&&!O()&&(Ht.style.maxWidth=ro,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Ht){At=or.fromConfig(o.attachments),At.setPreviewsContainer(Ht),Fe.addEventListener("change",y=>{let v=y.target;At?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=Ih(i);ue.appendChild(m)}let vy=()=>an?.prefetch();if(o.contextMentions?.enabled&&pe&&(an=tg({config:o,textarea:pe,anchor:P??pe,getMessages:()=>z.getMessages(),liveRegionHost:ue}),an)){let i=pe;i.parentElement?.insertBefore(an.contextRow,i);let m=an.affordanceButtons;for(let y=m.length-1;y>=0;y--){let v=m[y];Qe?Qe.insertBefore(v,Qe.firstChild):P?.appendChild(v)}}(()=>{let i=o.layout?.slots??{},m=v=>{switch(v){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Le;case"footer-top":return it;case"composer":return P;case"footer-bottom":return U;default:return null}},y=(v,L)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")$.insertBefore(L,$.firstChild);else if(v==="header-right")$.appendChild(L);else{let I=$.querySelector(".persona-flex-col");I?I.parentNode?.insertBefore(L,I.nextSibling):$.appendChild(L)}break;case"body-top":{let I=ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(L):ae.insertBefore(L,ae.firstChild);break}case"body-bottom":ae.appendChild(L);break;case"footer-top":it.replaceWith(L);break;case"footer-bottom":U.replaceWith(L);break;default:break}};for(let[v,L]of Object.entries(i))if(L)try{let I=L({config:o,defaultContent:()=>m(v)});I&&y(v,I)}catch(I){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,I)}})();let Du=i=>{let y=i.target.closest('button[data-expand-header="true"]');if(!y)return;let v=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");if(I==="reasoning")Kr.has(L)?Kr.delete(L):Kr.add(L),Jg(L,v);else if(I==="tool")Xr.has(L)?Xr.delete(L):Xr.add(L),Qg(L,v,o);else if(I==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=dr.get(L)??V;dr.set(L,!X),th(L,v,o)}qo.delete(L)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let y=Le.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let L=v.toString(),I=Tg(L);!I||I===L||(m.setData("text/plain",I),i.preventDefault())});let El=new Map,Fu=null,Ou="idle",Cy={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wy=(i,m)=>{let{icon:y,label:v}=Cy[m];i.setAttribute("aria-label",v),i.title=v,i.setAttribute("aria-pressed",m==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",m!=="idle"),i.classList.toggle("persona-message-action-loading",m==="loading");let L=oe(y,14,"currentColor",2);L&&(i.innerHTML="",i.appendChild(L))},Nu=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;wy(m,v&&v===Fu?Ou:"idle")})};Le.addEventListener("click",i=>{let y=i.target.closest(".persona-message-action-btn[data-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest("[data-actions-for]");if(!v)return;let L=v.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let V=z.getMessages().find(X=>X.id===L);if(V&&Je.onCopy){let X=V.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let se=oe("check",14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let fe=oe("copy",14,"currentColor",2);fe&&(y.innerHTML="",y.appendChild(fe))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),Je.onCopy(V)}}else if(I==="read-aloud")z.toggleReadAloud(L);else if(I==="upvote"||I==="downvote"){let V=(El.get(L)??null)===I,X=I==="upvote"?"thumbs-up":"thumbs-down";if(V){El.delete(L),y.classList.remove("persona-message-action-active");let se=oe(X,14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se))}else{let se=I==="upvote"?"downvote":"upvote",fe=v.querySelector(`[data-action="${se}"]`);if(fe){fe.classList.remove("persona-message-action-active");let nt=oe(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(fe.innerHTML="",fe.appendChild(nt))}El.set(L,I),y.classList.add("persona-message-action-active");let re=oe(X,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(re)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let ze=z.getMessages().find(pt=>pt.id===L);ze&&Je.onFeedback&&Je.onFeedback({type:I,messageId:ze.id,message:ze})}}}),Le.addEventListener("click",i=>{let y=i.target.closest("button[data-approval-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest(".persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let J=I==="approve"?"approved":"denied",X=z.getMessages().find(fe=>fe.id===L);if(!X?.approval)return;let se=v.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?z.resolveWebMcpApproval(L,J):z.resolveApproval(X.approval,J)});let Ye=null,aa=null,sa=()=>{},ia="none",ys=null,vn={artifacts:[],selectedId:null},_n=!1,Cn=!1,la=!1,hr=!1,_u=()=>hr||vn.artifacts.some(i=>Bn(o.features?.artifacts,i)==="panel"),bs=()=>vn.artifacts.length>0&&!_n&&_u(),lt={current:null},kl=(i,m)=>{let y=z.getArtifactById(m),v=y?.markdown,L=y?.title||"artifact",I=y?.file,J=y?.artifactType??"markdown";if(!v){let se=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let re=z.getMessages().find(xe=>xe.id===se);if(re?.rawContent)try{let xe=JSON.parse(re.rawContent);v=xe?.props?.markdown,L=xe?.props?.title||L,xe?.props?.file&&typeof xe.props.file=="object"&&(I=xe.props.file),!y&&typeof xe?.props?.artifactType=="string"&&(J=xe.props.artifactType)}catch{}}}return{markdown:v,title:L,file:I,artifactType:J}};Le.addEventListener("click",i=>{let y=i.target.closest("[data-download-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:I,title:J,file:V}=kl(y,v);if(!I)return;let{filename:X,mime:se,content:fe}=lg({title:J,markdown:I,file:V}),re=new Blob([fe],{type:se}),xe=URL.createObjectURL(re),ze=document.createElement("a");ze.href=xe,ze.download=X,ze.click(),URL.revokeObjectURL(xe)}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-artifact-custom-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-artifact-custom-action");if(!v)return;let L=y.closest("[data-artifact-inline]"),I=L?null:y.closest("[data-open-artifact]"),J=L?L.getAttribute("data-artifact-inline"):I?.getAttribute("data-open-artifact")??null,X=(L?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===v);if(!X)return;let{markdown:se,title:fe,file:re,artifactType:xe}=kl(y,J??""),ze={artifactId:J,title:fe,artifactType:xe,markdown:se,file:re};try{Promise.resolve(X.onClick(ze)).catch(()=>{})}catch{}}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-copy-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-copy-artifact");if(!v)return;let L=z.getArtifactById(v),I="";if(L)I=Xa(L);else{let{markdown:J,file:V,artifactType:X}=kl(y,v);X==="markdown"&&(I=Xa({id:v,artifactType:"markdown",status:"complete",markdown:J??"",...V?{file:V}:{}}))}I&&navigator.clipboard.writeText(I).then(()=>{let J=oe("check",16,"currentColor",2);J&&(y.replaceChildren(J),setTimeout(()=>{let V=oe("copy",16,"currentColor",2);V&&y.replaceChildren(V)},1500))}).catch(()=>{})}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-expand-artifact-inline]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(_n=!1,hr=!0,Cn=!0,la=!0,z.selectArtifact(v),Un())}),Le.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let y=m.closest("[data-open-artifact]");if(!y)return;let v=y.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),_n=!1,hr=!0,z.selectArtifact(v),Un())}),Le.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let m=i.target;!m.hasAttribute("data-open-artifact")&&!m.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),m.click())});let yr=Pe.composerOverlay,br=(i,m,y)=>{let v=m.trim();if(!v||!lt.current)return;let L=i.getAttribute("data-tool-call-id")??"",I=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:v,answers:y.structured,values:y.values??(y.source==="multi"?v.split(", "):[v]),isFreeText:I,source:y.source},bubbles:!0,composed:!0})),Co(yr,L);let J=lt.current.getMessages().find(V=>V.toolCall?.id===L);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,y.structured??v):lt.current.sendMessage(v)},No=i=>{let m=lt.current;if(!m)return;let y=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(L=>L.toolCall?.id===y);v&&m.persistAskUserQuestionProgress(v,{answers:ei(i,v),currentIndex:xn(i)})},Uu=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Ll=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=xn(i),y=Ir(i);if(m>=y-1)return;let v=lt.current?.getMessages().find(L=>L.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(ti(i,v,o,m+1),No(i))};yr.addEventListener("click",i=>{let y=i.target.closest("[data-ask-user-action]");if(!y)return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;let L=y.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),L==="dismiss"){let I=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I);let J=lt.current?.getMessages().find(V=>V.toolCall?.id===I);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(L==="pick"){let I=y.getAttribute("data-option-label");if(!I)return;let J=v.getAttribute("data-multi-select")==="true",V=vo(v);if(V&&J){let X=Yo(v)[xn(v)],se=new Set(Array.isArray(X)?X:[]);se.has(I)?se.delete(I):se.add(I),wo(v,Array.from(se)),No(v);return}if(V){wo(v,I),No(v),Ll(v);return}if(J){let X=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",X?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!X);let se=v.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=ud(v).length===0);return}br(v,I,{source:"pick",values:[I]});return}if(L==="submit-multi"){let I=ud(v);if(I.length===0)return;br(v,I.join(", "),{source:"multi",values:I});return}if(L==="open-free-text"){let I=v.querySelector('[data-ask-free-text-row="true"]');I&&(I.classList.remove("persona-hidden"),I.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(L==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(L==="submit-free-text"){let J=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(vo(v)){wo(v,J.trim()),No(v),Ll(v);return}br(v,J,{source:"free-text"});return}if(L==="next"||L==="back"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=Yo(v)[xn(v)];(typeof re!="string"||re!==X)&&wo(v,X)}let se=L==="next"?1:-1,fe=xn(v)+se;ti(v,J,o,fe),No(v);return}if(L==="submit-all"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&wo(v,X);let se=ei(v,J);lt.current.persistAskUserQuestionProgress(J,{answers:se,currentIndex:xn(v)});let fe=Uu(se);br(v,fe||"(submitted)",{source:"submit-all",structured:se});return}if(L==="skip"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(xe=>xe.toolCall?.id===I);if(!J)return;let V=vo(v),X=xn(v),se=Ir(v),fe=X>=se-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}wo(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),fe){let xe=ei(v,J),ze=Uu(xe);br(v,ze||"(skipped)",{source:"submit-all",structured:xe});return}ti(v,J,o,X+1),No(v);return}}),yr.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let y=i.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let L=y.value;if(L.trim()){if(vo(v)){wo(v,L.trim()),No(v),Ll(v);return}br(v,L,{source:"free-text"})}});let qu=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let m=i.target;if(m?.tagName==="INPUT"||m?.tagName==="TEXTAREA"||m?.isContentEditable)return;let y=yr.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),I=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];I&&(i.preventDefault(),I.click())};document.addEventListener("keydown",qu);let ao=null,bt=null,da=null,xs=null,Pl=()=>{},Vu=!1,vs="",Cs="";function Rl(){xs?.(),xs=null}let zu=()=>{if(!ao||!bt)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,y=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||y){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let v=ao.firstElementChild;if(!v||v===bt)return;let L=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${L}px`,bt.style.zIndex="5";let I=iu(ao,m),J=v.offsetWidth+I/2-L/2;bt.style.left=`${Math.max(0,J)}px`},ws=()=>{},Ay=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>y?!1:C||Et(o)},As=()=>!Zt(o)||!bs()||e.classList.contains("persona-artifact-narrow-host")||Ay()||(e.ownerDocument.defaultView??window).innerWidth<dw?"none":ou(o)?"detached":"welded",Un=()=>{if(!Ye||!Zt(o))return;as(e,o),ss(e,o),ws();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let y=bs();Ye.setVisible(y),Ye.update(vn),_n?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!1):vn.artifacts.length>0&&_u()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!la&&(Cn=!1),Cn!==Vu){let I=Ye.element;Cn?(vs=I.style.width,Cs=I.style.maxWidth,I.style.removeProperty("width"),I.style.removeProperty("max-width")):(vs&&(I.style.width=vs),Cs&&(I.style.maxWidth=Cs),vs="",Cs=""),Vu=Cn}e.classList.toggle("persona-artifact-expanded",Cn),Ye.setExpanded(Cn);let L=As();L!==ia&&(ia=L,sa()),Pl()};if(Zt(o)){ce.style.position="relative";let i=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Ye=uh(o,{onSelect:y=>lt.current?.selectArtifact(y),onDismiss:()=>{_n=!0,Un()},onToggleExpand:()=>{let y=!Cn,v=vn.selectedId??vn.artifacts[vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(Cn=y,y||(la=!1),Un())}}),Ye.element.classList.add("persona-hidden"),ao=m,m.appendChild(i),m.appendChild(Ye.element),Ye.backdrop&&ce.appendChild(Ye.backdrop),ce.appendChild(m),Pl=()=>{if(!ao||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let v=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let L=e.ownerDocument,I=L.defaultView??window,J=V=>{if(!Ye||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||I.innerWidth<=640)return;V.preventDefault(),Rl();let X=V.clientX,se=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,re=ze=>{let pt=ao.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),dn=iu(ao,I),St=nt?0:v.getBoundingClientRect().width||6,Pt=se-(ze.clientX-X),N=Ch(Pt,pt,dn,St,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${N}px`,Ye.element.style.maxWidth="none",zu()},xe=()=>{L.removeEventListener("pointermove",re),L.removeEventListener("pointerup",xe),L.removeEventListener("pointercancel",xe),xs=null;try{v.releasePointerCapture(V.pointerId)}catch{}};xs=xe,L.addEventListener("pointermove",re),L.addEventListener("pointerup",xe),L.addEventListener("pointercancel",xe);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",J),bt=v,ao.insertBefore(v,Ye.element),da=()=>{v.removeEventListener("pointerdown",J)}}if(bt){let v=bs();bt.classList.toggle("persona-hidden",!v),zu()}},ws=()=>{if(!C||!Ye||(o.launcher?.sidebarMode??!1)||Et(o)&&rn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640;if(L&&v.innerWidth<=I||!gh(o,C))return;let J=o.launcher?.width??o.launcherWidth??pn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";bs()?(ce.style.width=V,ce.style.maxWidth=V):(ce.style.width=J,ce.style.maxWidth=J)},typeof ResizeObserver<"u"&&(aa=new ResizeObserver(()=>{Un()}),aa.observe(ce))}else ce.appendChild(ue);O()&&et&&(Pe.peekBanner&&et.appendChild(Pe.peekBanner),et.appendChild(Y)),e.appendChild(He),et&&e.appendChild(et);let Ss=()=>{if(O()){ce.style.width="100%",ce.style.maxWidth="100%";let Tt=o.launcher?.composerBar??{},nn=He.dataset.state==="expanded",qs=Tt.expandedSize??"anchored";if(!(nn&&qs!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Ma=o.theme?.components?.panel,Vs=ko(o),Tr=($n,Jo)=>$n==null||$n===""?Jo:Qt(Vs,$n)??$n,zs="1px solid var(--persona-border)",Zl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Xo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Tr(Ma?.border,zs),ue.style.borderRadius=Tr(Ma?.borderRadius,Xo),ue.style.boxShadow=Tr(Ma?.shadow,Zl),ue.style.overflow="hidden";return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,L=o.launcher?.detachedPanel===!0,I=o.theme?.components?.panel,J=ko(o),V=(Tt,nn)=>Tt==null||Tt===""?nn:Qt(J,Tt)??Tt,X=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=fe,xe=se&&re&&C,ze=i&&se&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",dn=o.launcher?.zIndex??Gt,St="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",N="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Te=L&&!xe&&!ze;Te?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Oe=Te?St:m||xe?"none":St,Ce=Te?Pt:xe?"none":m?nt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":v?"none":Pt;i&&!xe&&!Te&&(Ce="none",Oe="none");let Ct=Te?N:m||xe?"0":N,ut=V(I?.border,Oe),Ft=V(I?.shadow,Ce),ft=V(I?.borderRadius,Ct),tn=As(),Rt=tn==="detached",Ee=tn==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Ee);let Ne="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Zt(o)&&ou(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let dt=Rt||vt?"none":Ft,gt=Rt?St:Ee?"none":ut,Ze=Rt?N:ft;vt&&(gt="none",Ze="0");let Ie=I?.borderRadius!=null&&I.borderRadius!=="",yt=vt&&!Ie?"0":ft,zt=ae.scrollTop;e.style.cssText="",He.style.cssText="",ce.style.cssText="",ue.style.cssText="",ae.style.cssText="",Y.style.cssText="",$e&&(ae.style.display="none"),(y||v)&&(e.style.minWidth="0");let bn=()=>{if(zt<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===zt)return;let nn=ae.scrollHeight-ae.clientHeight;nn<=0||(ae.scrollTop=Math.min(zt,nn))})};if(xe){He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),He.style.cssText=`
|
|
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=`
|
|
50
50
|
position: fixed !important;
|
|
51
51
|
inset: 0 !important;
|
|
52
52
|
width: 100% !important;
|
|
@@ -56,9 +56,9 @@ _Details: ${n.message}_`:o}var Ua=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: ${pn} !important;
|
|
60
60
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
61
|
-
`,
|
|
61
|
+
`,ue.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 Ua=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
|
+
`,fe.style.cssText=`
|
|
75
75
|
display: flex !important;
|
|
76
76
|
flex-direction: column !important;
|
|
77
77
|
flex: 1 1 0% !important;
|
|
@@ -82,7 +82,7 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
82
82
|
overflow: hidden !important;
|
|
83
83
|
border-radius: 0 !important;
|
|
84
84
|
border: none !important;
|
|
85
|
-
`,
|
|
85
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",ye.style.flexShrink="0",K=!0,vn();return}let js=o?.launcher?.width??o?.launcherWidth??fn;if(!m&&!i)v&&y?(ue.style.width="100%",ue.style.maxWidth="100%"):(ue.style.width=js,ue.style.maxWidth=js);else if(i)if(sn(o).reveal==="emerge"&&!L){let rn=sn(o).width;ue.style.width=rn,ue.style.maxWidth=rn}else ue.style.width="100%",ue.style.maxWidth="100%";if(ks(),ue.style.boxShadow=it,ue.style.borderRadius=gt,Rt?ue.style.border="none":Pe&&(ue.style.border=ct),fe.style.border=ft,fe.style.borderRadius=Je,fe.style.boxShadow=Rt&&!xt?Ne:"",xt&&(fe.style.background="transparent",ie.style.background="transparent",ye.style.background="transparent",ye.style.borderTop="none"),Pe){let Tt=o.features?.artifacts?.layout;As=Tt?.unifiedSplitOuterRadius?.trim()||Tt?.paneBorderRadius?.trim()||pt}else As=null;if(i&&!ge&&!Le&&!Rt&&!Pe&&I?.border===void 0&&(fe.style.border="none",sn(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),i&&!ge&&Pe&&I?.border===void 0&&(sn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),De.style.display="flex",De.style.flexDirection="column",De.style.flex="1 1 0%",De.style.minHeight="0",De.style.maxHeight="100%",De.style.height="100%",v&&(De.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.height="100%",Rt||(ue.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",ye.style.flexShrink="0"),v&&(Le||Rt||xt)&&!i&&(xt||(De.style.padding="var(--persona-panel-inset)"),De.style.background="var(--persona-panel-canvas-bg)"),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"),!m&&!v&&!i&&(In[dt]??In["bottom-right"]).split(" ").forEach(rn=>De.classList.add(rn)),m){let Tt=o.launcher?.sidebarWidth??"420px";L?De.style.cssText=`
|
|
86
86
|
position: fixed !important;
|
|
87
87
|
top: var(--persona-panel-inset) !important;
|
|
88
88
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -93,9 +93,9 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
93
93
|
padding: 0 !important;
|
|
94
94
|
display: flex !important;
|
|
95
95
|
flex-direction: column !important;
|
|
96
|
-
z-index: ${
|
|
97
|
-
${
|
|
98
|
-
`:
|
|
96
|
+
z-index: ${pn} !important;
|
|
97
|
+
${et?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
98
|
+
`:De.style.cssText=`
|
|
99
99
|
position: fixed !important;
|
|
100
100
|
top: 0 !important;
|
|
101
101
|
bottom: 0 !important;
|
|
@@ -106,9 +106,9 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
106
106
|
padding: 0 !important;
|
|
107
107
|
display: flex !important;
|
|
108
108
|
flex-direction: column !important;
|
|
109
|
-
z-index: ${
|
|
110
|
-
${
|
|
111
|
-
`,
|
|
109
|
+
z-index: ${pn} !important;
|
|
110
|
+
${et?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
111
|
+
`,ue.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 Ua=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
|
-
${Rt?"border: none !important;":
|
|
125
|
-
`,
|
|
122
|
+
box-shadow: ${it} !important;
|
|
123
|
+
border-radius: ${gt} !important;
|
|
124
|
+
${Rt?"border: none !important;":Pe?`border: ${ct} !important;`:""}
|
|
125
|
+
`,ue.style.setProperty("width","100%","important"),ue.style.setProperty("max-width","100%","important"),fe.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 Ua=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
131
131
|
min-height: 0 !important;
|
|
132
132
|
max-height: 100% !important;
|
|
133
133
|
overflow: hidden !important;
|
|
134
|
-
border-radius: ${
|
|
135
|
-
border: ${
|
|
136
|
-
${Rt&&!
|
|
137
|
-
${
|
|
138
|
-
`,
|
|
134
|
+
border-radius: ${Je} !important;
|
|
135
|
+
border: ${ft} !important;
|
|
136
|
+
${Rt&&!xt?`box-shadow: ${Ne} !important;`:""}
|
|
137
|
+
${xt?"background: transparent !important;":""}
|
|
138
|
+
`,ye.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;",nn=m?"":"padding-top: 1.25em !important;",qs=m?"":`z-index: ${o.launcher?.zIndex??Gt} !important;`;He.style.cssText+=Tt+nn+qs}bn()};Ss(),rr(e,o),as(e,o),ss(e,o),sa=()=>{Ss(),rr(e,o),as(e,o),ss(e,o),ys?e.style.setProperty("--persona-artifact-welded-outer-radius",ys):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",qu)}),Ve.push(()=>{oa!==null&&clearTimeout(oa)});let Rn=null,In=null;Ve.push(()=>{Rn?.(),Rn=null,In?.(),In=null}),aa&&Ve.push(()=>{aa?.disconnect(),aa=null}),Ve.push(()=>{da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&Ve.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),Xe?.destroy(),Xe=null,We?.destroy(),We=null,Se=null});let _o=null,$u=()=>{_o&&(_o(),_o=null),o.colorScheme==="auto"&&(_o=Nr(()=>{rr(e,o)}))};$u(),Ve.push(()=>{_o&&(_o(),_o=null)}),Ve.push(l);let Ms=o.features?.streamAnimation;if(Ms?.type&&Ms.type!=="none"){let i=zr(Ms.type,Ms.plugins);i&&(Qi(i,e),Ve.push(()=>Ng(e)))}let Ts=sh(it),Uo=null,z,Il=i=>{if(!z)return;let m=i??z.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?oi(m):null;y?Ts.render(y,z,pe,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?Ts.render([],z,pe,m):Ts.render(o.suggestionChips,z,pe,m,o.suggestionChipsConfig)},wn=!1,qo=Lg(),xr=new Map,Vo=new Map,so=new Map,Wl=0,Sy=Gn()!==null,sn=$i(),mn=0,io=null,gn=!1,Es=!1,lo=0,An=null,zo=null,Hl=!1,ks=!1,ca=null,pa=!0,Ls=!1,Ps=null,Rs=!1,$o=()=>{Rs=!0},Bl=null,My=4,Is=24,Ty=80,Dl=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ju=o.voiceRecognition?.autoResume??!1,qn=i=>{p.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},Sn=()=>{E(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Ey=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=pu(u.voiceState),m=!!i.active,y=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("restore"),z.isVoiceActive()&&Sr()}):Fs("restore"))},1e3)},ky=()=>z?Ph(z.getMessages()).filter(i=>!i.__skipPersist):[],Ws=null,Gu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Fl=(i,m)=>{let y=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Gu(m,V)})}catch(J){return Gu(m,J),null}},v=Ws,L=v?v.then(()=>y()??void 0):y();if(!L)return;let I=L.finally(()=>{Ws===I&&(Ws=null)});Ws=I};function Ol(i){if(!d?.save)return;let y={messages:i?Ph(i):z?ky():[],metadata:u,artifacts:vn.artifacts,selectedArtifactId:vn.selectedId};Fl(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let vr=null,Ku=()=>He.querySelector("#persona-scroll-container")||ae,ua=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),gn=!1},Xu=()=>{io!==null&&(cancelAnimationFrame(io),io=null),Es=!1,ua()},Ly=()=>wn&&_l()&&(fn()!=="anchor-top"||Lu()),Nl=()=>{let i=Do()||"Jump to latest",m=Ly();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),lo>0?(Fo.textContent=String(lo),Fo.style.display="",kt.setAttribute("aria-label",`${i} (${lo} new)`)):(Fo.textContent="",Fo.style.display="none",kt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Ju=()=>{lo!==0&&(lo=0,Nl())},_l=()=>no()?!sn.isFollowing():!Wo(ae,Is),ln=()=>{if(!gs()||$e){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==ue&&ue.appendChild(kt),gr();let m=Fn(ae)>0&&_l();m?Nl():Ju(),kt.style.display=m?"":"none"},fa=()=>{sn.pause()&&(Xu(),ln())},co=()=>{sn.resume(),Ju(),ln()},po=(i=!1)=>{no()&&sn.isFollowing()&&(!i&&!wn||(io!==null&&(cancelAnimationFrame(io),io=null),Es=!0,io=requestAnimationFrame(()=>{io=null,Es=!1,sn.isFollowing()&&Py(Ku(),i?220:140)})))},Qu=(i,m,y,v=()=>!0)=>{let L=i.scrollTop,I=m(),J=I-L;if(ua(),Math.abs(J)<1){gn=!0,i.scrollTop=I,mn=i.scrollTop,gn=!1;return}let V=performance.now();gn=!0;let X=fe=>1-Math.pow(1-fe,3),se=fe=>{if(!v()){ua();return}let re=m();re!==I&&(I=re,J=I-L);let xe=fe-V,ze=Math.min(xe/y,1),pt=X(ze),nt=L+J*pt;i.scrollTop=nt,mn=i.scrollTop,ze<1?vr=requestAnimationFrame(se):(i.scrollTop=I,mn=i.scrollTop,vr=null,gn=!1)};vr=requestAnimationFrame(se)},Py=(i,m=500)=>{let y=Fn(i)-i.scrollTop;if(Math.abs(y)<1){mn=i.scrollTop;return}if(Math.abs(y)>=Ty){ua(),gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1;return}Qu(i,()=>Fn(i),m,()=>sn.isFollowing())},Yu=()=>{let i=Ku();gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1,ln()},Zu=i=>{let m=0,y=i;for(;y&&y!==ae;)m+=y.offsetTop,y=y.offsetParent;return m},Ry=()=>{let i=ae.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ae.ownerDocument.getSelection()},Hs=()=>Hg(Ry(),ae),ef=()=>{if(yy()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(I=>I.role==="user");if(!m)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ae.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let L=Math.min(Math.max(0,Zu(v)-Eu()),Fn(ae));return gn=!0,ae.scrollTop=L,mn=ae.scrollTop,gn=!1,fn()==="follow"&&!Wo(ae,Is)&&sn.pause(),ln(),!0},tf=i=>{oo.style.height=`${Math.max(0,Math.round(i))}px`,An&&(An.spacerHeight=Math.max(0,i))},ma=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),ua(),An=null,oo.style.height="0px"},nf=i=>{zo!==null&&cancelAnimationFrame(zo),zo=requestAnimationFrame(()=>{zo=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ae.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Zu(y),L=An?.spacerHeight??0,I=ae.scrollHeight-L,{targetScrollTop:J,spacerHeight:V}=Bg({anchorOffsetTop:v,topOffset:Eu(),viewportHeight:ae.clientHeight,contentHeight:I});An={initialSpacerHeight:V,contentHeightAtAnchor:I,spacerHeight:V},tf(V),Qu(ae,()=>J,220)})},Iy=()=>{if(no()){if(!sn.isFollowing()||Wo(ae,1))return;po(!wn);return}if(An&&An.initialSpacerHeight>0){let i=ae.scrollHeight-An.spacerHeight,m=Dg({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:i});m!==An.spacerHeight&&tf(m)}ln()},Wy=i=>{let m=fn();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(pa=!1,Ls=!0,Rs=!1,Ps=i,nf(i))},Hy=()=>{if(fn()==="anchor-top"){if(Ls){pa=!1;return}pa=!0,ma(),co(),po(!0)}},By=i=>{if(fn()!=="anchor-top"||!Ls||Rs||Hs())return;let m=ca===null;for(let y of i){if(!m){y.id===ca&&(m=!0);continue}if(Wg(y)){if(y.id===Ps)return;Ps=y.id,nf(y.id);return}}},Dy=i=>{let m=new Map;i.forEach(y=>{let v=Dl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(p.emit("assistant:message",y),!ks&&(fn()!=="anchor-top"||Lu())&&_l()&&(lo+=1,Nl(),ln(),Ru(lo===1?"1 new message below.":`${lo} new messages below.`))),y.role==="assistant"&&v?.streaming&&y.streaming===!1&&p.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(v?y.approval.status!=="pending"&&p.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):p.emit("approval:requested",{approval:y.approval,message:y}))}),Dl.clear(),m.forEach((y,v)=>{Dl.set(v,y)})},Bs=(i,m)=>{let y=m==="user"?"user":"assistant",v=o.layout?.messages?.[y],L=v?.width??"content",I=v?.maxWidth??(L==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${m}`,`persona-message-width-${L}`),i.classList.toggle("persona-justify-end",m==="user"),i.setAttribute("data-message-role",m),i.setAttribute("data-message-width",L),i.style.setProperty("--persona-message-row-max-width",I)},jo=(i,m)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${i}`,y.setAttribute("data-wrapper-id",i),Bs(y,m),y},Fy=(i,m,y)=>{let v=document.createElement("div"),I=(()=>{let N=a.find(Te=>Te.renderLoadingIndicator);if(N?.renderLoadingIndicator)return N.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(N,Te)=>Te==null?!1:typeof Te=="string"?(N.textContent=Te,!0):(N.appendChild(Te),!0),V=new Set,X=new Map,se=new Set,fe=a.some(N=>N.renderAskUserQuestion),re=[],xe=[],ze=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(m.forEach(N=>{V.add(N.id),X.set(N.id,N.role);let Te=fe&&Xn(N),Oe=pt&&N.variant==="approval"&&!!N.approval,Ce=!Te&&N.role==="assistant"&&!N.variant&&ze&&ps(N);!Oe&&so.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id)),!Ce&&Vo.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Vo.delete(N.id));let Ct=Xn(N)?`:${N.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${N.agentMetadata?.askUserQuestionAnswers?Object.keys(N.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=kg(N,Wl)+Ct,Ft=Te||Oe||Ce?null:Pg(qo,N.id,ut);if(Ft){v.appendChild(Ft.cloneNode(!0)),Xn(N)&&N.toolCall?.id&&N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let ft=null,tn=a.find(Ne=>!!(N.variant==="reasoning"&&Ne.renderReasoning||N.variant==="tool"&&Ne.renderToolCall||!N.variant&&Ne.renderMessage)),Rt=o.layout?.messages;if(Xn(N)&&N.agentMetadata?.askUserQuestionAnswered===!0){xr.delete(N.id),i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ba(N)&&o.features?.suggestReplies?.enabled!==!1)return;if(Xn(N)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=a.find(qt=>typeof qt.renderAskUserQuestion=="function");if(Ne&<.current){let qt=xr.get(N.id),Vt=qt!==ut,vt=null;if(Vt){let{payload:Ze,complete:Ie}=Jn(N),yt=N.id,zt=()=>lt.current?.getMessages().find(bn=>bn.id===yt);vt=Ne.renderAskUserQuestion({message:N,payload:Ze,complete:Ie,resolve:bn=>{let Sa=zt();Sa&<.current?.resolveAskUserQuestion(Sa,bn)},dismiss:()=>{let bn=zt();bn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(bn),lt.current?.resolveAskUserQuestion(bn,"(dismissed)"))},config:o})}let dt=qt!=null;if(Vt&&vt===null&&!dt){N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let gt=jo(N.id,N.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),re.push({messageId:N.id,fingerprint:ut,bubble:vt});return}else{N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}}else if(Oe){let Ne=a.find(dt=>typeof dt.renderApproval=="function")??s,Vt=so.get(N.id)!==ut,vt=null;if(Vt&&Ne?.renderApproval){let dt=N.id,gt=(Ze,Ie)=>{let yt=lt.current?.getMessages().find(zt=>zt.id===dt);yt?.approval&&(yt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(yt.id,Ze):lt.current?.resolveApproval(yt.approval,Ze,Ie))};vt=Ne.renderApproval({message:N,defaultRenderer:()=>ll(N,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if(Vt&&vt===null)i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id),ft=ll(N,o);else{let dt=jo(N.id,N.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),v.appendChild(dt),nt.push({messageId:N.id,fingerprint:ut,bubble:vt});return}}else if(tn)if(N.variant==="reasoning"&&N.reasoning&&tn.renderReasoning){if(!ge)return;ft=tn.renderReasoning({message:N,defaultRenderer:()=>Jp(N,o),config:o})}else if(N.variant==="tool"&&N.toolCall&&tn.renderToolCall){if(!ne)return;ft=tn.renderToolCall({message:N,defaultRenderer:()=>Yp(N,o),config:o})}else tn.renderMessage&&(ft=tn.renderMessage({message:N,defaultRenderer:()=>{let Ne=Gr(N,y,Rt,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o});return N.role!=="user"&&lu(Ne,N,o,z),Ne},config:o}));if(!ft&&Ce){let Ne=hl(N);if(Ne){let qt=Vo.get(N.id),Vt=qt!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&Ln.getOptions(Ne.component)?.bubbleChrome!==!1,dt=null;if(Vt){let gt=gl(Ne,{config:o,message:N,transform:y});if(gt&&Ne.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),Ie=Ze?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ie):Ie,zt=Ie?i.querySelector(`#wrapper-${N.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Ze&&zt&&zt!==Ze&&wg(zt)&&(Ze===gt?gt=zt:Ze.replaceWith(zt))}if(gt)if(vt){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${N.id}`,Ze.setAttribute("data-message-id",N.id),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${N.id}`,Ze.setAttribute("data-message-id",N.id),Ze.setAttribute("data-persona-component-directive","true"),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=Ze}}if(dt||qt!=null){let gt=jo(N.id,N.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),xe.push({messageId:N.id,fingerprint:ut,bubble:dt});return}}}if(!ft)if(N.variant==="reasoning"&&N.reasoning){if(!ge)return;ft=Jp(N,o)}else if(N.variant==="tool"&&N.toolCall){if(!ne)return;ft=Yp(N,o)}else if(N.variant==="approval"&&N.approval){if(o.approval===!1)return;ft=ll(N,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&N.role==="user"?ft=Ne.renderUserMessage({message:N,config:o,streaming:!!N.streaming}):Ne?.renderAssistantMessage&&N.role==="assistant"?ft=Ne.renderAssistantMessage({message:N,config:o,streaming:!!N.streaming}):ft=Gr(N,y,Ne,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o}),N.role!=="user"&&ft&&lu(ft,N,o,z)}let Ee=jo(N.id,N.role);Ee.appendChild(ft),Rg(qo,N.id,ut,Ee),v.appendChild(Ee)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Oe=Te.getAttribute("data-persona-ask-sheet-for");Oe&&!se.has(Oe)&&Co(Pe.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let N=[],Te=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";m.forEach(Ce=>{if(Ce.variant==="tool"&&Ce.toolCall&&ne){Te.push(Ce);return}Ce.variant==="reasoning"&&!ge||((Te.length>1||Oe&&Te.length>0)&&N.push(Te),Te=[])}),(Te.length>1||Oe&&Te.length>0)&&N.push(Te),N.forEach(Ce=>{let Ct=Ce.map(Ne=>Array.from(v.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===Ne.id)).filter(Ne=>!!Ne);if(Ct.length<(Oe?1:2))return;let ut=jo(`tool-group-${Ce[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Ce[0].id}`;let tn=`Called ${Ce.length} ${Ce.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Ce,toolCalls:Ce.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:tn,config:o});J(ft,Rt)||(ft.textContent=tn);let Ee=document.createElement("div");Ee.className="persona-tool-group-stack persona-flex persona-flex-col",Ee.id=`tool-group-stack-${Ce[0].id}`,Ee.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(ft),Oe||Ft.appendChild(Ee),ut.appendChild(Ft),Ct[0].before(ut),Ct.forEach((Ne,qt)=>{if(Oe){Ne.remove();return}Ne.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),qt<Ct.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(Ne),Ee.appendChild(Vt)})})}Ig(qo,V);let dn=m.some(N=>N.role==="assistant"&&N.streaming),St=m[m.length-1],Pt=St?.role==="assistant"&&!St.streaming&&St.variant!=="approval";if(wn&&m.some(N=>N.role==="user")&&!dn&&!Pt){let N={config:o,streaming:!0,location:"standalone",defaultRenderer:lr},Te=a.find(Ce=>Ce.renderLoadingIndicator),Oe=null;if(Te?.renderLoadingIndicator&&(Oe=Te.renderLoadingIndicator(N)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(N)),Oe===null&&(Oe=lr()),Oe){let Ce=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Ce.className=Ct?Kp("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ce.setAttribute("data-typing-indicator","true"),Ct&&(Ce.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Ce.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ce.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ce.appendChild(Oe);let Ft=jo("typing-indicator","assistant");Ft.appendChild(Ce),v.appendChild(Ft)}}if(!wn&&m.length>0){let N=m[m.length-1],Te={config:o,lastMessage:N,messageCount:m.length},Oe=a.find(Ct=>Ct.renderIdleIndicator),Ce=null;if(Oe?.renderIdleIndicator&&(Ce=Oe.renderIdleIndicator(Te)),Ce===null&&o.loadingIndicator?.renderIdle&&(Ce=o.loadingIndicator.renderIdle(Te)),Ce){let Ct=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Ct.className=ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Ce);let Ft=jo("idle-indicator","assistant");Ft.appendChild(Ct),v.appendChild(Ft)}}if(em(v),zi(i,v),od(i),re.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of re){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),xr.set(N,Te)))}if(xr.size>0)for(let N of xr.keys())V.has(N)||xr.delete(N);if(xe.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of xe){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),Vo.set(N,Te)))}if(Vo.size>0)for(let N of Vo.keys())V.has(N)||Vo.delete(N);if(nt.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of nt){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),so.set(N,Te)))}if(so.size>0)for(let N of so.keys())V.has(N)||so.delete(N)},ga=(i,m,y)=>{Fy(i,m,y),Nu()},ha=null,Oy=()=>{if(ha)return;let i=y=>{let v=y.composedPath();v.includes(He)||et&&v.includes(et)||ct(!1,"user")};ha=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},of=()=>{if(!ha)return;(e.ownerDocument??document).removeEventListener("pointerdown",ha,!0),ha=null};Ve.push(()=>of());let ya=null,Ny=()=>{if(ya)return;let i=y=>{y.key==="Escape"&&(y.isComposing||ct(!1,"user"))};ya=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},rf=()=>{if(!ya)return;(e.ownerDocument??document).removeEventListener("keydown",ya,!0),ya=null};Ve.push(()=>rf());let ba=!1,af=new Set,_y=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Cr=()=>{if(!O())return;let i=Pe.peekBanner,m=Pe.peekTextNode;if(!i||!m)return;if(Q){i.classList.remove("persona-pill-peek--visible");return}let y=z?.getMessages()??[],v;for(let St=y.length-1;St>=0;St--){let Pt=y[St];if(Pt.role==="assistant"&&Pt.content){v=Pt;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let L=v.content,I=!!v.streaming,J=_y(),V=Ki(J),X=V.type!=="none"?zr(V.type,J?.plugins):null,se=X?.isAnimating?.(v)===!0,fe=X!==null&&(I||se);fe&&X&&!af.has(X.name)&&(Qi(X,e),af.add(X.name));let re=fe&&X?.containerClass?X.containerClass:null,xe=m.dataset.personaPeekStreamClass??null;xe&&xe!==re&&(m.classList.remove(xe),delete m.dataset.personaPeekStreamClass),re&&xe!==re&&(m.classList.add(re),m.dataset.personaPeekStreamClass=re),fe?(m.style.setProperty("--persona-stream-step",`${V.speed}ms`),m.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let ze=fe?Xi(L,V.buffer,X,v,I):L;if(fe&&V.placeholder==="skeleton"&&I&&(!ze||!ze.trim())){let St=document.createElement("div"),Pt=Za();Pt.classList.add("persona-pill-peek__skeleton"),St.appendChild(Pt),zi(m,St)}else{let St=Math.max(0,ze.length-100),Pt=ze.length>100?ze.slice(-100):ze,N=Hn(Pt);if(!fe||!X){let Te=ze.length>100?`\u2026${Pt}`:Pt;m.textContent!==Te&&(m.textContent=Te)}else{let Te=N;(X.wrap==="char"||X.wrap==="word")&&(Te=Ya(N,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:St}));let Oe=document.createElement("div");if(Oe.innerHTML=Te,X.useCaret&&Pt.length>0){let Ce=Ji(),Ct=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=Ct[Ct.length-1];ut?.parentNode?ut.parentNode.insertBefore(Ce,ut.nextSibling):Oe.appendChild(Ce)}zi(m,Oe),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let dn=wn||ba;i.classList.toggle("persona-pill-peek--visible",dn)};if(O()){let i=Pe.peekBanner;if(i){let v=L=>{L.preventDefault(),L.stopPropagation(),ct(!0,"user")};i.addEventListener("pointerdown",v),Ve.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ba||(ba=!0,Cr())},y=()=>{ba&&(ba=!1,Cr())};ce.addEventListener("pointerenter",m),ce.addEventListener("pointerleave",y),Ve.push(()=>{ce.removeEventListener("pointerenter",m),ce.removeEventListener("pointerleave",y)}),et&&(et.addEventListener("pointerenter",m),et.addEventListener("pointerleave",y),Ve.push(()=>{et.removeEventListener("pointerenter",m),et.removeEventListener("pointerleave",y)}))}let Uy=i=>{let m=o.launcher?.composerBar??{},y=m.expandedSize??"anchored",v=m.bottomOffset??"16px",L=m.collapsedMaxWidth,I=m.expandedMaxWidth??"880px",J=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",re=He.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",et){let xe=et.style;xe.bottom=v,xe.width=L??""}if(i&&y!=="fullscreen"){if(y==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=V,re.maxWidth=se,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${fe})`,re.top=J,re.width=I,re.maxWidth=se}},xa=()=>{if(!q())return;if(O()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Q?"expanded":"collapsed";He.dataset.state=fe,He.dataset.expandedSize=se,et&&(et.dataset.state=fe,et.dataset.expandedSize=se),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Uy(Q),ue.style.display=Q?"flex":"none",Ss(),Q?(Oy(),Ny()):(of(),rf()),Cr();return}let i=Et(o),m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,L=m.innerWidth<=y,I=v&&L&&C,J=rn(o).reveal;Q?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Xt&&(Xt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!I?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":Xt&&(Xt.style.display=i?"none":""))},ct=(i,m="user")=>{if(!q()||Q===i)return;let y=Q;Q=i,xa();let v=(()=>{let I=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=J.innerWidth<=X,fe=Et(o)&&V&&se,re=O()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return I||V&&se&&C||fe||re})();if(Q&&v){if(!Rn){let I=e.getRootNode(),J=I instanceof ShadowRoot?I.host:e.closest(".persona-host");J&&(Rn=Op(J,o.launcher?.zIndex??Gt))}In||(In=Np(e.ownerDocument))}else Q||(Rn?.(),Rn=null,In?.(),In=null);Q&&(wa(),ef()||(fn()==="follow"?po(!0):Yu()));let L={open:Q,source:m,timestamp:Date.now()};Q&&!y?p.emit("widget:opened",L):!Q&&y&&p.emit("widget:closed",L),p.emit("widget:state",{open:Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()})},Ul=i=>{rt(i?"stop":"send"),G&&(G.disabled=i),Ts.buttons.forEach(m=>{m.disabled=i}),Y.dataset.personaComposerStreaming=i?"true":"false",Y.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},ql=()=>{Ke.active||pe&&pe.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ql(),200)});let sf=()=>{x.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",H.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",pe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ae.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(ae.classList.remove("persona-gap-3"),ae.classList.add("persona-gap-6")):(ae.classList.remove("persona-gap-6"),ae.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(ve.textContent=o.copy?.sendButtonLabel??"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{E(m=>({...m,sessionId:i}))}});let Go=null,qy=()=>{Go==null&&(Go=setInterval(()=>{let i=Le.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Go),Go=null;return}let m=Date.now();i.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=ai(m-v))})},100))},Vl=(i,m)=>{if(Object.is(i,m))return!0;if(i===null||m===null||typeof i!="object"||typeof m!="object")return!1;if(Array.isArray(i)||Array.isArray(m))return!Array.isArray(i)||!Array.isArray(m)||i.length!==m.length?!1:i.every((J,V)=>Vl(J,m[V]));let y=i,v=m,L=Object.keys(y),I=Object.keys(v);return L.length===I.length&&L.every(J=>Object.prototype.hasOwnProperty.call(v,J)&&Vl(y[J],v[J]))},lf=i=>{let{content:m,rawContent:y,llmContent:v,...L}=i;return L},zl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ps(i),Vy=(i,m,y)=>{if(i.length!==m.length)return!1;let v=i[y.index],L=m[y.index];return!v||!L||v.id!==y.id||L.id!==y.id?!1:(!Object.is(v.content,L.content)||!Object.is(v.rawContent,L.rawContent)||!Object.is(v.llmContent,L.llmContent))&&zl(v)&&zl(L)&&Vl(lf(v),lf(L))},df=null,wr=null,Ko=null,Vn=null,Ds=i=>{df=i;let m,y;wr=null;for(let L=i.length-1;L>=0;L-=1){let I=i[L];if(!m&&I.role==="user"&&(m=I),!y&&I.role==="assistant"&&(y=I),!wr&&zl(I)&&(wr={index:L,id:I.id}),m&&y&&wr)break}ga(Le,i,ie),Pp(Le,vn.artifacts,{suppressTransition:wn}),qy(),Il(i),po(!wn),Dy(i),i.length===0&&(ma(),pa=!0,Ls=!1,Ps=null,Rs=!1),!Hl||ks?(Hl=!0,ca=m?.id??null,Bl=y?.id??null):m&&m.id!==ca?(ca=m.id,Wy(m.id)):y&&y.id!==Bl&&Hy(),y&&(Bl=y.id),By(i);let v=Ke.lastUserMessageId;m&&m.id!==v&&(Ke.lastUserMessageId=m.id,p.emit("user:message",m)),Ke.lastUserMessageWasVoice=!!m?.viaVoice,Ol(i),Cr()},$l=()=>{Vn!==null&&(cancelAnimationFrame(Vn),Vn=null);let i=Ko;Ko=null,i&&Ds(i)},cf=()=>{Vn!==null&&cancelAnimationFrame(Vn),Vn=null,Ko=null},zy=i=>{let m=Ko??df;if(wn&&m&&wr&&Vy(m,i,wr)){Ko=i,Vn===null&&(Vn=requestAnimationFrame(()=>{Vn=null;let y=Ko;Ko=null,y&&Ds(y)}));return}if(i.length===0){cf(),Ds(i);return}$l(),Ds(i)};z=new Fr(o,{onMessagesChanged(i){zy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Kt(U,(v=>v==="idle"?m.idleText??It.idle:v==="connecting"?m.connectingText??It.connecting:v==="connected"?m.connectedText??It.connected:v==="error"?m.errorText??It.error:v==="paused"?m.pausedText??It.paused:v==="resuming"?m.resumingText??It.resuming:It[v])(i),m,i)},onStreamingChanged(i){i||(z?.getMessages().length===0?cf():$l()),wn=i,Ul(i),z&&ga(Le,z.getMessages(),ie),i||po(!0),ln(),Ru(i?"Responding\u2026":"Response complete."),Cr()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":zn(),Sr();break;case"processing":zn(),tb();break;case"speaking":zn(),nb();break;default:i==="idle"&&z.isBargeInActive()?(zn(),Sr(),G?.setAttribute("aria-label","End voice session")):(Ke.active=!1,zn(),qn("system"),Sn());break}},onArtifactsState(i){vn=i,i.artifacts.length===0&&(hr=!1),Pp(Le,i.artifacts,{suppressTransition:wn}),Un(),Ol()},onReconnect(i){let{executionId:m,lastEventId:y}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:m,after:y}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:m,after:y,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:m,after:y})}}),lt.current=z,Ve.push(()=>z.cancel());let jl=null;if(z.onReadAloudChange((i,m)=>{Fu=i,Ou=m,Nu();let y=i??jl;i&&(jl=i);let v=y?z.getMessages().find(L=>L.id===y)??null:null;p.emit("message:read-aloud",{messageId:y,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(jl=null)}),Hl=!0,o.voiceRecognition?.provider?.type==="runtype")try{z.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&z.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(We||o.onSSEEvent)&&z.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),_e?.processEvent(i,m),We?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let pf=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};g?g.then(i=>{if(i){if(i.metadata&&(u=pu(i.metadata),S.syncFromMetadata()),i.messages?.length){ks=!0;try{z.hydrateMessages(i.messages)}finally{ks=!1}}i.artifacts?.length&&z.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>pf()):pf();let uf=()=>{!O()||Q||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},$y=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[y,v]=await Promise.allSettled([i.finalize(),m.finalize()]),L=[];return y.status==="fulfilled"?L.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),v.status==="fulfilled"?L.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),gw(L)}}:i:m,jy=()=>{let m=pe.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},va=!1,Gy=async i=>{let m=pe.value.trim(),y=At?.hasAttachments()??!1,v=m?await(an?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){pe.value="",pe.style.height="auto",Ca(),an?.clear();return}let L=an?.collectForSubmit()??null,I=v?.kind==="server"?v.mentions:null,J=$y(L,I),V=v?.kind==="prompt"?v.sendText:m,X=!!L&&L.refs.length>0;if(!V&&!y&&!X&&!I)return;uf();let se;y&&(se=[],se.push(...At.getContentParts()),V&&se.push(Mo(V)));let fe=v?.kind==="prompt"?void 0:jy();pe.value="",pe.style.height="auto",Ca(),z.sendMessage(V,{contentParts:se,mentions:J??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),y&&At.clearAttachments(),L&&an?.clear()},Gl=async i=>{if(!va){va=!0;try{await Gy(i)}finally{va=!1}}},ff=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),_e?.reset(),Xe?.update();return}va||Gl()},Ky=()=>o.features?.composerHistory!==!1,Kl={...Wp},Xl=!1,Ca=()=>{Kl={...Wp}},Xy=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Jy=i=>{if(!pe)return;Xl=!0,pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),Xl=!1;let m=pe.value.length;pe.setSelectionRange(m,m)},Qy=i=>{Xl||(i.isComposing||an?.handleInput(i.inputType??void 0),Ca())},Yy=i=>{if(pe&&!(!i.isComposing&&an?.handleKeydown(i))){if(Ky()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=pe.selectionStart===0&&pe.selectionEnd===0,y=Eg({direction:i.key==="ArrowUp"?"up":"down",history:Xy(),currentValue:pe.value,atStart:m,state:Kl});if(Kl=y.state,y.handled){i.preventDefault(),y.value!==void 0&&Jy(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(va){i.preventDefault();return}Ca(),i.preventDefault(),ve.click()}}},mf=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(ue)&&(z.cancel(),_e?.reset(),Xe?.update(),Ca(),i.preventDefault(),i.stopImmediatePropagation())},Zy=async i=>{if(o.attachments?.enabled!==!0||!At)return;let m=pw(i.clipboardData);m.length!==0&&(i.preventDefault(),await At.handleFiles(m))},hn=null,Wn=!1,Ar=null,xt=null,gf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fs=(i="user")=>{if(Wn||z.isStreaming())return;let m=gf();if(!m)return;hn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;hn.continuous=!0,hn.interimResults=!0,hn.lang="en-US";let L=pe.value;hn.onresult=I=>{let J="",V="";for(let se=0;se<I.results.length;se++){let fe=I.results[se],re=fe[0].transcript;fe.isFinal?J+=re+" ":V=re}let X=L+J+V;pe.value=X,Ar&&clearTimeout(Ar),(J||V)&&(Ar=window.setTimeout(()=>{pe.value.trim()&&hn&&Wn&&(uo(),Gl({viaVoice:!0}))},v))},hn.onerror=I=>{I.error!=="no-speech"&&uo()},hn.onend=()=>{if(Wn){let I=pe.value.trim();I&&I!==L.trim()&&Gl({viaVoice:!0}),uo()}};try{if(hn.start(),Wn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),qn(i),Sn(),G){let I=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:I.iconName??"mic",iconSize:parseFloat(I.iconSize??o.sendButton?.size??"40")||24};let J=I.recordingBackgroundColor,V=I.recordingIconColor,X=I.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let se=G.querySelector("svg");se&&se.setAttribute("stroke",V)}X&&(G.style.borderColor=X),G.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(i="user")=>{if(Wn){if(Wn=!1,Ar&&(clearTimeout(Ar),Ar=null),hn){try{hn.stop()}catch{}hn=null}if(Ke.active=!1,qn(i),Sn(),G){if(G.classList.remove("persona-voice-recording"),xt){G.style.backgroundColor=xt.backgroundColor,G.style.color=xt.color,G.style.borderColor=xt.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",xt.color||"currentColor"),xt=null}G.setAttribute("aria-label","Start voice recognition")}}},eb=(i,m)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",L=i?.provider?.type==="custom";if(!(y||v||L))return null;let J=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button";let X=i?.tooltipText??"Start voice recognition";V.setAttribute("aria-label",X);let se=i?.iconName??"mic",fe=m?.size??"40px",re=i?.iconSize??fe,xe=parseFloat(re)||24,ze=i?.backgroundColor??m?.backgroundColor,pt=i?.iconColor??m?.textColor;V.style.width=re,V.style.height=re,V.style.minWidth=re,V.style.minHeight=re,V.style.fontSize="18px",V.style.lineHeight="1",pt?V.style.color=pt:V.style.color="var(--persona-text, #111827)";let dn=oe(se,xe,pt||"currentColor",1.5);dn?V.appendChild(dn):V.textContent="\u{1F3A4}",ze?V.style.backgroundColor=ze:V.style.backgroundColor="",i?.borderWidth&&(V.style.borderWidth=i.borderWidth,V.style.borderStyle="solid"),i?.borderColor&&(V.style.borderColor=i.borderColor),i?.paddingX&&(V.style.paddingLeft=i.paddingX,V.style.paddingRight=i.paddingX),i?.paddingY&&(V.style.paddingTop=i.paddingY,V.style.paddingBottom=i.paddingY),J.appendChild(V);let St=i?.showTooltip??!1;return Ut({anchor:V,trigger:J,text:()=>V.getAttribute("aria-label")??X,enabled:St}),{micButton:V,micButtonWrapper:J}},Jl=()=>{if(!G||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Ql=(i,m)=>{if(!G)return;let y=G.querySelector("svg");y&&y.remove();let v=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),L=oe(i,v,m,1.5);L&&G.appendChild(L)},Os=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Sr=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Os(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let L=G.querySelector("svg");L&&L.setAttribute("stroke",y)}v&&(G.style.borderColor=v),G.setAttribute("aria-label","Stop voice recognition")},tb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??xt?.color??"",L=i.processingBackgroundColor??xt?.backgroundColor??"",I=i.processingBorderColor??xt?.borderColor??"";Os(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=I;let J=v||"currentColor";G.style.color=J,Ql(y,J),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},nb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??y,L=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),I=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),J=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");Os(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=I,G.style.borderColor=J;let V=L||"currentColor";G.style.color=V,Ql(v,V);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",X),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},zn=()=>{G&&(Os(),xt&&(G.style.backgroundColor=xt.backgroundColor??"",G.style.color=xt.color??"",G.style.borderColor=xt.borderColor??"",Ql(xt.iconName,xt.color||"currentColor"),xt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ns=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=z.getVoiceStatus(),m=z.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()});return}z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),Ke.manuallyDeactivated=!z.isVoiceActive(),Sn(),qn("user"),z.isVoiceActive()?Sr():zn()});return}if(Wn){let i=pe.value.trim();Ke.manuallyDeactivated=!0,Sn(),uo("user"),i&&(pe.value="",pe.style.height="auto",z.sendMessage(i))}else Ke.manuallyDeactivated=!1,Sn(),Fs("user")};Wu=Ns,G&&(G.addEventListener("click",Ns),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),zn()):uo("system"),G&&G.removeEventListener("click",Ns)}));let ob=p.on("assistant:complete",()=>{ju&&(Ke.active||Ke.manuallyDeactivated||ju==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("auto"),z.isVoiceActive()&&Sr()}):Fs("auto"))},600))});Ve.push(ob);let rb=p.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});Ve.push(rb);let hf=()=>{ct(!Q,"user")},Ot=null,Xt=null;if(C&&!O()){let{instance:i,element:m}=zp({config:o,plugins:a,onToggle:hf});Ot=i,i||(Xt=m)}Ot?e.appendChild(Ot.element):Xt&&e.appendChild(Xt),xa(),Il(),sf(),Ul(z.isStreaming()),ef()||(fn()==="follow"?po(!0):Yu()),Ey(),W&&(!C||O()?setTimeout(()=>ql(),0):Q&&setTimeout(()=>ql(),200));let wa=()=>{if(O()){gr(),xa();return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640,J=v.innerWidth<=I,V=L&&J&&C;try{if(V){sa(),ia=As();return}let X=!1;j&&(j=!1,sa(),X=!0);let se=As();if(!X&&se!==ia&&(sa(),X=!0),ia=se,X&&Pl(),!C&&!i){ce.style.height="",ce.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??pn;ce.style.width=re,ce.style.maxWidth=re}if(ws(),!y){let fe=v.innerHeight,re=64,xe=o.launcher?.heightOffset??0,ze=Math.max(200,fe-re),pt=Math.min(640,ze),nt=Math.max(200,pt-xe);ce.style.height=`${nt}px`}}finally{if(gr(),xa(),Q&&C){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,xe=Et(o)&&re&&se,ze=fe||re&&se&&C||xe;if(ze&&!In){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!Rn&&(Rn=Op(nt,o.launcher?.zIndex??Gt)),In=Np(e.ownerDocument)}else ze||(Rn?.(),Rn=null,In?.(),In=null)}}};wa();let yf=e.ownerDocument.defaultView??window;if(yf.addEventListener("resize",wa),Ve.push(()=>yf.removeEventListener("resize",wa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gr()});i.observe(Y),Ve.push(()=>i.disconnect())}mn=ae.scrollTop;let bf=Fn(ae),xf=()=>{let i=ae.scrollTop,m=Fn(ae),y=m<bf;if(bf=m,!no()){mn=i,ln();return}let{action:v,nextLastScrollTop:L}=ji({following:sn.isFollowing(),currentScrollTop:i,lastScrollTop:mn,nearBottom:Wo(ae,Is),userScrollThreshold:My,isAutoScrolling:gn||Es||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(mn=L,v==="resume"){Hs()||co();return}v==="pause"&&fa()};if(ae.addEventListener("scroll",xf,{passive:!0}),Ve.push(()=>ae.removeEventListener("scroll",xf)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Iy(),od(Le)});i.observe(Le),i.observe(ae),Ve.push(()=>i.disconnect())}let vf=()=>{no()&&sn.isFollowing()&&Hs()&&fa()},Cf=ae.ownerDocument;Cf.addEventListener("selectionchange",vf),Ve.push(()=>{Cf.removeEventListener("selectionchange",vf)});let ab=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),wf=i=>{ab.has(i.key)&&($o(),ku()&&no()&&sn.isFollowing()&&fa())},Af=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&($o(),ku()&&no()&&sn.isFollowing()&&fa())};ae.addEventListener("keydown",wf),ae.addEventListener("focusin",Af),Ve.push(()=>{ae.removeEventListener("keydown",wf),ae.removeEventListener("focusin",Af)});let Sf=i=>{if(i.deltaY!==0&&$o(),!no())return;let m=Gi({following:sn.isFollowing(),deltaY:i.deltaY,nearBottom:Wo(ae,Is),resumeWhenNearBottom:!0});m==="pause"?fa():m==="resume"&&!Hs()&&co()};ae.addEventListener("wheel",Sf,{passive:!0}),ae.addEventListener("touchmove",$o,{passive:!0}),ae.addEventListener("pointerdown",$o,{passive:!0}),Ve.push(()=>{ae.removeEventListener("touchmove",$o),ae.removeEventListener("pointerdown",$o)}),Ve.push(()=>ae.removeEventListener("wheel",Sf)),kt.addEventListener("click",()=>{ma(),ae.scrollTop=ae.scrollHeight,mn=ae.scrollTop,co(),po(!0),ln()}),Ve.push(()=>kt.remove()),Ve.push(()=>{Xu(),ma()});let Mf=()=>{R&&(Uo&&(R.removeEventListener("click",Uo),Uo=null),q()?(R.style.display="",Uo=()=>{ct(!1,"user")},R.addEventListener("click",Uo)):R.style.display="none")};Mf(),(()=>{let{clearChatButton:i}=Pe;i&&i.addEventListener("click",()=>{z.clearMessages(),qo.clear(),co(),Co(Pe.composerOverlay);try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),d?.clear&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()})})(),P&&P.addEventListener("submit",ff);let Tf=[["keydown",Yy],["input",Qy],["paste",Zy],["focus",vy]],Ef=i=>{if(i)for(let[m,y]of Tf)i.addEventListener(m,y)},kf=i=>{if(i)for(let[m,y]of Tf)i.removeEventListener(m,y)};Ef(pe),an?.onComposerSwap((i,m)=>{kf(m),pe=i,Ef(i)});let Lf=e.ownerDocument??document;Lf.addEventListener("keydown",mf,!0);let Pf="persona-attachment-drop-active",Aa=0,Yl=()=>{Aa=0,ue.classList.remove(Pf)},Mr=()=>o.attachments?.enabled===!0&&At!==null,Rf=i=>{!xl(i.dataTransfer)||!Mr()||(Aa++,Aa===1&&ue.classList.add(Pf))},If=i=>{!xl(i.dataTransfer)||!Mr()||(Aa--,Aa<=0&&Yl())},Wf=i=>{!xl(i.dataTransfer)||!Mr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Hf=i=>{if(!xl(i.dataTransfer)||!Mr())return;i.preventDefault(),i.stopPropagation(),Yl();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&At.handleFiles(m)},fo=!0;ue.addEventListener("dragenter",Rf,fo),ue.addEventListener("dragleave",If,fo),e.addEventListener("dragover",Wf,fo),e.addEventListener("drop",Hf,fo);let _s=e.ownerDocument,Bf=i=>{Mr()&&i.preventDefault()},Df=i=>{Mr()&&i.preventDefault()};_s.addEventListener("dragover",Bf),_s.addEventListener("drop",Df),Ve.push(()=>{P&&P.removeEventListener("submit",ff),kf(pe),Lf.removeEventListener("keydown",mf,!0),an?.destroy()}),Ve.push(()=>{ue.removeEventListener("dragenter",Rf,fo),ue.removeEventListener("dragleave",If,fo),e.removeEventListener("dragover",Wf,fo),e.removeEventListener("drop",Hf,fo),_s.removeEventListener("dragover",Bf),_s.removeEventListener("drop",Df),Yl()}),Ve.push(()=>{z.cancel()}),Ot?Ve.push(()=>{Ot?.destroy()}):Xt&&Ve.push(()=>{Xt?.remove()});let Lt={update(i){let m=o.toolCall,y=o.messageActions,v=o.layout?.messages,L=o.colorScheme,I=o.loadingIndicator,J=o.iterationDisplay,V=o.features?.showReasoning,X=o.features?.showToolCalls,se=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=ul({...o,features:r},i),r=o.features,o=is(o),Ss(),rr(e,o),as(e,o),ss(e,o),Un(),o.colorScheme!==L&&$u();let xe=ls.getForInstance(o.plugins);a.length=0,a.push(...xe),C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,Z=o.features?.scrollToBottom??{};let ze=fn();me=o.features?.scrollBehavior??{},ze!==fn()&&(ma(),co()),Iu(),ln();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(We||(Se=new os(we),We=new ns(mt,Se),_e=_e??new rs,Se.open().then(()=>We?.restore()).catch(()=>{}),z.setSSEEventCallback((te,Ge)=>{o.onSSEEvent?.(te,Ge),_e?.processEvent(te,Ge),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!tt&&$){let te=o.features?.eventStream?.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te?.toggleButton?" "+te.toggleButton:"");tt=b("button",Ge),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let ht=oe("activity","18px","currentColor",1.5);ht&&tt.appendChild(ht);let ot=Pe.clearChatButtonWrapper,at=Pe.closeButtonWrapper,$t=ot||at;$t&&$t.parentNode===$?$.insertBefore(tt,$t):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}}else!le&&pt&&(ra(),tt&&(tt.remove(),tt=null),We?.clear(),Se?.destroy(),We=null,Se=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Ot&&!Xt){let{instance:te,element:Ge}=zp({config:o,plugins:a,onToggle:hf});Ot=te,te||(Xt=Ge),e.appendChild(Ge)}Ot&&Ot.update(o),K&&o.launcher?.title!==void 0&&(K.textContent=o.launcher.title),_&&o.launcher?.subtitle!==void 0&&(_.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==F&&$){let te=nt?$r(o,nt,{showClose:q(),onClose:()=>ct(!1,"user")}):eo({config:o,showClose:q(),onClose:()=>ct(!1,"user")});wt.replaceHeader(te),$=wt.header.element,B=wt.header.iconHolder,K=wt.header.headerTitle,_=wt.header.headerSubtitle,R=wt.header.closeButton,F=nt?.layout}else if(nt){if(B&&(B.style.display=nt.showIcon===!1?"none":""),K&&(K.style.display=nt.showTitle===!1?"none":""),_&&(_.style.display=nt.showSubtitle===!1?"none":""),R){let te=q()&&nt.showCloseButton!==!1;R.style.display=te?"":"none"}if(Pe.clearChatButtonWrapper){let te=nt.showClearChat;if(te!==void 0){Pe.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Ge}=Pe;Ge&&!Ge.classList.contains("persona-absolute")&&(te?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let St=o.layout?.showHeader!==!1;$&&($.style.display=St?"":"none");let Pt=o.layout?.showFooter!==!1;Y&&(Y.style.display=Pt?"":"none"),gr(),ln(),C!==D?C?ct(T,"auto"):(Q=!0,xa()):T!==w&&ct(T,"auto"),w=T,D=C,wa(),Mf();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(m),Ce=JSON.stringify(o.messageActions)!==JSON.stringify(y),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ut=o.loadingIndicator?.render!==I?.render||o.loadingIndicator?.renderIdle!==I?.renderIdle||o.loadingIndicator?.showBubble!==I?.showBubble,Ft=o.iterationDisplay!==J,ft=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(Oe||Ce||Ct||ut||Ft||ft)&&z&&(Wl++,ga(Le,z.getMessages(),ie));let Rt=o.features?.streamAnimation?.type;if(Rt!==re&&Rt&&Rt!=="none"){let te=zr(Rt,o.features?.streamAnimation?.plugins);te&&Qi(te,e)}let Ee=o.launcher??{},Ne=Ee.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Vt=Ne||qt===!1,vt=Ee.headerIconName,dt=Ee.headerIconSize??"48px";if(B){let te=ue.querySelector(".persona-border-b-persona-divider"),Ge=te?.querySelector(".persona-flex-col");if(Vt)B.style.display="none",te&&Ge&&!te.contains(Ge)&&te.insertBefore(Ge,te.firstChild);else{if(B.style.display="",B.style.height=dt,B.style.width=dt,te&&Ge&&(te.contains(B)?B.nextSibling!==Ge&&(B.remove(),te.insertBefore(B,Ge)):te.insertBefore(B,Ge)),vt){let ot=parseFloat(dt)||24,at=oe(vt,ot*.6,"currentColor",1);at?B.replaceChildren(at):B.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let ot=B.querySelector("img");if(ot)ot.src=Ee.iconUrl,ot.style.height=dt,ot.style.width=dt;else{let at=document.createElement("img");at.src=Ee.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=dt,at.style.width=dt,B.replaceChildren(at)}}else{let ot=B.querySelector("svg"),at=B.querySelector("img");(ot||at)&&B.replaceChildren(),B.textContent=Ee.agentIconText??"\u{1F4AC}"}let ht=B.querySelector("img");ht&&(ht.style.height=dt,ht.style.width=dt)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(K&&(K.style.display=gt===!1?"none":""),_&&(_.style.display=Ze===!1?"none":""),R){let te=q()&&o.layout?.header?.showCloseButton!==!1;R.style.display=te?"":"none";let Ge=Ee.closeButtonSize??"32px",ht=Ee.closeButtonPlacement??"inline";R.style.height=Ge,R.style.width=Ge;let{closeButtonWrapper:ot}=Pe,at=ht==="top-right",$t=ot?.classList.contains("persona-absolute");if(ot&&at!==$t)if(ot.remove(),at)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ot);else{let go=Ee.clearChat?.placement??"inline",Ta=Ee.clearChat?.enabled??!0;ot.className=Ta&&go==="inline"?"":"persona-ml-auto";let Ff=ue.querySelector(".persona-border-b-persona-divider");Ff&&Ff.appendChild(ot)}if(R.style.color=Ee.closeButtonColor||Yt.actionIconColor,Ee.closeButtonBackgroundColor?(R.style.backgroundColor=Ee.closeButtonBackgroundColor,R.classList.remove("hover:persona-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let go=Ee.closeButtonBorderWidth||"0px",Ta=Ee.closeButtonBorderColor||"transparent";R.style.border=`${go} solid ${Ta}`,R.classList.remove("persona-border-none")}else R.style.border="",R.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(R.style.borderRadius=Ee.closeButtonBorderRadius,R.classList.remove("persona-rounded-full")):(R.style.borderRadius="",R.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(R.style.paddingLeft=Ee.closeButtonPaddingX,R.style.paddingRight=Ee.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),Ee.closeButtonPaddingY?(R.style.paddingTop=Ee.closeButtonPaddingY,R.style.paddingBottom=Ee.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let cn=Ee.closeButtonIconName??"x",Mn=Ee.closeButtonIconText??"\xD7";R.innerHTML="";let Nt=oe(cn,"28px","currentColor",1);Nt?(Nt.style.display="block",R.appendChild(Nt)):R.textContent=Mn;let jt=Ee.closeButtonTooltipText??"Close chat",jn=Ee.closeButtonShowTooltip??!0;R.setAttribute("aria-label",jt),ot&&Ut({anchor:R,trigger:ot,text:()=>R?.getAttribute("aria-label")??jt,enabled:jn})}let{clearChatButton:Ie,clearChatButtonWrapper:yt}=Pe;if(Ie){let te=Ee.clearChat??{},Ge=te.enabled??!0,ht=o.layout?.header?.showClearChat,ot=ht!==void 0?ht:Ge,at=te.placement??"inline";if(yt){yt.style.display=ot?"":"none";let{closeButtonWrapper:$t}=Pe;!O()&&$t&&!$t.classList.contains("persona-absolute")&&(ot?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let cn=at==="top-right",Mn=yt.classList.contains("persona-absolute");if(!O()&&cn!==Mn&&ot){if(yt.remove(),cn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",ue.style.position="relative",ue.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let jt=ue.querySelector(".persona-border-b-persona-divider"),jn=Pe.closeButtonWrapper;jt&&jn&&jn.parentElement===jt?jt.insertBefore(yt,jn):jt&&jt.appendChild(yt)}let Nt=Pe.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(cn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!O()){let go=te.size??"32px";Ie.style.height=go,Ie.style.width=go}let $t=te.iconName??"refresh-cw",cn=te.iconColor??"";Ie.style.color=cn||Yt.actionIconColor,Ie.innerHTML="";let Mn=O()?"14px":"20px",Nt=oe($t,Mn,"currentColor",1);if(Nt&&(Nt.style.display="block",Ie.appendChild(Nt)),te.backgroundColor?(Ie.style.backgroundColor=te.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let go=te.borderWidth||"0px",Ta=te.borderColor||"transparent";Ie.style.border=`${go} solid ${Ta}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");te.borderRadius?(Ie.style.borderRadius=te.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),te.paddingX?(Ie.style.paddingLeft=te.paddingX,Ie.style.paddingRight=te.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),te.paddingY?(Ie.style.paddingTop=te.paddingY,Ie.style.paddingBottom=te.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let jt=te.tooltipText??"Clear chat",jn=te.showTooltip??!0;Ie.setAttribute("aria-label",jt),yt&&Ut({anchor:Ie,trigger:yt,text:()=>Ie?.getAttribute("aria-label")??jt,enabled:jn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],bn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick];S=cs({parsers:zt,handlers:bn,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null}),ie=Rh(o,S,De),z.updateConfig(o),ga(Le,z.getMessages(),ie),Il(),sf(),Ul(z.isStreaming());let Sa=o.voiceRecognition?.enabled===!0,Us=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Tt=o.voiceRecognition?.provider?.type==="runtype";if(Sa&&(Us||Tt))if(!G||!Ue){let te=eb(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,Ue=te.micButtonWrapper,Re.insertBefore(Ue,ee),G.addEventListener("click",Ns),G.disabled=z.isStreaming())}else{let te=o.voiceRecognition??{},Ge=o.sendButton??{},ht=te.iconName??"mic",ot=Ge.size??"40px",at=te.iconSize??ot,$t=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let cn=te.iconColor??Ge.textColor;G.innerHTML="";let Mn=oe(ht,$t,cn||"currentColor",1.5);Mn?G.appendChild(Mn):G.textContent="\u{1F3A4}";let Nt=te.backgroundColor??Ge.backgroundColor;Nt?G.style.backgroundColor=Nt:G.style.backgroundColor="",cn?G.style.color=cn:G.style.color="var(--persona-text, #111827)",te.borderWidth?(G.style.borderWidth=te.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),te.borderColor?G.style.borderColor=te.borderColor:G.style.borderColor="",te.paddingX?(G.style.paddingLeft=te.paddingX,G.style.paddingRight=te.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),te.paddingY?(G.style.paddingTop=te.paddingY,G.style.paddingBottom=te.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let jt=te.tooltipText??"Start voice recognition",jn=te.showTooltip??!1;G.setAttribute("aria-label",jt),Ue&&Ut({anchor:G,trigger:Ue,text:()=>G?.getAttribute("aria-label")??jt,enabled:jn}),Ue.style.display="",G.disabled=z.isStreaming()}else G&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():Wn&&uo());if(o.attachments?.enabled===!0){if(!qe||!he){let te=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Ht||(Ht=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ht.style.display="none",P.insertBefore(Ht,pe)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),P.insertBefore(Fe,pe)),qe=b("div","persona-send-button-wrapper"),he=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),he.type="button",he.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let ot=te.buttonIconName??"paperclip",at=ht,$t=parseFloat(at)||40,cn=Math.round($t*.6);he.style.width=at,he.style.height=at,he.style.minWidth=at,he.style.minHeight=at,he.style.fontSize="18px",he.style.lineHeight="1";let Mn=oe(ot,cn,"currentColor",1.5);Mn?he.appendChild(Mn):he.textContent="\u{1F4CE}",he.addEventListener("click",jt=>{jt.preventDefault(),Fe?.click()}),qe.appendChild(he);let Nt=te.buttonTooltipText??"Attach file";Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Nt}),Qe?Qe.append(qe):P.appendChild(qe),!At&&Fe&&Ht&&(At=or.fromConfig(te),At.setPreviewsContainer(Ht),Fe.addEventListener("change",async()=>{At&&Fe?.files&&(await At.handleFileSelect(Fe.files),Fe.value="")}))}else{qe.style.display="";let te=o.attachments??{};Fe&&(Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Ih(o.attachments?.dropOverlay)),he){let te=o.attachments??{},Ge=te.buttonTooltipText??"Attach file";he.setAttribute("aria-label",Ge),he.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,ot=oe(te.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);ot?he.appendChild(ot):he.textContent="\u{1F4CE}",qe&&Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Ge})}}else qe&&(qe.style.display="none"),At&&At.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},Ma=Bt.useIcon??!1,Vs=Bt.iconText??"\u2191",Tr=Bt.iconName,zs=Bt.tooltipText??"Send message",Zl=Bt.showTooltip??!1,Xo=Bt.size??"40px",$n=Bt.backgroundColor,Jo=Bt.textColor;if(Ma){if(ve.style.width=Xo,ve.style.height=Xo,ve.style.minWidth=Xo,ve.style.minHeight=Xo,ve.style.fontSize="18px",ve.style.lineHeight="1",Jo?ve.style.color=Jo:ve.style.color="var(--persona-button-primary-fg, #ffffff)",!z.isStreaming())if(ve.innerHTML="",Tr){let te=parseFloat(Xo)||24,Ge=Jo?.trim()||"currentColor",ht=oe(Tr,te,Ge,2);ht?ve.appendChild(ht):ve.textContent=Vs}else ve.textContent=Vs;ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-primary")):(ve.style.backgroundColor="",ve.classList.add("persona-bg-persona-primary"))}else ve.textContent=o.copy?.sendButtonLabel??"Send",ve.style.width="",ve.style.height="",ve.style.minWidth="",ve.style.minHeight="",ve.style.fontSize="",ve.style.lineHeight="",ve.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-accent")):ve.classList.add("persona-bg-persona-accent"),Jo?ve.style.color=Jo:ve.classList.add("persona-text-white");Bt.borderWidth?(ve.style.borderWidth=Bt.borderWidth,ve.style.borderStyle="solid"):(ve.style.borderWidth="",ve.style.borderStyle=""),Bt.borderColor?ve.style.borderColor=Bt.borderColor:ve.style.borderColor="",Bt.paddingX?(ve.style.paddingLeft=Bt.paddingX,ve.style.paddingRight=Bt.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),Bt.paddingY?(ve.style.paddingTop=Bt.paddingY,ve.style.paddingBottom=Bt.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom=""),z.isStreaming()||ve.setAttribute("aria-label",zs),ee&&Ut({anchor:ve,trigger:ee,text:()=>ve.getAttribute("aria-label")??zs,enabled:Zl});let $s=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);$s?(Le.style.maxWidth=$s,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",P&&(P.style.maxWidth=$s,P.style.marginLeft="auto",P.style.marginRight="auto"),it&&(it.style.maxWidth=$s,it.style.marginLeft="auto",it.style.marginRight="auto")):(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",P&&(P.style.maxWidth="",P.style.marginLeft="",P.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let mo=o.statusIndicator??{},sb=mo.visible??!0;if(U.style.display=sb?"":"none",z){let te=z.getStatus();Kt(U,(ht=>ht==="idle"?mo.idleText??It.idle:ht==="connecting"?mo.connectingText??It.connecting:ht==="connected"?mo.connectedText??It.connected:ht==="error"?mo.errorText??It.error:It[ht])(te),mo,te)}U.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ib=mo.align==="left"?"persona-text-left":mo.align==="center"?"persona-text-center":"persona-text-right";U.classList.add(ib)},open(){q()&&ct(!0,"api")},close(){q()&&ct(!1,"api")},toggle(){q()&&ct(!Q,"api")},reconnect(){z.reconnectNow()},clearChat(){_n=!1,z.clearMessages(),qo.clear(),co();try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()},setMessage(i){return!pe||z.isStreaming()?!1:(!Q&&q()&&ct(!0,"system"),pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let m=i?.trim()||pe.value.trim();return m?(!Q&&q()&&ct(!0,"system"),pe.value="",pe.style.height="auto",z.sendMessage(m),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("user"),z.isVoiceActive()&&Sr()})),!0):Wn?!0:gf()?(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),Fs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()}),!0):!1:Wn?(Ke.manuallyDeactivated=!0,Sn(),uo("user"),!0):!1},injectMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!Q&&q()&&ct(!0,"system");let m=z.injectAssistantMessage(i);return de&&(de=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),m},injectUserMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!Q&&q()&&ct(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!Q&&q()&&ct(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!Q&&q()&&ct(!0,"system"),z.injectTestEvent(i)},async connectStream(i,m){return z.connectStream(i,m)},__pushEventStreamEvent(i){We&&(_e?.processEvent(i.type,i.payload),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!le||!We||Tl()},hideEventStream(){$e&&ra()},isEventStreamVisible(){return $e},showArtifacts(){Zt(o)&&(_n=!1,hr=!0,Un(),Ye?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(_n=!0,Un())},upsertArtifact(i){return Zt(o)?(Bn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(_n=!1,hr=!0),z.upsertArtifact(i)):null},selectArtifact(i){Zt(o)&&z.selectArtifact(i)},clearArtifacts(){Zt(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return C&&!Q&&!O()||!pe?!1:(pe.focus(),!0)},async resolveApproval(i,m,y){let L=z.getMessages().find(I=>I.variant==="approval"&&I.approval?.id===i);if(!L?.approval)throw new Error(`Approval not found: ${i}`);if(L.approval.toolType==="webmcp"){z.resolveWebMcpApproval(L.id,m);return}return z.resolveApproval(L.approval,m,y)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){E(i)},on(i,m){return p.on(i,m)},off(i,m){p.off(i,m)},isOpen(){return q()&&Q},isVoiceActive(){return Ke.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:q()&&Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()}},showCSATFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=yl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=bl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return z.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return z.submitNPSFeedback(i,m)},destroy(){$l(),Go!=null&&(clearInterval(Go),Go=null),Ve.forEach(i=>i()),He.remove(),et?.remove(),Ot?.destroy(),Xt?.remove(),Uo&&R.removeEventListener("click",Uo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:y=>y?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ve.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ve.push(()=>{window.removeEventListener("persona:focusInput",m)}),le){let V=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.showEventStream()},X=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),Ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let y=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},v=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},L=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},I=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",J),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",J)})}let yn=uw(o.persistState);if(yn&&q()){let i=fw(yn.storage),m=`${yn.keyPrefix}widget-open`,y=`${yn.keyPrefix}widget-voice`,v=`${yn.keyPrefix}widget-voice-mode`;if(i){let L=yn.persist?.openState&&i.getItem(m)==="true",I=yn.persist?.voiceState&&i.getItem(y)==="true",J=yn.persist?.voiceState&&i.getItem(v)==="true";if(L&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(I||J)Lt.startVoiceRecognition();else if(yn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),yn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(m,"true")}),p.on("widget:closed",()=>{i.setItem(m,"false")})),yn.persist?.voiceState&&(p.on("voice:state",V=>{i.setItem(y,V.active?"true":"false")}),p.on("user:message",V=>{i.setItem(v,V.viaVoice?"true":"false")})),yn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(y),i.removeItem(v)},X=()=>V();window.addEventListener("persona:clear-chat",X),Ve.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(f&&q()&&setTimeout(()=>{Lt.open()},0),Cr(),!Sy){let i=kr(()=>{z&&(Wl++,qo.clear(),ga(Le,z.getMessages(),ie))});Ve.push(i)}return Lt};var Wh=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let a=o.offsetHeight>0;o.remove(),!(!r||a)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Hh=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},gu=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Bh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",gu(e)},uu=e=>{e.style.transition=""},fu=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},mu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},xw=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},vw=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},Cw=e=>{let t=ko(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Qt(t,r)??r;return{inset:o(n?.inset,Ii),canvasBackground:o(n?.canvasBackground,Wi)}},Dh=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},ww=(e,t,n,o,r,a,s,l)=>{let p=rn(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";xw(e,t,n,o,c),vw(e,t,n,o,p.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,h=a?.launcher?.mobileFullscreen??!0,A=a?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=A:!1;if(h&&E&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fu(t),uu(o),Bh(o),mu(n),Cl(r,o),Dh(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(a?.launcher?.zIndex??Gt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Bh(o),hw(o,p.maxHeight),Dh(o,d&&s,u,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fu(t),uu(o),mu(n),Cl(r,o);let M=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=C,o.style.pointerEvents=s?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",uu(o),gu(o),Cl(r,o);let M=Wh(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",T=p.side==="right"?s?-M:0:s?0:-M;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+M}px`,t.style.transition=C,t.style.marginLeft=`${T}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",fu(t),gu(o),mu(n),Cl(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?p.width:"0px",C=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",T=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",yw(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=C,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let W=d?`calc(${Wh(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Hh(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Hh(n,o)},destroy(){n.remove()}}},Sw=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let a=e.nextSibling,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,A=()=>{h=t?.launcher?.detachedPanel===!0?Cw(t):null};A();let E=()=>{ww(s,l,p,c,d,t,u,h)},k=null,M=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Nr(()=>{A(),E()}))},S=()=>{f(),rn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{E()}),g.observe(s)))},C=!1,T=()=>{E(),S(),u&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,bw(s,rn(t)))},W=s.ownerDocument.defaultView,w=()=>{T()};return W?.addEventListener("resize",w),rn(t).reveal==="push"?(l.appendChild(p),l.appendChild(c),s.appendChild(l)):(s.appendChild(p),s.appendChild(c)),T(),M(),{mode:"docked",host:d,shell:s,syncWidgetState(D){let F=D.launcherEnabled?D.open:!0;u!==F&&(u=F,T())},updateConfig(D){t=D,(t?.launcher?.enabled??!0)===!1&&(u=!0),A(),T(),M()},destroy(){W?.removeEventListener("resize",w),k?.(),k=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},us=(e,t)=>Et(t)?Sw(e,t):Aw(e,t);var Mw=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Fh=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Oh=e=>{let t=Mw(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=us(t,r),s,l=[],p=(E,k)=>{let S=!(k?.launcher?.enabled??!0)||Et(k),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),S&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0",C.style.minWidth="0"),n){let T=E.attachShadow({mode:"open"});T.appendChild(C),Fh(T,o)}else E.appendChild(C),Fh(E,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},c=()=>{a.syncWidgetState(s.getState())},d=()=>{l.forEach(E=>E()),l=[s.on("widget:opened",c),s.on("widget:closed",c)],c()},u=()=>{let E=p(a.host,r);s=vl(E,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(E=>E()),l=[],s.destroy()};u(),e.onChatReady?.();let f=E=>{g(),a.destroy(),a=us(t,E),r=E,u()},h={update(E){let k=ul(r??{},E),M=Et(r),S=Et(k),C=Bo(r),T=Bo(k);if(M!==S||C!==T){f(k);return}r=k,a.updateConfig(r),s.update(E),c()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},A=new Proxy(h,{get(E,k,M){if(k==="host")return a.host;if(k in E)return Reflect.get(E,k,M);let S=s[k];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=A),A};function Tw(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function Ew(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(a=>a.toLowerCase().startsWith(o))?1:Tw(o,n)?2:3}function Nh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function wl(e,t){let n=t.trim();if(!n)return[...e].sort(Nh);let o=[];for(let r of e){let a=Ew(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:Nh(r.item,a.item)),o.map(r=>r.item)}function kw(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function _h(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>wl(e.items,t),resolve:e.resolve}}function Uh(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>wl(t,kw(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var jh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Lw=new Set(["button","a","input","select","textarea","details","summary"]),Pw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),hu=/\b(product|card|item|listing|result)\b/i,bu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Rw=3e3,Iw=100;function Gh(e){let t=typeof e.className=="string"?e.className:"";if(hu.test(t)||e.id&&hu.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&hu.test(o.value))return!0}return!1}function Kh(e){return bu.test((e.textContent??"").trim())}function Xh(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ww(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qh(e){let t=e.match(bu);return t?t[0]:null}function Vh(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Hw(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Bw="commerce-card",Dw="result-card";function zh(e){return!Gh(e)||!Kh(e)||!Xh(e)&&!Ww(e)?0:5200}function $h(e){return!Gh(e)||Kh(e)||!Xh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xu=[{id:Bw,scoreElement(e){return zh(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||bu.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(zh(e)===0)return null;let{title:n,href:o}=Vh(e),r=qh((e.textContent??"").trim())??qh(t.text)??"",a=Hw(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
|
|
144
|
-
`)}},{id:
|
|
145
|
-
`)}}];function
|
|
142
|
+
${xt?"background: transparent !important;":""}
|
|
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:uA,scoreElement(e){return uy(e)},formatSummary(e,t){if(uy(e)===0)return null;let{title:n,href:o}=cy(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
145
|
+
`)}}];function fA(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function mA(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),c=e.rules??ku;return l==="simple"&&e.rules&&e.rules.length>0?(fA(),c=[]):l==="simple"&&(c=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:c}}function Tu(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var gA=["data-testid","data-product","data-action","data-id","data-name","data-type"];function hA(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"||aA.has(t)||n&&sA.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function yy(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 yA(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);let p=e.getAttribute("role");p&&(t.role=p);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function Lu(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${Tu(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of gA){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${Tu(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=>Tu(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 bA(e){return e==="static"?lA:iA}function by(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Lu(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:hA(e),attributes:yA(e)}}function xA(e,t,n,o){let r=bA(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 vA(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 CA(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let c=l,d=c.tagName.toLowerCase();if(fy.has(d)){l=s.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!yy(c)){l=s.nextNode();continue}let u=by(c,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(k=>k==="role");if(!g&&!f){l=s.nextNode();continue}if(o.has(u.selector)){l=s.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:S}=xA(c,u,e.rules,n);r.push({el:c,domIndex:a,enriched:u,score:h,formattingRule:S}),a+=1}l=s.nextNode()}r.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let p=[];for(let c of r){if(p.length>=e.maxElements)break;vA(p,c)||p.push(c)}return p.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),p.map(c=>{let d;if(c.formattingRule?.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(d=g)}let u={...c.enriched};return d&&(u.formattedSummary=d),u})}function wA(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,c=p.tagName.toLowerCase();if(fy.has(c)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!yy(p)){a=r.nextNode();continue}let d=by(p,e.maxTextLength),u=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!u&&!g){a=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}a=r.nextNode()}let s=[],l=[];for(let p of n)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function xy(e={}){let t=mA(e),n=t.root??document.body;return n?t.mode==="simple"?wA(t,n):CA(t,n):[]}var Il=100;function vy(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,Il)}" (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,Il)}" (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,Il)}" (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,Il)}"`);o.push(`Content:
|
|
156
156
|
${a.join(`
|
|
157
157
|
`)}`)}return o.join(`
|
|
158
158
|
|
|
159
|
-
`)}function
|
|
159
|
+
`)}function Cy(){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 wy(){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 Ay(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:qn(e.colors.primary,.95),100:qn(e.colors.primary,.9),200:qn(e.colors.primary,.8),300:qn(e.colors.primary,.7),400:qn(e.colors.primary,.6),500:e.colors.primary,600:qn(e.colors.primary,.8),700:qn(e.colors.primary,.7),800:qn(e.colors.primary,.6),900:qn(e.colors.primary,.5),950:qn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Sy(){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 My(){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 qn(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 Ty(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var AA={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"}}},Ey={components:{panel:{borderRadius:"0",shadow:"none"}}},Pu={id:"shop",label:"Shopping Assistant",config:{theme:AA,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:fn},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"]}},Ru={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ey}},Iu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ey}},Wu={shop:Pu,minimal:Ru,fullscreen:Iu};function ky(e){return Wu[e]}var SA=`
|
|
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(),MA={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:SA};pr(MA);var TA=`
|
|
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(),vs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",EA=10,kA=120,Hu=120,LA=.4,PA=50,RA=e=>{if(!e)return Hu;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Hu},Dy=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=RA(t);return kA*n/Hu},Bu=e=>{let t=vs[Math.floor(Math.random()*vs.length)];return e&&t===e&&(t=vs[(vs.indexOf(t)+1)%vs.length]),t},IA=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()<LA&&(r.textContent=Bu())}},Ly=new WeakMap,Py=25,Ry=.5,WA=6,Iy=.25,Wy=new WeakMap,Hy=new WeakMap,HA=(e,t)=>{if(!e)return Py*Ry;let n=Wy.get(e);Wy.set(e,t);let o=Hy.get(e)??Py;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Iy)+r*Iy,Hy.set(e,o))}return Math.max(WA,o*Ry)},sa=new Map,BA=e=>e.closest("[data-message-id]")?.dataset.messageId??null,DA=e=>{e&&sa.set(e,(sa.get(e)??0)+1)},FA=e=>{if(!e)return;let t=sa.get(e)??0;t<=1?sa.delete(e):sa.set(e,t-1)},Fy=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=Bu();let n=BA(e);n&&(e.dataset.glyphCycleMessageId=n),DA(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=HA(o,r),s=Dy(e),l=EA*s,p=r+l;if(o){let c=Ly.get(o);c!==void 0&&(p=Math.max(p,c)),Ly.set(o,p+a)}OA(e,t,p)},OA=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=Dy(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,FA(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Bu(r);e.textContent=s,r=s,IA(e),setTimeout(a,o)};setTimeout(a,o)},By=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))Fy(n)},NA=e=>e.nodeType===1,_A={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:TA,bufferContent(e){if(e.length<PA)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(sa.get(e.id)??0)>0},onAttach(e){By(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))NA(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?Fy(r):By(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};pr(_A);var nn=typeof document<"u"?document.currentScript?.src??null:null;Sm(()=>{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)});lm(()=>{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)});Da().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});lg(()=>{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)});xg(()=>{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)});vg(()=>{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 Nb(UA);})();
|
|
214
214
|
/*! Bundled license information:
|
|
215
215
|
|
|
216
216
|
lucide/dist/esm/icons/activity.mjs:
|
|
@@ -228,6 +228,7 @@ lucide/dist/esm/icons/building.mjs:
|
|
|
228
228
|
lucide/dist/esm/icons/calendar-days.mjs:
|
|
229
229
|
lucide/dist/esm/icons/calendar.mjs:
|
|
230
230
|
lucide/dist/esm/icons/camera.mjs:
|
|
231
|
+
lucide/dist/esm/icons/chart-column.mjs:
|
|
231
232
|
lucide/dist/esm/icons/check.mjs:
|
|
232
233
|
lucide/dist/esm/icons/chevron-down.mjs:
|
|
233
234
|
lucide/dist/esm/icons/chevron-left.mjs:
|
|
@@ -269,6 +270,7 @@ lucide/dist/esm/icons/image-plus.mjs:
|
|
|
269
270
|
lucide/dist/esm/icons/image.mjs:
|
|
270
271
|
lucide/dist/esm/icons/info.mjs:
|
|
271
272
|
lucide/dist/esm/icons/key.mjs:
|
|
273
|
+
lucide/dist/esm/icons/lightbulb.mjs:
|
|
272
274
|
lucide/dist/esm/icons/link.mjs:
|
|
273
275
|
lucide/dist/esm/icons/loader-circle.mjs:
|
|
274
276
|
lucide/dist/esm/icons/loader.mjs:
|
|
@@ -287,6 +289,7 @@ lucide/dist/esm/icons/moon.mjs:
|
|
|
287
289
|
lucide/dist/esm/icons/package.mjs:
|
|
288
290
|
lucide/dist/esm/icons/paperclip.mjs:
|
|
289
291
|
lucide/dist/esm/icons/pause.mjs:
|
|
292
|
+
lucide/dist/esm/icons/pen-line.mjs:
|
|
290
293
|
lucide/dist/esm/icons/pencil.mjs:
|
|
291
294
|
lucide/dist/esm/icons/percent.mjs:
|
|
292
295
|
lucide/dist/esm/icons/phone.mjs:
|