@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
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!
|
|
3
|
-
`):e};var
|
|
1
|
+
import{a as Ed}from"./chunk-5EIIHQLQ.js";import{a as y,b as Md,c as Ie,d as On,e as ae,f as Pd,h as Id,i as Rd}from"./chunk-QJ4LV2KW.js";import{a as kd,b as Ld}from"./chunk-IO5VVUKP.js";var nr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:dv,load:Cg,provide:pv,getSync:qi}=nr({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),fa=new Set,Ag=()=>{let e=[...fa];fa.clear();for(let t of e)try{t()}catch{}};var Sg=()=>{let e=qi();return e?Promise.resolve(e):Cg().then(t=>(Ag(),t))},ga=e=>qi()?()=>{}:(fa.add(e),Sg().catch(()=>{}),()=>{fa.delete(e)});var _n=qi;var Tg=e=>{if(e)return e},Ki=e=>{let t=null;return n=>{let o=_n();if(!o)return ao(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Tg(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},ma=e=>e?Ki({markedOptions:e.options,renderer:e.renderer}):Ki(),gv=Ki();var ao=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Mg={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"]},Eg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,kg=()=>{let e=null;return t=>{let n=_n();if(!n)return ao(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Eg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Mg)}},ha=e=>e===!1?null:typeof e=="function"?e:kg();var Wd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Hd=e=>e.includes("|"),Bd=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())},Lg=e=>`| ${e.join(" | ")} |`,Pg=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Ig=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Dd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Hd(r)||Wd.test(r)||!Wd.test(s))continue;let a=Bd(r).length;if(a<1)continue;let l=Pg(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Hd(d))break;let c=Lg(Ig(Bd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
|
|
3
|
+
`):e};var Fd="var(--persona-md-table-scroll-fade, 24px)",Nd=new WeakSet;function _d(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 Od(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":Fd),e.style.setProperty("--persona-fade-r",r<=1?"0px":Fd)}function Gi(e){Nd.has(e)||(Nd.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Od(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Od)}var $n="webmcp:",Qi=new Map,$d=e=>{Qi.clear();for(let t of e){let n=t.title?.trim();n&&Qi.set(t.name,n)}},ts=e=>Qi.get(Vd(e)),ya={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ud=null;function jd(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}:${Rg(t.join(""))}`}function zd(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,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 Rg(e){let t=zd(e,0).toString(36),n=zd(e,2654435761).toString(36);return`${t}.${n}`}var ba=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 ya.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}$d(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Hg(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return An("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return An(v?"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 s=Vd(t),a;try{a=await r.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return An(`Failed to read WebMCP registry: ${x}`)}$d(a);let l=a.find(v=>v.name===s);if(!l)return An(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return An(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return An("Aborted by cancel()");let p=ts(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return An("User declined the tool call.");if(o?.aborted)return An("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let v=await r.executeTool(l,Ng(n),{signal:c.signal});return Bg(v)}catch(v){if(u)return An(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return An("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return An(x)}finally{clearTimeout(w),o&&o.removeEventListener("abort",g)}}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){ya.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,ya.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??Dg;try{return await n(t)}catch(o){return ya.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=>Wg(t,o))}},Vd=e=>e.startsWith($n)?e.slice($n.length):e,or=e=>e.startsWith($n),Wg=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Hg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Bg=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:Og(t)}]}},An=e=>({isError:!0,content:[{type:"text",text:e}]}),Dg=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Fg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
6
|
${t}`:"")+(e.description?`
|
|
7
7
|
|
|
8
|
-
${e.description}`:"");return window.confirm(n)},mg=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)}},hg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},yg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function un(e){return e==="card"?"collapsed":e}function er(e){return e.split(";",1)[0].trim().toLowerCase()}function bg(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(er(r)===t)return{mode:un(s),selector:er(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(er(r)===o)return{mode:un(s),selector:o}}function vg(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:un(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?er(t.file.mimeType):void 0,p=l?bg(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:un(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:un(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:un(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:un(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:un(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ro(e,t){return vg(e,t).mode}function Qr(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 wg="agent_",xg="flow_";function kd(e){return e.startsWith(wg)?{kind:"agentId",agentId:e}:e.startsWith(xg)?{kind:"flowId",flowId:e}:null}function Ld(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=kd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=kd(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(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.`)}import{parse as Cg,ARR as Ag,OBJ as Sg,STR as Tg}from"partial-json";var Ui="ask_user_question",Xr=8,tr="data-persona-ask-sheet-for",Mg="Other",Eg="Other\u2026",Id="Type your own answer here",Rd="Send",kg="Next",Lg="Back",Pg="Submit all",Ig="Skip",Rg=3,Vi="data-ask-current-index",qi="data-ask-question-count",Wd="data-ask-answers",Ki="data-ask-grouped",Hd="data-ask-layout",Wg=e=>e.layout==="pills"?"pills":"rows",Hg=e=>e.getAttribute(Hd)==="pills"?"pills":"rows",Pd=!1,Bd=e=>e.replace(/["\\]/g,"\\$&"),Lo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ui,Gi=e=>e?.features?.askUserQuestion??{},nr=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(""),s=Cg(r,Tg|Sg|Ag);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Jr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Xr&&!Pd&&(Pd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Xr}.`)),t.slice(0,Xr)},Bg=e=>Jr(e)[0]??null,Dg=(e,t)=>Jr(e)[t]??null,Fg=(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))},Dd=(e,t,n)=>{if(e!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ng=(e,t,n,o)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=h("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Dd(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Og=e=>{let n=h("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},_g=(e,t,n,o)=>{let s=h("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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Rg;c++)s.appendChild(Og(o));return s}if(p.forEach((c,u)=>{s.appendChild(Ng(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Mg:Eg;if(o==="rows"){let u=h("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 w=h("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??Id,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=Dd(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},Fd=(e,t)=>{let o=h("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??Id,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Rd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},$g=e=>{let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},zg=(e,t,n)=>{let o=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Lg,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ig,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Pg:n.nextLabel??kg,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=e=>{let t=e.getAttribute(Wd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nd=(e,t)=>{e.setAttribute(Wd,JSON.stringify(t))},fn=e=>{let t=Number(e.getAttribute(Vi)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},jg=(e,t)=>{e.setAttribute(Vi,String(Math.max(0,Math.floor(t))))},or=e=>{let t=Number(e.getAttribute(qi)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(Ki)==="true",Ug=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Vg=(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)))},fa=(e,t)=>{let{payload:n}=nr(t),o=Jr(n),r=Po(e),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Od=e=>{let t=Po(e),n=fn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},_d=e=>{if(!so(e))return;let t=Po(e),n=fn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Qi=(e,t,n)=>{let o=Gi(n),r=Hg(e),{payload:s,complete:a}=nr(t),l=so(e),p=fn(e),d=or(e),c=l?Dg(s,p):Bg(s),u=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof c?.question=="string"?c.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let L=_g(c,o,a,r);C.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Fd(o,r))}let R=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!R?e.appendChild($g(o)):(!u||l)&&R&&R.remove(),e.setAttribute("data-multi-select",u?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=zg(p,d,o);B?B.replaceWith(L):e.appendChild(L)}else B&&B.remove();Od(e),_d(e)},qg=(e,t,n)=>{let o=Gi(t),r=Wg(o),s=e.toolCall.id,a=Jr(n),l=Math.max(1,a.length),p=l>1,d=Ug(e,a),c=p?Vg(e,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(tr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(qi,String(l)),u.setAttribute(Vi,String(c)),u.setAttribute(Ki,p?"true":"false"),u.setAttribute(Hd,r),Nd(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Fg(u,o);let w=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let R=h("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 R.setAttribute("data-ask-pill-list","true"),R.setAttribute("role","group"),u.appendChild(R),r!=="rows"&&u.appendChild(Fd(o,r)),Qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Kg=(e,t,n)=>{let{payload:o}=nr(t),r=Math.max(1,Jr(o).length);r>or(e)&&(e.setAttribute(qi,String(r)),r>1&&!so(e)&&e.setAttribute(Ki,"true")),Qi(e,t,n)};var ga=(e,t,n)=>{if(!n||!Lo(e)||Gi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${tr}]`).forEach(d=>{d.getAttribute(tr)!==r&&d.remove()});let a=n.querySelector(`[${tr}="${Bd(r)}"]`);if(a){Kg(a,e,t);return}let{payload:l}=nr(e),p=qg(e,t,l);n.appendChild(p)},rr=(e,t)=>{if(!e)return;let n=t?`[${tr}="${Bd(t)}"]`:`[${tr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Xi=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),ao=(e,t)=>{let n=Po(e),o=fn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Nd(e,n),Od(e),_d(e)},ma=(e,t,n,o)=>{let r=or(e),s=Math.max(0,Math.min(r-1,o));jg(e,s),Qi(e,t,n)};var On="suggest_replies";var Gg={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},$d={name:On,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. 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:Gg,origin:"sdk",annotations:{readOnlyHint:!0}},Ji=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Yi=e=>e.variant==="tool"&&e.toolCall?.name===On,Qg=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},zd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Yi(n))continue;let o=Qg(n.toolCall?.args);return o.length>0?o:null}return null},jd=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Xg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Xr,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},Jg={name:Ui,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:Xg,origin:"sdk",annotations:{readOnlyHint:!0}},ha=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Jg),jd(e)&&t.push($d),t};import{parse as Yg,STR as Zg,OBJ as em}from"partial-json";var Ud=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},Fg=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)}},Ng=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Og=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function gn(e){return e==="card"?"collapsed":e}function rr(e){return e.split(";",1)[0].trim().toLowerCase()}function _g(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(rr(r)===t)return{mode:gn(s),selector:rr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(rr(r)===o)return{mode:gn(s),selector:o}}function $g(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:gn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?rr(t.file.mimeType):void 0,p=l?_g(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:gn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:gn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:gn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:gn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:gn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function io(e,t){return $g(e,t).mode}function ns(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...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 Ug="agent_",zg="flow_";function qd(e){return e.startsWith(Ug)?{kind:"agentId",agentId:e}:e.startsWith(zg)?{kind:"flowId",flowId:e}:null}function Kd(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=qd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=qd(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(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.`)}import{parse as jg,ARR as Vg,OBJ as qg,STR as Kg}from"partial-json";var Xi="ask_user_question",os=8,sr="data-persona-ask-sheet-for",Gg="Other",Qg="Other\u2026",Qd="Type your own answer here",Xd="Send",Xg="Next",Jg="Back",Yg="Submit all",Zg="Skip",em=3,Ji="data-ask-current-index",Yi="data-ask-question-count",Jd="data-ask-answers",Zi="data-ask-grouped",Yd="data-ask-layout",tm=e=>e.layout==="pills"?"pills":"rows",nm=e=>e.getAttribute(Yd)==="pills"?"pills":"rows",Gd=!1,Zd=e=>e.replace(/["\\]/g,"\\$&"),Wo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xi,el=e=>e?.features?.askUserQuestion??{},ar=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(""),s=jg(r,Kg|qg|Vg);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},rs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>os&&!Gd&&(Gd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${os}.`)),t.slice(0,os)},om=e=>rs(e)[0]??null,rm=(e,t)=>rs(e)[t]??null,sm=(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))},ep=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},am=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=ep(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},im=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},lm=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<em;c++)s.appendChild(im(o));return s}if(p.forEach((c,u)=>{s.appendChild(am(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Gg:Qg;if(o==="rows"){let u=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=y("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Qd,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),u.appendChild(w);let v=ep(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},tp=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Qd,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Xd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},cm=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Xd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},dm=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Jg,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Zg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Yg:n.nextLabel??Xg,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ho=e=>{let t=e.getAttribute(Jd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},np=(e,t)=>{e.setAttribute(Jd,JSON.stringify(t))},mn=e=>{let t=Number(e.getAttribute(Ji)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pm=(e,t)=>{e.setAttribute(Ji,String(Math.max(0,Math.floor(t))))},ir=e=>{let t=Number(e.getAttribute(Yi)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},lo=e=>e.getAttribute(Zi)==="true",um=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},fm=(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)))},va=(e,t)=>{let{payload:n}=ar(t),o=rs(n),r=Ho(e),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},op=e=>{let t=Ho(e),n=mn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},rp=e=>{if(!lo(e))return;let t=Ho(e),n=mn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},tl=(e,t,n)=>{let o=el(n),r=nm(e),{payload:s,complete:a}=ar(t),l=lo(e),p=mn(e),d=ir(e),c=l?rm(s,p):om(s),u=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let k=typeof c?.question=="string"?c.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=lm(c,o,a,r);x.replaceWith(k)}if(r!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(tp(o,r))}let P=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?e.appendChild(cm(o)):(!u||l)&&P&&P.remove(),e.setAttribute("data-multi-select",u?"true":"false");let F=e.querySelector('[data-ask-nav-row="true"]');if(l){let k=dm(p,d,o);F?F.replaceWith(k):e.appendChild(k)}else F&&F.remove();op(e),rp(e)},gm=(e,t,n)=>{let o=el(t),r=tm(o),s=e.toolCall.id,a=rs(n),l=Math.max(1,a.length),p=l>1,d=um(e,a),c=p?fm(e,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(sr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Yi,String(l)),u.setAttribute(Ji,String(c)),u.setAttribute(Zi,p?"true":"false"),u.setAttribute(Yd,r),np(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sm(u,o);let w=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let P=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),u.appendChild(P),r!=="rows"&&u.appendChild(tp(o,r)),tl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},mm=(e,t,n)=>{let{payload:o}=ar(t),r=Math.max(1,rs(o).length);r>ir(e)&&(e.setAttribute(Yi,String(r)),r>1&&!lo(e)&&e.setAttribute(Zi,"true")),tl(e,t,n)};var wa=(e,t,n)=>{if(!n||!Wo(e)||el(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${sr}]`).forEach(d=>{d.getAttribute(sr)!==r&&d.remove()});let a=n.querySelector(`[${sr}="${Zd(r)}"]`);if(a){mm(a,e,t);return}let{payload:l}=ar(e),p=gm(e,t,l);n.appendChild(p)},lr=(e,t)=>{if(!e)return;let n=t?`[${sr}="${Zd(t)}"]`:`[${sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},nl=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),co=(e,t)=>{let n=Ho(e),o=mn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,np(e,n),op(e),rp(e)},xa=(e,t,n,o)=>{let r=ir(e),s=Math.max(0,Math.min(r-1,o));pm(e,s),tl(e,t,n)};var Un="suggest_replies";var hm={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},ap={name:Un,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:hm,origin:"sdk",annotations:{readOnlyHint:!0}},ol=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ss=e=>e.variant==="tool"&&e.toolCall?.name===Un,ym=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 s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});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},ip=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ss(n))continue;let o=ym(n.toolCall?.args);return o.length>0?o:null}return null},sp=new Set,bm=(e,t,n)=>{let o=`${e}:${t}:${n}`;sp.has(o)||(sp.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},po=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],p=n?.[a];l===void 0||p===void 0||l!==p&&bm(a,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var vm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:os,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},wm={name:Xi,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:vm,origin:"sdk",annotations:{readOnlyHint:!0}},Ca=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(wm),po(e).expose&&t.push(ap),t};import{parse as xm,STR as Cm,OBJ as Am}from"partial-json";var lp=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),uo=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)}},Sm=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`},cp=e=>e.status==="complete"?Sm(e):e.status==="pending"?"Waiting":"",Tm=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 dp=e=>e.status==="complete"?Tm(e):"Using tool...",Aa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},is=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 Aa(t)},Sa=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Aa(t)},rl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=is(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ta=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&as(o,n.slice(s,a.index),[]),a[1]!==void 0?as(o,a[1],["bold"]):a[2]!==void 0?as(o,a[2],["italic"]):a[3]!==void 0&&as(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&as(o,n.slice(s),[]),o},as=(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})},Mm=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
-
`).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 s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Kd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gd=()=>{let e=om();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)}},Qd=()=>{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=Yg(n,Zg|em);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ud(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ud(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Xd=()=>{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 Jd="4.14.0";var ts=Jd;var sm="https://api.runtype.com/v1/dispatch",wa="https://api.runtype.com";function am(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 s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var el=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 im(e){switch(e){case"json":return Qd;case"regex-json":return Gd;case"xml":return Xd;default:return Kd}}var Yd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lm(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=Yd(n);if(!Yd(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=es(e);return es(t)!==null&&a===null?t:e}var ns=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??sm,this.headers={"Content-Type":"application/json","X-Persona-Version":ts,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??im(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 ua(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 s=Ld(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/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}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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$/,"")||wa}/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}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(el).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.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 a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.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$/,"")||wa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Md(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||wa}/resume`,a;r&&(a=(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(a&&(p.sessionId=a),r&&a){let d=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let f={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{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 s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));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(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(el).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),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,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.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 s=t.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=S=>{let D=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,y=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,P=S.tools?S.tools.map(T=>({...T,chunks:T.chunks?[...T.chunks]:void 0})):void 0;return{...S,reasoning:D,toolCall:y,tools:P}},w=S=>{if(S.role!=="assistant"||S.variant)return!0;let D=Array.isArray(S.contentParts)&&S.contentParts.length>0,y=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||D||y||!!S.stopReason},f=S=>{w(S)&&n({type:"message",message:u(S)})},v=null,C=null,R={current:null},B={current:null},L=null,E="",M=new Map,_=new Map,G=new Map,x=new Map,j=new Map,U={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},F=S=>{if(S==null)return null;try{return String(S)}catch{return null}},$=S=>F(S.stepId??S.step_id??S.step??S.parentId??S.flowStepId??S.flow_step_id),X=S=>F(S.callId??S.call_id??S.requestId??S.request_id??S.toolCallId??S.tool_call_id??S.stepId??S.step_id),me=o,he=!1,Ae=()=>{if(v)return v;let S,D="",y=L;return!he&&me?(S=me,he=!0,D=r??""):me&&y?S=`${me}_${y}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:S,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},Z=(S,D)=>{U.lastId=D,S&&U.byStep.set(S,D)},ce=(S,D)=>{let y=S.reasoningId??S.id,P=$(S);if(y){let I=String(y);return Z(P,I),I}if(P){let I=U.byStep.get(P);if(I)return U.lastId=I,I}if(U.lastId&&!D)return U.lastId;if(!D)return null;let T=`reason-${c()}`;return Z(P,T),T},ee=S=>{let D=x.get(S);if(D)return D;let y={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return x.set(S,y),f(y),y},le=(S,D)=>{oe.lastId=D,S&&oe.byCall.set(S,D)},Y=new Set,pe=new Map,xe=new Set,ye=new Map,ve=S=>{if(!S)return!1;let D=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return D==="emit_artifact_markdown"||D==="emit_artifact_component"},je=(S,D)=>{let y=S.toolId??S.id,P=X(S);if(y){let I=String(y);return le(P,I),I}if(P){let I=oe.byCall.get(P);if(I)return oe.lastId=I,I}if(oe.lastId&&!D)return oe.lastId;if(!D)return null;let T=`tool-${c()}`;return le(P,T),T},Me=S=>{let D=j.get(S);if(D)return D;let y={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return j.set(S,y),f(y),y},De=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let D=Number(S);if(!Number.isNaN(D)&&Number.isFinite(D))return D;let y=Date.parse(S);if(!Number.isNaN(y))return y}return Date.now()},Qe=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},Ve=new Map,Te=new Map,Le=new Map,Xe=(S,D,y)=>{let P=Le.get(S);P||(P=[],Le.set(S,P));let T=0,I=P.length;for(;T<I;){let H=T+I>>>1;P[H].seq<D?T=H+1:I=H}P[T]?.seq===D?P[T]={seq:D,text:y}:P.splice(T,0,{seq:D,text:y});let q="";for(let H=0;H<P.length;H++)q+=P[H].text;return q},Ht=(S,D)=>{let y=Qe(D),P=Te.get(S.id),T=lm(P,y);S.rawContent=T;let I=Ve.get(S.id),q=Re=>{let Je=S.content??"";Re.trim()!==""&&(Je.trim().length===0||Re.startsWith(Je)||Re.trimStart().startsWith(Je.trim()))&&(S.content=Re)},H=()=>{if(I){let Re=I.close?.();Re instanceof Promise&&Re.catch(()=>{})}Ve.delete(S.id),Te.delete(S.id),S.streaming=!1,f(S)};if(!I){q(y),H();return}let z=es(T);if(z!==null&&z.trim()!==""){q(z),H();return}let J=Re=>{let Je=typeof Re=="string"?Re:Re?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let rt=I.getExtractedText();return rt!==null&&rt.trim()!==""?rt:y},qe;try{qe=I.processChunk(T)}catch{q(y),H();return}if(qe instanceof Promise){qe.then(Re=>{q(J(Re)),H()}).catch(()=>{q(y),H()});return}q(J(qe)),H()},It=null,qt=(S,D,y,P)=>{S.rawContent=D,Ve.has(S.id)||Ve.set(S.id,this.createStreamParser());let T=Ve.get(S.id),I=D.trim().startsWith("{")||D.trim().startsWith("[");if(I&&Te.set(S.id,D),T.__isPlainTextParser===!0){S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S);return}let H=T.processChunk(D);if(H instanceof Promise)H.then(z=>{let J=typeof z=="string"?z:z?.text??null;J!==null&&J.trim()!==""?(S.content=J,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}).catch(()=>{S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S)});else{let z=typeof H=="string"?H:H?.text??null;z!==null&&z.trim()!==""?(S.content=z,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}},xt=(S,D)=>{let y=D??S.content;if(y==null||y===""){S.streaming=!1,f(S);return}let T=Te.get(S.id)??Qe(y);S.rawContent=T;let I=Ve.get(S.id),q=null,H=!1;if(I&&(q=I.getExtractedText(),q===null&&(q=es(T)),q===null)){let z=I.processChunk(T);z instanceof Promise?(H=!0,z.then(J=>{let qe=typeof J=="string"?J:J?.text??null;qe!==null&&(S.content=qe,S.streaming=!1,Ve.delete(S.id),Te.delete(S.id),f(S))}).catch(()=>{})):q=typeof z=="string"?z:z?.text??null}if(!H){q!==null&&q.trim()!==""?S.content=q:Te.has(S.id)||(S.content=Qe(y));let z=Ve.get(S.id);if(z){let J=z.close?.();J instanceof Promise&&J.catch(()=>{}),Ve.delete(S.id)}Te.delete(S.id),S.streaming=!1,f(S)}},He=(S,D,y)=>{let P=_.get(S);if(P)return P;let T={id:`nested-${D}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:D}};return _.set(S,T),f(T),T},de=[],et,Ie=new Map,fe=0,se="agent",Pe=!1,it=null,ue=null,Ce=new Map,te=this.config.iterationDisplay??"separate";for(et=()=>{for(let S=0;S<de.length;S++){let D=de[S].payloadType,y=de[S].payload;if(!Pe&&se!=="flow"&&typeof y.stepType=="string"&&(se="flow"),D==="reasoning_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T),He(P,T,"reasoning");continue}let I=ce(y,!0)??`reason-${c()}`,q=ee(I);q.reasoning=q.reasoning??{id:I,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??De(y.startedAt??y.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),q.streaming=!0,q.reasoning.status="streaming",f(q)}else if(D==="reasoning_delta"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let H=_.get(P),z=y.reasoningText??y.text??y.delta??"";z&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(z)),f(H));continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=ee(T);I.reasoning=I.reasoning??{id:T,status:"streaming",chunks:[]},I.reasoning.startedAt=I.reasoning.startedAt??De(y.startedAt??y.timestamp);let q=y.reasoningText??y.text??y.delta??"";if(q&&y.hidden!==!0){let H=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(H!==void 0){let z=Xe(T,H,String(q));I.reasoning.chunks=[z]}else I.reasoning.chunks.push(String(q))}if(I.reasoning.status=y.done?"complete":"streaming",y.done){I.reasoning.completedAt=De(y.completedAt??y.timestamp);let H=I.reasoning.startedAt??Date.now();I.reasoning.durationMs=Math.max(0,(I.reasoning.completedAt??Date.now())-H)}I.streaming=I.reasoning.status!=="complete",f(I)}else if(D==="reasoning_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let z=_.get(P);if(z.reasoning){let J=typeof y.text=="string"?y.text:"";J&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(J),z.reasoning.status="complete",z.streaming=!1,f(z)}M.delete(P),_.delete(P);continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=typeof y.text=="string"?y.text:"";!x.get(T)&&(I||y.scope==="loop")&&ee(T);let q=x.get(T);if(q?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),I&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(I),q.reasoning.status="complete",q.reasoning.completedAt=De(y.completedAt??y.timestamp);let z=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-z),q.streaming=!1,f(q)}let H=$(y);H&&U.byStep.delete(H)}else if(D==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(fe=y.iteration);let P=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??je(y,!0)??`tool-${c()}`,T=y.toolName??y.name;if(ve(T)){Y.add(P);continue}le(X(y),P);let I=Me(P),q=I.toolCall??{id:P,status:"pending"};q.name=T??q.name,q.status="running",y.parameters!==void 0?q.args=y.parameters:y.args!==void 0&&(q.args=y.args),q.startedAt=q.startedAt??De(y.startedAt??y.timestamp),q.completedAt=void 0,q.durationMs=void 0,I.toolCall=q,I.streaming=!0,y.executionId&&(I.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(I)}else if(D==="tool_output_delta"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P))continue;let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.startedAt=I.startedAt??De(y.startedAt??y.timestamp);let q=y.text??y.delta??y.message??"";q&&(I.chunks=I.chunks??[],I.chunks.push(String(q))),I.status="running",T.toolCall=I,T.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T)}else if(D==="tool_complete"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.status="complete",y.result!==void 0&&(I.result=y.result),typeof y.duration=="number"&&(I.duration=y.duration),I.completedAt=De(y.completedAt??y.timestamp);let q=y.duration??y.executionTime;if(typeof q=="number")I.durationMs=q;else{let J=I.startedAt??Date.now();I.durationMs=Math.max(0,(I.completedAt??Date.now())-J)}T.toolCall=I,T.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T);let z=X(y);z&&oe.byCall.delete(z)}else if(D==="await"&&y.toolName){let P=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,T=P??y.toolId??`local-${c()}`,I=Me(T),q=y.toolName,H=y.origin==="webmcp"&&!Zo(q)?`webmcp:${q}`:q,z=Zo(H),J=I.toolCall??{id:T,status:"pending"};J.name=H,J.args=y.parameters,J.status=z?"running":"complete",J.chunks=J.chunks??[],J.startedAt=J.startedAt??De(y.startedAt??y.timestamp??y.awaitedAt),z?(J.completedAt=void 0,J.duration=void 0,J.durationMs=void 0):J.completedAt=J.completedAt??J.startedAt,I.toolCall=J,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:y.executionId??I.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(I)}else if(D==="text_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T);continue}let I=v;I&&(se==="flow"?(xt(I),It=I):(I.streaming=!1,f(I)),v=null),L=typeof y.id=="string"?y.id:L,E=""}else if(D==="text_delta"){let P=typeof y.id=="string"?y.id:null,T=P?M.get(P):void 0;if(P&&T){let q=typeof y.delta=="string"?y.delta:"",H=(G.get(P)??"")+q;if(G.set(P,H),H.trim()==="")continue;let z=He(P,T);z.agentMetadata={...z.agentMetadata,executionId:y.executionId,parentToolId:T},qt(z,H,q,void 0);continue}if(L=typeof y.id=="string"?y.id:L,se==="flow"){let q=typeof y.delta=="string"?y.delta:"";if(E+=q,E.trim()==="")continue;let H=Ae();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},qt(H,E,q,void 0),C=H;continue}let I=Ae();I.content+=y.delta??"",I.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:it??void 0,agentName:ue?.agentName},C=I,f(I)}else if(D==="text_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)){let I=_.get(P);I&&xt(I),M.delete(P),G.delete(P),_.delete(P);continue}let T=v;T&&(se==="flow"?(xt(T),It=T):((T.content??"")===""&&typeof y.text=="string"&&(T.content=y.text),T.streaming=!1,f(T)),v=null),L=null,E=""}else if(D==="step_complete"){let P=y.stepType,T=y.executionType;if(P==="tool"||T==="context")continue;if(y.success===!1){let I=y.error,q=typeof I=="string"&&I!==""?I:I!=null&&typeof I=="object"&&Reflect.has(I,"message")?String(I.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let H=v;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let I=It;It=null;let q=y.stopReason,H=y.result?.response;if(I)q&&(I.stopReason=q),H!=null?Ht(I,H):I.streaming!==!1&&(Ve.delete(I.id),Te.delete(I.id),I.streaming=!1,f(I));else{let z=H!=null&&H!=="";if(z||q){let J=Ae();q&&(J.stopReason=q),z?xt(J,H):(J.streaming=!1,f(J))}}continue}}else if(D==="execution_start")se=y.kind==="flow"?"flow":"agent",Pe=!0,se==="agent"&&(ue={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:De(y.startedAt)});else if(D==="turn_start"){let P=typeof y.iteration=="number"?y.iteration:fe;if(P!==fe){if(ue&&(ue.currentIteration=P),te==="separate"&&P>1){let T=v;T&&(T.streaming=!1,f(T),Ce.set(P-1,T),v=null)}fe=P}it=typeof y.id=="string"?y.id:null,C=null}else if(D==="tool_input_delta"){let P=y.toolCallId??oe.lastId;if(P){let T=j.get(P);T?.toolCall&&(T.toolCall.chunks=T.toolCall.chunks??[],T.toolCall.chunks.push(y.delta??""),f(T))}}else{if(D==="tool_input_complete")continue;if(D==="turn_complete"){let P=y.stopReason,T=v??C;if(P&&T!==null){let I=y.id;(!I||T.agentMetadata?.turnId===I)&&(T.stopReason=P,f(T))}it===y.id&&(it=null)}else if(D==="media_start"){let P=String(y.id);Ie.set(P,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(D==="media_delta"){let P=Ie.get(String(y.id));P&&typeof y.delta=="string"&&P.parts.push(y.delta)}else if(D==="media_complete"){let P=String(y.id),T=Ie.get(P);Ie.delete(P);let I=(typeof y.mediaType=="string"?y.mediaType:void 0)??T?.mediaType??"application/octet-stream",q=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:T&&T.parts.length>0?T.parts.join(""):void 0,z=null;if(q)z={type:"media",data:q,mediaType:I};else if(H){let Je=I.toLowerCase();z={type:Je==="image"||Je.startsWith("image/")?"image-url":"file-url",url:H,mediaType:I}}let J=y.toolCallId??T?.toolCallId,qe=z?[z]:[],Re=[];for(let Je of qe){if(!Je||typeof Je!="object")continue;let rt=Je,V=typeof rt.type=="string"?rt.type:void 0,_e=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",be=null,$e="";if(V==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;$e=_e.length>0?_e:"application/octet-stream",be=`data:${$e};base64,${Fe}`}else if(V==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else if(V==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else continue;if(be)if(V==="image-url"||$e.startsWith("image/"))Re.push({type:"image",image:be,...$e.includes("/")?{mimeType:$e}:{}});else if($e.startsWith("audio/"))Re.push({type:"audio",audio:be,mimeType:$e});else if($e.startsWith("video/"))Re.push({type:"video",video:be,mimeType:$e});else{let Fe=$e||"application/octet-stream";Re.push({type:"file",data:be,mimeType:Fe,filename:am(Fe)})}}if(Re.length>0){let Je=c(),rt=J,_e={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Je}`:String(Je)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Je,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:fe}};f(_e);let be=v;be&&(be.streaming=!1,f(be)),v=null,R.current=null}}else if(D==="execution_complete"){let P=y.kind??se;P==="agent"&&ue&&(ue.status=y.success?"complete":"error",ue.completedAt=De(y.completedAt),ue.stopReason=y.stopReason);let T=v;T&&(P==="flow"&&T.streaming!==!1?xt(T):(T.streaming=!1,f(T)),v=null),L=null,E="",It=null,n({type:"status",status:"idle",terminal:!0})}else if(D==="execution_error"){let P=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(D!=="ping"){if(D==="approval_start"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(T)}else if(D==="step_await"&&y.awaitReason==="approval_required"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(T)}else if(D==="approval_complete"){let P=y.approvalId;if(P){let I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:y.decision??"approved",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(I)}}else if(D==="artifact_start"||D==="artifact_delta"||D==="artifact_update"||D==="artifact_complete"){if(D==="artifact_start"){let P=y.artifactType,T=String(y.id),I=typeof y.title=="string"?y.title:void 0,q=y.file,H;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&(H={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:T,artifactType:P,title:I,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let z=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ye.set(T,{markdown:"",title:I,file:H,...z?{props:z}:{}}),!xe.has(T)){xe.add(T);let J=ro(this.config.features?.artifacts,{artifactType:P,...H?{file:H}:{}}),qe=typeof y.component=="string"?y.component:void 0,Re={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Qr(J,{artifactId:T,title:I,artifactType:P,status:"streaming",...H?{file:H}:{},...qe?{component:qe}:{}})};pe.set(T,Re),f(Re)}}else if(D==="artifact_delta"){let P=String(y.id),T=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:P,artDelta:T});let I=ye.get(P);I&&(I.markdown+=T)}else if(D==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0});let T=ye.get(String(y.id));T&&(T.props={...T.props??{},...P})}else if(D==="artifact_complete"){let P=String(y.id);n({type:"artifact_complete",id:P});let T=pe.get(P);if(T){T.streaming=!1;try{let I=JSON.parse(T.rawContent??"{}");if(I.props){I.props.status="complete";let q=ye.get(P);q?.markdown&&(I.props.markdown=q.markdown),q?.file&&(I.props.file=q.file),I.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(I.props.componentProps=q.props)}T.rawContent=JSON.stringify(I)}catch{}ye.delete(P),f(T),pe.delete(P)}}}else if(D==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let T=String(P.id??`msg-${c()}`),I=P.role,H={id:T,role:I==="user"?"user":I==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let J=JSON.parse(H.rawContent)?.props?.artifactId;typeof J=="string"&&xe.add(J)}catch{}v=null,R.current=null,Ve.delete(T),Te.delete(T)}else if(D==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let P=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(P)});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}else if(D==="step_error"||D==="dispatch_error"||D==="flow_error"){let P=null;if(y.error instanceof Error)P=y.error;else if(D==="dispatch_error"){let T=y.message??y.error;T!=null&&T!==""&&(P=new Error(String(T)))}else{let T=y.error;typeof T=="string"&&T!==""?P=new Error(T):T!=null&&typeof T=="object"&&Reflect.has(T,"message")&&(P=new Error(String(T.message??T)))}if(P){n({type:"error",error:P});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:S,value:D}=await s.read();if(S)break;l+=a.decode(D,{stream:!0});let y=l.split(`
|
|
11
|
+
`).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 s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ls=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pp=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},up=()=>{let e=Mm();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)}},fp=()=>{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=xm(n,Cm|Am);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?lp(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=lp(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var gp=()=>{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 mp="4.15.0";var cs=mp;var km="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Lm(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 s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var sl=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 Pm(e){switch(e){case"json":return fp;case"regex-json":return up;case"xml":return gp;default:return pp}}var hp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Im(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=hp(n);if(!hp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ls(e);return ls(t)!==null&&a===null?t:e}var ds=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??km,this.headers={"Content-Type":"application/json","X-Persona-Version":cs,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Pm(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 ba(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 s=Kd(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/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}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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$/,"")||Ma}/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}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(sl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.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 a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.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$/,"")||Ma}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?jd(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ma}/resume`,a;r&&(a=(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(a&&(p.sessionId=a),r&&a){let d=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{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 s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));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(sl).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(sl).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),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,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.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 s=t.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=C=>{let $=C.reasoning?{...C.reasoning,chunks:[...C.reasoning.chunks]}:void 0,h=C.toolCall?{...C.toolCall,chunks:C.toolCall.chunks?[...C.toolCall.chunks]:void 0}:void 0,L=C.tools?C.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...C,reasoning:$,toolCall:h,tools:L}},w=C=>{if(C.role!=="assistant"||C.variant)return!0;let $=Array.isArray(C.contentParts)&&C.contentParts.length>0,h=typeof C.rawContent=="string"&&C.rawContent.trim()!=="";return typeof C.content=="string"&&C.content.trim()!==""||$||h||!!C.stopReason},g=C=>{w(C)&&n({type:"message",message:u(C)})},v=null,x=null,P={current:null},F={current:null},k=null,T="",M=new Map,U=new Map,j=new Map,A=new Map,V=new Map,K={lastId:null,byStep:new Map},ne={lastId:null,byCall:new Map},D=C=>{if(C==null)return null;try{return String(C)}catch{return null}},_=C=>D(C.stepId??C.step_id??C.step??C.parentId??C.flowStepId??C.flow_step_id),Y=C=>D(C.callId??C.call_id??C.requestId??C.request_id??C.toolCallId??C.tool_call_id??C.stepId??C.step_id),ge=o,he=!1,ce=()=>{if(v)return v;let C,$="",h=k;return!he&&ge?(C=ge,he=!0,$=r??""):ge&&h?C=`${ge}_${h}`:C=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:C,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},Z=(C,$)=>{K.lastId=$,C&&K.byStep.set(C,$)},de=(C,$)=>{let h=C.reasoningId??C.id,L=_(C);if(h){let H=String(h);return Z(L,H),H}if(L){let H=K.byStep.get(L);if(H)return K.lastId=H,H}if(K.lastId&&!$)return K.lastId;if(!$)return null;let I=`reason-${c()}`;return Z(L,I),I},te=C=>{let $=A.get(C);if($)return $;let h={id:`reason-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:C,status:"streaming",chunks:[]}};return A.set(C,h),g(h),h},ie=(C,$)=>{ne.lastId=$,C&&ne.byCall.set(C,$)},J=new Set,fe=new Map,Ce=new Set,ye=new Map,xe=C=>{if(!C)return!1;let $=C.replace(/_+/g,"_").replace(/^_|_$/g,"");return $==="emit_artifact_markdown"||$==="emit_artifact_component"},ve=(C,$)=>{let h=C.toolId??C.id,L=Y(C);if(h){let H=String(h);return ie(L,H),H}if(L){let H=ne.byCall.get(L);if(H)return ne.lastId=H,H}if(ne.lastId&&!$)return ne.lastId;if(!$)return null;let I=`tool-${c()}`;return ie(L,I),I},Ae=C=>{let $=V.get(C);if($)return $;let h={id:`tool-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:C,status:"pending"}};return V.set(C,h),g(h),h},Te=C=>{if(typeof C=="number"&&Number.isFinite(C))return C;if(typeof C=="string"){let $=Number(C);if(!Number.isNaN($)&&Number.isFinite($))return $;let h=Date.parse(C);if(!Number.isNaN(h))return h}return Date.now()},qe=C=>{if(typeof C=="string")return C;if(C==null)return"";try{return JSON.stringify(C)}catch{return String(C)}},ze=new Map,Me=new Map,Pe=new Map,Ke=(C,$,h)=>{let L=Pe.get(C);L||(L=[],Pe.set(C,L));let I=0,H=L.length;for(;I<H;){let R=I+H>>>1;L[R].seq<$?I=R+1:H=R}L[I]?.seq===$?L[I]={seq:$,text:h}:L.splice(I,0,{seq:$,text:h});let B="";for(let R=0;R<L.length;R++)B+=L[R].text;return B},Wt=(C,$)=>{let h=qe($),L=Me.get(C.id),I=Im(L,h);C.rawContent=I;let H=ze.get(C.id),B=we=>{let nt=C.content??"";we.trim()!==""&&(nt.trim().length===0||we.startsWith(nt)||we.trimStart().startsWith(nt.trim()))&&(C.content=we)},R=()=>{if(H){let we=H.close?.();we instanceof Promise&&we.catch(()=>{})}ze.delete(C.id),Me.delete(C.id),C.streaming=!1,g(C)};if(!H){B(h),R();return}let Q=ls(I);if(Q!==null&&Q.trim()!==""){B(Q),R();return}let se=we=>{let nt=typeof we=="string"?we:we?.text??null;if(nt!==null&&nt.trim()!=="")return nt;let tt=H.getExtractedText();return tt!==null&&tt.trim()!==""?tt:h},Ee;try{Ee=H.processChunk(I)}catch{B(h),R();return}if(Ee instanceof Promise){Ee.then(we=>{B(se(we)),R()}).catch(()=>{B(h),R()});return}B(se(Ee)),R()},It=null,qt=(C,$,h,L)=>{C.rawContent=$,ze.has(C.id)||ze.set(C.id,this.createStreamParser());let I=ze.get(C.id),H=$.trim().startsWith("{")||$.trim().startsWith("[");if(H&&Me.set(C.id,$),I.__isPlainTextParser===!0){C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C);return}let R=I.processChunk($);if(R instanceof Promise)R.then(Q=>{let se=typeof Q=="string"?Q:Q?.text??null;se!==null&&se.trim()!==""?(C.content=se,g(C)):!H&&!$.trim().startsWith("<")&&(C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C))}).catch(()=>{C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C)});else{let Q=typeof R=="string"?R:R?.text??null;Q!==null&&Q.trim()!==""?(C.content=Q,g(C)):!H&&!$.trim().startsWith("<")&&(C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C))}},xt=(C,$)=>{let h=$??C.content;if(h==null||h===""){C.streaming=!1,g(C);return}let I=Me.get(C.id)??qe(h);C.rawContent=I;let H=ze.get(C.id),B=null,R=!1;if(H&&(B=H.getExtractedText(),B===null&&(B=ls(I)),B===null)){let Q=H.processChunk(I);Q instanceof Promise?(R=!0,Q.then(se=>{let Ee=typeof se=="string"?se:se?.text??null;Ee!==null&&(C.content=Ee,C.streaming=!1,ze.delete(C.id),Me.delete(C.id),g(C))}).catch(()=>{})):B=typeof Q=="string"?Q:Q?.text??null}if(!R){B!==null&&B.trim()!==""?C.content=B:Me.has(C.id)||(C.content=qe(h));let Q=ze.get(C.id);if(Q){let se=Q.close?.();se instanceof Promise&&se.catch(()=>{}),ze.delete(C.id)}Me.delete(C.id),C.streaming=!1,g(C)}},Be=(C,$,h)=>{let L=U.get(C);if(L)return L;let I={id:`nested-${$}-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:C,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:$}};return U.set(C,I),g(I),I},ue=[],Xe,We=new Map,me=0,le="agent",Re=!1,Kt=null,pt=null,mt=new Map,z=this.config.iterationDisplay??"separate";for(Xe=()=>{for(let C=0;C<ue.length;C++){let $=ue[C].payloadType,h=ue[C].payload;if(!Re&&le!=="flow"&&typeof h.stepType=="string"&&(le="flow"),$==="reasoning_start"){let L=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(L&&I){M.set(L,I),Be(L,I,"reasoning");continue}let H=de(h,!0)??`reason-${c()}`,B=te(H);B.reasoning=B.reasoning??{id:H,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Te(h.startedAt??h.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(B.reasoning.scope=h.scope),B.streaming=!0,B.reasoning.status="streaming",g(B)}else if($==="reasoning_delta"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)&&U.has(L)){let R=U.get(L),Q=h.reasoningText??h.text??h.delta??"";Q&&h.hidden!==!0&&R.reasoning&&(R.reasoning.chunks.push(String(Q)),g(R));continue}let I=de(h,!1)??de(h,!0)??`reason-${c()}`,H=te(I);H.reasoning=H.reasoning??{id:I,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??Te(h.startedAt??h.timestamp);let B=h.reasoningText??h.text??h.delta??"";if(B&&h.hidden!==!0){let R=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(R!==void 0){let Q=Ke(I,R,String(B));H.reasoning.chunks=[Q]}else H.reasoning.chunks.push(String(B))}if(H.reasoning.status=h.done?"complete":"streaming",h.done){H.reasoning.completedAt=Te(h.completedAt??h.timestamp);let R=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-R)}H.streaming=H.reasoning.status!=="complete",g(H)}else if($==="reasoning_complete"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)&&U.has(L)){let Q=U.get(L);if(Q.reasoning){let se=typeof h.text=="string"?h.text:"";se&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(se),Q.reasoning.status="complete",Q.streaming=!1,g(Q)}M.delete(L),U.delete(L);continue}let I=de(h,!1)??de(h,!0)??`reason-${c()}`,H=typeof h.text=="string"?h.text:"";!A.get(I)&&(H||h.scope==="loop")&&te(I);let B=A.get(I);if(B?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(B.reasoning.scope=h.scope),H&&B.reasoning.chunks.length===0&&B.reasoning.chunks.push(H),B.reasoning.status="complete",B.reasoning.completedAt=Te(h.completedAt??h.timestamp);let Q=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-Q),B.streaming=!1,g(B)}let R=_(h);R&&K.byStep.delete(R)}else if($==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(me=h.iteration);let L=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??ve(h,!0)??`tool-${c()}`,I=h.toolName??h.name;if(xe(I)){J.add(L);continue}ie(Y(h),L);let H=Ae(L),B=H.toolCall??{id:L,status:"pending"};B.name=I??B.name,B.status="running",h.parameters!==void 0?B.args=h.parameters:h.args!==void 0&&(B.args=h.args),B.startedAt=B.startedAt??Te(h.startedAt??h.timestamp),B.completedAt=void 0,B.durationMs=void 0,H.toolCall=B,H.streaming=!0,h.executionId&&(H.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(H)}else if($==="tool_output_delta"){let L=ve(h,!1)??ve(h,!0)??`tool-${c()}`;if(J.has(L))continue;let I=Ae(L),H=I.toolCall??{id:L,status:"running"};H.startedAt=H.startedAt??Te(h.startedAt??h.timestamp);let B=h.text??h.delta??h.message??"";B&&(H.chunks=H.chunks??[],H.chunks.push(String(B))),H.status="running",I.toolCall=H,I.streaming=!0;let R=h.agentContext;(R||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:R?.executionId??h.executionId,iteration:R?.iteration??h.iteration}),g(I)}else if($==="tool_complete"){let L=ve(h,!1)??ve(h,!0)??`tool-${c()}`;if(J.has(L)){J.delete(L);continue}let I=Ae(L),H=I.toolCall??{id:L,status:"running"};H.status="complete",h.result!==void 0&&(H.result=h.result),typeof h.duration=="number"&&(H.duration=h.duration),H.completedAt=Te(h.completedAt??h.timestamp);let B=h.duration??h.executionTime;if(typeof B=="number")H.durationMs=B;else{let se=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-se)}I.toolCall=H,I.streaming=!1;let R=h.agentContext;(R||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:R?.executionId??h.executionId,iteration:R?.iteration??h.iteration}),g(I);let Q=Y(h);Q&&ne.byCall.delete(Q)}else if($==="await"&&h.toolName){let L=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,I=L??h.toolId??`local-${c()}`,H=Ae(I),B=h.toolName,R=h.origin==="webmcp"&&!or(B)?`webmcp:${B}`:B,Q=or(R),se=H.toolCall??{id:I,status:"pending"};se.name=R,se.args=h.parameters,se.status=Q?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Te(h.startedAt??h.timestamp??h.awaitedAt),Q?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,H.toolCall=se,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:h.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...L?{webMcpToolCallId:L}:{}},g(H)}else if($==="text_start"){let L=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(L&&I){M.set(L,I);continue}let H=v;H&&(le==="flow"?(xt(H),It=H):(H.streaming=!1,g(H)),v=null),k=typeof h.id=="string"?h.id:k,T=""}else if($==="text_delta"){let L=typeof h.id=="string"?h.id:null,I=L?M.get(L):void 0;if(L&&I){let B=typeof h.delta=="string"?h.delta:"",R=(j.get(L)??"")+B;if(j.set(L,R),R.trim()==="")continue;let Q=Be(L,I);Q.agentMetadata={...Q.agentMetadata,executionId:h.executionId,parentToolId:I},qt(Q,R,B,void 0);continue}if(k=typeof h.id=="string"?h.id:k,le==="flow"){let B=typeof h.delta=="string"?h.delta:"";if(T+=B,T.trim()==="")continue;let R=ce();R.agentMetadata={executionId:h.executionId,iteration:h.iteration},qt(R,T,B,void 0),x=R;continue}let H=ce();H.content+=h.delta??"",H.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:Kt??void 0,agentName:pt?.agentName},x=H,g(H)}else if($==="text_complete"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)){let H=U.get(L);H&&xt(H),M.delete(L),j.delete(L),U.delete(L);continue}let I=v;I&&(le==="flow"?(xt(I),It=I):((I.content??"")===""&&typeof h.text=="string"&&(I.content=h.text),I.streaming=!1,g(I)),v=null),k=null,T=""}else if($==="step_complete"){let L=h.stepType,I=h.executionType;if(L==="tool"||I==="context")continue;if(h.success===!1){let H=h.error,B=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(B)});let R=v;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"});continue}{let H=It;It=null;let B=h.stopReason,R=h.result?.response;if(H)B&&(H.stopReason=B),R!=null?Wt(H,R):H.streaming!==!1&&(ze.delete(H.id),Me.delete(H.id),H.streaming=!1,g(H));else{let Q=R!=null&&R!=="";if(Q||B){let se=ce();B&&(se.stopReason=B),Q?xt(se,R):(se.streaming=!1,g(se))}}continue}}else if($==="execution_start")le=h.kind==="flow"?"flow":"agent",Re=!0,le==="agent"&&(pt={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Te(h.startedAt)});else if($==="turn_start"){let L=typeof h.iteration=="number"?h.iteration:me;if(L!==me){if(pt&&(pt.currentIteration=L),z==="separate"&&L>1){let I=v;I&&(I.streaming=!1,g(I),mt.set(L-1,I),v=null)}me=L}Kt=typeof h.id=="string"?h.id:null,x=null}else if($==="tool_input_delta"){let L=h.toolCallId??ne.lastId;if(L){let I=V.get(L);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(h.delta??""),g(I))}}else{if($==="tool_input_complete")continue;if($==="turn_complete"){let L=h.stopReason,I=v??x;if(L&&I!==null){let H=h.id;(!H||I.agentMetadata?.turnId===H)&&(I.stopReason=L,g(I))}Kt===h.id&&(Kt=null)}else if($==="media_start"){let L=String(h.id);We.set(L,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if($==="media_delta"){let L=We.get(String(h.id));L&&typeof h.delta=="string"&&L.parts.push(h.delta)}else if($==="media_complete"){let L=String(h.id),I=We.get(L);We.delete(L);let H=(typeof h.mediaType=="string"?h.mediaType:void 0)??I?.mediaType??"application/octet-stream",B=typeof h.data=="string"?h.data:void 0,R=typeof h.url=="string"?h.url:I&&I.parts.length>0?I.parts.join(""):void 0,Q=null;if(B)Q={type:"media",data:B,mediaType:H};else if(R){let nt=H.toLowerCase();Q={type:nt==="image"||nt.startsWith("image/")?"image-url":"file-url",url:R,mediaType:H}}let se=h.toolCallId??I?.toolCallId,Ee=Q?[Q]:[],we=[];for(let nt of Ee){if(!nt||typeof nt!="object")continue;let tt=nt,_e=typeof tt.type=="string"?tt.type:void 0,Je=typeof tt.mediaType=="string"?tt.mediaType.toLowerCase():"",q=null,$e="";if(_e==="media"){let De=typeof tt.data=="string"?tt.data:void 0;if(!De)continue;$e=Je.length>0?Je:"application/octet-stream",q=`data:${$e};base64,${De}`}else if(_e==="image-url"){let De=typeof tt.url=="string"?tt.url:void 0;if(!De)continue;$e=Je,q=De}else if(_e==="file-url"){let De=typeof tt.url=="string"?tt.url:void 0;if(!De)continue;$e=Je,q=De}else continue;if(q)if(_e==="image-url"||$e.startsWith("image/"))we.push({type:"image",image:q,...$e.includes("/")?{mimeType:$e}:{}});else if($e.startsWith("audio/"))we.push({type:"audio",audio:q,mimeType:$e});else if($e.startsWith("video/"))we.push({type:"video",video:q,mimeType:$e});else{let De=$e||"application/octet-stream";we.push({type:"file",data:q,mimeType:De,filename:Lm(De)})}}if(we.length>0){let nt=c(),tt=se,Je={id:`agent-media-${typeof tt=="string"&&tt.length>0?`${tt}-${nt}`:String(nt)}`,role:"assistant",content:"",contentParts:we,createdAt:new Date().toISOString(),streaming:!1,sequence:nt,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:me}};g(Je);let q=v;q&&(q.streaming=!1,g(q)),v=null,P.current=null}}else if($==="execution_complete"){let L=h.kind??le;L==="agent"&&pt&&(pt.status=h.success?"complete":"error",pt.completedAt=Te(h.completedAt),pt.stopReason=h.stopReason);let I=v;I&&(L==="flow"&&I.streaming!==!1?xt(I):(I.streaming=!1,g(I)),v=null),k=null,T="",It=null,n({type:"status",status:"idle",terminal:!0})}else if($==="execution_error"){let L=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(L)})}else if($!=="ping"){if($==="approval_start"){let L=h.approvalId??`approval-${c()}`,I={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:"pending",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(I)}else if($==="step_await"&&h.awaitReason==="approval_required"){let L=h.approvalId??`approval-${c()}`,I={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:"pending",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(I)}else if($==="approval_complete"){let L=h.approvalId;if(L){let H={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:h.decision??"approved",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(H)}}else if($==="artifact_start"||$==="artifact_delta"||$==="artifact_update"||$==="artifact_complete"){if($==="artifact_start"){let L=h.artifactType,I=String(h.id),H=typeof h.title=="string"?h.title:void 0,B=h.file,R;B&&typeof B=="object"&&!Array.isArray(B)&&typeof B.path=="string"&&typeof B.mimeType=="string"&&(R={path:B.path,mimeType:B.mimeType,...typeof B.language=="string"?{language:B.language}:{}}),n({type:"artifact_start",id:I,artifactType:L,title:H,component:typeof h.component=="string"?h.component:void 0,...R?{file:R}:{}});let Q=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(ye.set(I,{markdown:"",title:H,file:R,...Q?{props:Q}:{}}),!Ce.has(I)){Ce.add(I);let se=io(this.config.features?.artifacts,{artifactType:L,...R?{file:R}:{}}),Ee=typeof h.component=="string"?h.component:void 0,we={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ns(se,{artifactId:I,title:H,artifactType:L,status:"streaming",...R?{file:R}:{},...Ee?{component:Ee}:{}})};fe.set(I,we),g(we)}}else if($==="artifact_delta"){let L=String(h.id),I=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:L,artDelta:I});let H=ye.get(L);H&&(H.markdown+=I)}else if($==="artifact_update"){let L=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:L,component:typeof h.component=="string"?h.component:void 0});let I=ye.get(String(h.id));I&&(I.props={...I.props??{},...L})}else if($==="artifact_complete"){let L=String(h.id);n({type:"artifact_complete",id:L});let I=fe.get(L);if(I){I.streaming=!1;try{let H=JSON.parse(I.rawContent??"{}");if(H.props){H.props.status="complete";let B=ye.get(L);B?.markdown&&(H.props.markdown=B.markdown),B?.file&&(H.props.file=B.file),H.component==="PersonaArtifactInline"&&B?.props&&Object.keys(B.props).length>0&&(H.props.componentProps=B.props)}I.rawContent=JSON.stringify(H)}catch{}ye.delete(L),g(I),fe.delete(L)}}}else if($==="transcript_insert"){let L=h.message;if(!L||typeof L!="object")continue;let I=String(L.id??`msg-${c()}`),H=L.role,R={id:I,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof L.content=="string"?L.content:"",rawContent:typeof L.rawContent=="string"?L.rawContent:void 0,createdAt:typeof L.createdAt=="string"?L.createdAt:new Date().toISOString(),streaming:L.streaming===!0,...typeof L.variant=="string"?{variant:L.variant}:{},sequence:c()};if(g(R),R.rawContent)try{let se=JSON.parse(R.rawContent)?.props?.artifactId;typeof se=="string"&&Ce.add(se)}catch{}v=null,P.current=null,ze.delete(I),Me.delete(I)}else if($==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let L=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(L)});let I=v;I&&I.streaming&&(I.streaming=!1,g(I)),n({type:"status",status:"idle"})}}else if($==="step_error"||$==="dispatch_error"||$==="flow_error"){let L=null;if(h.error instanceof Error)L=h.error;else if($==="dispatch_error"){let I=h.message??h.error;I!=null&&I!==""&&(L=new Error(String(I)))}else{let I=h.error;typeof I=="string"&&I!==""?L=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(L=new Error(String(I.message??I)))}if(L){n({type:"error",error:L});let I=v;I&&I.streaming&&(I.streaming=!1,g(I)),n({type:"status",status:"idle"})}}}}}ue.length=0};;){let{done:C,value:$}=await s.read();if(C)break;l+=a.decode($,{stream:!0});let h=l.split(`
|
|
12
12
|
|
|
13
|
-
`);l=
|
|
14
|
-
`),I="message",q="",H=null;for(let Re of T)Re.startsWith("event:")?I=Re.replace("event:","").trim():Re.startsWith("data:")?q+=Re.replace("data:","").trim():Re.startsWith("id:")&&(H=Re.slice(3).trim());let z=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!q){z();continue}let J;try{J=JSON.parse(q)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let qe=I!=="message"?I:J.type??"message";if(this.onSSEEvent?.(qe,J),this.parseSSEEvent){R.current=v;let Re=await this.handleCustomSSEEvent(J,n,R,f,c,B);if(R.current&&R.current!==v&&(v=R.current),Re){z();continue}}de.push({payloadType:qe,payload:J}),et(),z()}}et()}};function xa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ca="[Image]";function Zd(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ar(e){return{type:"text",text:e}}var ep=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cm=["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"],_n=[...ep,...cm];function dm(e){return ep.includes(e)||e.startsWith("image/")}function Aa(e){return dm(e.type)}async function tp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Aa(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 np(e,t=_n,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 pm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function op(e,t){let n=pm(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 rp=16e3,um=24e3,fm=4096,gm=1380533830;function mm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===gm?new Uint8Array(e,44):new Uint8Array(e)}function hm(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 os=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 s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:rp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new cd(um);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${hm(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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 s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(fm,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.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=mm(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 Io=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(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({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 ir(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new os(e.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(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 sp(e){if(e?.type==="custom"&&e.custom)return ir({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return ir({type:"runtype",runtype:e.runtype});if(Io.isSupported())return ir({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tl(e){try{return sp(e),!0}catch{return!1}}function Sa(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 lr=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),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Sa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.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 rs=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 nl(e){if(!e)return"";let t=ym(e);return ap(t!==null?t:e)}function ym(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 ap(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,`
|
|
13
|
+
`);l=h.pop()??"";for(let L of h){let I=L.split(`
|
|
14
|
+
`),H="message",B="",R=null;for(let we of I)we.startsWith("event:")?H=we.replace("event:","").trim():we.startsWith("data:")?B+=we.replace("data:","").trim():we.startsWith("id:")&&(R=we.slice(3).trim());let Q=()=>{R!==null&&R!==""&&n({type:"cursor",id:R})};if(!B){Q();continue}let se;try{se=JSON.parse(B)}catch(we){n({type:"error",error:we instanceof Error?we:new Error("Failed to parse chat stream payload")});continue}let Ee=H!=="message"?H:se.type??"message";if(this.onSSEEvent?.(Ee,se),this.parseSSEEvent){P.current=v;let we=await this.handleCustomSSEEvent(se,n,P,g,c,F);if(P.current&&P.current!==v&&(v=P.current),we){Q();continue}}ue.push({payloadType:Ee,payload:se}),Xe(),Q()}}Xe()}};function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function cr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ka="[Image]";function yp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function dr(e){return{type:"text",text:e}}var bp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Rm=["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"],zn=[...bp,...Rm];function Wm(e){return bp.includes(e)||e.startsWith("image/")}function La(e){return Wm(e.type)}async function vp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;La(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 wp(e,t=zn,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 Hm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function xp(e,t){let n=Hm(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 Cp=16e3,Bm=24e3,Dm=4096,Fm=1380533830;function Nm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Fm?new Uint8Array(e,44):new Uint8Array(e)}function Om(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Cp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Cp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ed(Bm);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Om(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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 s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Dm,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.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=Nm(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 Bo=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(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({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 pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ps(e.runtype);case"browser":if(!Bo.isSupported())throw new Error("Browser speech recognition not supported");return new Bo(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 Ap(e){if(e?.type==="custom"&&e.custom)return pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return pr({type:"runtype",runtype:e.runtype});if(Bo.isSupported())return pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function al(e){try{return Ap(e),!0}catch{return!1}}function Pa(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 ur=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),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Pa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.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 us=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 il(e){if(!e)return"";let t=_m(e);return Sp(t!==null?t:e)}function _m(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 Sp(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,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
|
-
`),t.trim()}var
|
|
16
|
+
`),t.trim()}var Tp=null;var ll=()=>Tp?Tp():import("./runtype-tts-entry-UJAEF7NZ.js");var $m=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Um(e,t){return $m.some(n=>e[n]!==t[n])}function cl(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}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]}),lp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,cp=e=>Zo(e)||e===On,Ta=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 rs(()=>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&&(Zo(n.name)||n.name===On&&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 ns(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||ol().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 tl(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=lr.isSupported()?new lr({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,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return ol().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&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=ir(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,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:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,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(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),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(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),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(!vm(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ns(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}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:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?xa():n==="assistant"?sr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,C={id:p??(r==="user"?xa():r==="assistant"?sr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),Mp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ep=e=>or(e)||e===Un,Ia=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 us(()=>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&&(or(n.name)||n.name===Un&&po(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 ds(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||ll().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 al(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=ur.isSupported()?new ur({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,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return ll().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&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=pr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,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:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,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(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),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(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),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(!Um(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ds(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}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:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?Ea():n==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}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:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:g}=o,x={id:p??(r==="user"?Ea():r==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...g!==void 0&&{rawContent:g}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(ar(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(ar(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);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=xa(),s=sr();this.activeAssistantMessageId=null;let a=n?.contentParts&&Zd(n.contentParts)?Ca:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=rl(c,this.config.errorMessage);if(w){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=sr();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 s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=rl(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(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 s of this.messages)s.streaming&&s.id!==o&&(s.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(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}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(s=>s.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}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let v=c[f],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==On?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},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=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:u,resumeKey:f,output:Ji(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),R;if(!C)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await C}catch(B){let L=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return L||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,ss(L?"Aborted by cancel()":lp(B)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,ss("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:R,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===On?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,ss("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),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 v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);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(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===On,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Ji():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,ss("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,ss(C||p.aborted?"Aborted by cancel()":lp(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.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=ro(this.config.features?.artifacts,t),r=Qr(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}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.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(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ro(this.config.features?.artifacts,n),s=Qr(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!==s&&(o.rawContent=s,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=import("./session-reconnect-JKIJBHS5.js").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=>rl(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=sr(),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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=nl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Sa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=nl(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,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&cp(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&cp(f)&&r.toolCall?.status==="complete";(u||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),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(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ma={allowedTypes:_n,maxFileSize:10*1024*1024,maxFiles:4};function wm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xm(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 as=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ma.allowedTypes,maxFileSize:t.maxFileSize??Ma.maxFileSize,maxFiles:t.maxFiles??Ma.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:Ma.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=np(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 tp(n),s=Aa(n)?URL.createObjectURL(n):null,a={id:wm(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.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=Aa(t.file),o=h("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 a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=xm(t.file.type),p=ie(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=h("span");d.textContent=op(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=h("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 s=ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.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 Lt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Ea=Vt+1;var Cm=8,Am=8,sl=10,al=new WeakMap,dp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Sm=e=>{let t=e.getRootNode?.();return dp(t)?t:e.ownerDocument.body},il=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ot(e){al.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Cm,viewportPadding:a=Am}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,f=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),R=()=>{u?.(),u=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let oe=l(),F=p(),$=t.getBoundingClientRect(),X=d.getBoundingClientRect(),me=oe.documentElement.clientWidth||F.innerWidth,he=oe.documentElement.clientHeight||F.innerHeight,Ae=me-a-X.width,Z=$.left+$.width/2-X.width/2,ce=il(Z,a,Ae),ee=$.top-a,le=he-a-$.bottom,Y=X.height+s,pe=ee>=Y||ee>=le?"top":"bottom",xe=pe==="top"?$.top-s-X.height:$.bottom+s,ye=he-a-X.height,ve=il(xe,a,ye),je=$.left+$.width/2,Me=Math.max(sl,X.width-sl),De=il(je-ce,sl,Me);d.dataset.placement=pe,d.style.left=`${ce}px`,d.style.top=`${ve}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${De}px`)},L=()=>{if(v||!r||d||!t.isConnected)return;let oe=C(),F=Sm(t);if(!oe||!F)return;let $=l(),X=p();d=$.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Ea),c=$.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=oe,d.appendChild(c);let me=$.createElement("span");me.className="persona-control-tooltip__arrow",d.appendChild(me),F.appendChild(d),B(),d.dataset.state="open";let he=()=>{if(!t.isConnected){R();return}c&&(c.textContent=C()),B()};X.addEventListener("scroll",he,!0),X.addEventListener("resize",he);let Ae=t.getRootNode(),Z=dp(Ae)?Ae:$.documentElement,ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||R()});ce?.observe(Z,{childList:!0,subtree:!0}),u=()=>{X.removeEventListener("scroll",he,!0),X.removeEventListener("resize",he),ce?.disconnect()}},E=()=>{w||f?L():R()},M=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(w=!0,E())},_=()=>{w=!1,E()},G=()=>{f=!0,E()},x=()=>{f=!1,E()},j=oe=>{oe.key==="Escape"&&(w=!1,f=!1,R())};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",_),t.addEventListener("focus",G),t.addEventListener("blur",x),t.addEventListener("keydown",j);let U={get isOpen(){return d!==null},show:L,hide:R,reposition:B,destroy:()=>{v||(v=!0,R(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",G),t.removeEventListener("blur",x),t.removeEventListener("keydown",j),al.delete(t))}};return al.set(t,U),U}function pp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=h("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-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ie(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ot({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:nw,load:Tm}=Yo({fallbackImport:()=>import("./context-mentions-ONG7A7M6.js")});var ll=Tm;var{setLoader:sw,load:Mm}=Yo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var up=Mm;function is(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Be("span",{className:Dn("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=ie(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Be("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function fp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=ud(t).filter(E=>E.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(E=>E.sources.some(M=>typeof M.matchCommand=="function")),r=E=>o.some(M=>M.trigger?M.position==="line-start"?E.split(`
|
|
23
|
-
`).some(
|
|
24
|
-
`)[0]).startsWith(M.trigger):!1),s=(E,M)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:M}))}catch{}},a=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,w=null,f=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let E=ll().then(M=>(l=M.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:L,emit:s}),l)).catch(M=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",M),p===E&&(p=null),null));return p=E,E},C=()=>{up().then(E=>{let M=E.mountInlineComposer({textarea:e.textarea,renderToken:G=>is(G,{render:t.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});c=M.input,u=M.destroy;let _=d;_.replaceWith(M.element),d=M.element,f={next:M.element,prev:_},w?.(M.element,_),l?l.rebindComposer(M.input):p&&p.then(G=>G?.rebindComposer(M.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};t.display==="inline"&&C();let R=[],B=new Map;for(let E of n){if(!E.showButton)continue;let M=pp({config:{...t,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(_=>_?.openMenu(E.trigger))}});R.push(M),B.set(E.trigger,M.button)}let L=(E,M,_)=>{let G=B.get(M);G&&(G.setAttribute("aria-expanded",E?"true":"false"),E?G.setAttribute("aria-controls",_):G.removeAttribute("aria-controls"))};return{affordanceButtons:R.map(E=>E.wrapper),contextRow:a,handleInput:E=>{if(l){l.handleInput();return}if(!pd(E))return;let M=d,_=M.selectionStart??0;dd(M.value,_,n)&&v().then(G=>G?.handleInput())},handleKeydown:E=>{if(l?.isMenuOpen())return l.handleKeydown(E);if(E.key==="Backspace"&&l?.hasMentions()&&!f){let M=d,_=M.selectionStart===0&&M.selectionEnd===0;if((M.value.length===0||_)&&l.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(l??await v())?.dispatchInlineCommand(E)??null:null,clear:()=>l?.clear(),prefetch:()=>{ll().catch(()=>{})},onComposerSwap:E=>{w=E,f&&E(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let E of R)E.wrapper.remove();a.remove()}}}var gp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ls(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];gp(s)&&gp(r)?n[o]=ls(s,r):n[o]=r}return n}var $n="min(440px, calc(100vw - 24px))",hp="440px",Em={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:$n,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:Em,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 mp(e,t){if(!(!e&&!t))return e?t?ls(e,t):e:t}function ka(e){return e?{...at,...e,theme:mp(at.theme,e.theme),darkTheme:mp(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,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,l=at.features?.streamAnimation,p=e.features?.streamAnimation,d=at.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...at.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),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 La="16px",Pa="transparent",km={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"}},Lm={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"}},Pm={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:$n,maxWidth:hp,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:La,canvasBackground:Pa},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 Gt(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."))?Gt(e,o):o}function yp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Gt(e,a);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 a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Im(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 bp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=bp(s,r):n[o]=r}return n}function Rm(e,t){return t?bp(e,t):e}function cr(e,t={}){let n={palette:km,semantic:Lm,components:Pm},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:Rm(n.components,e?.components)};if(t.validate!==!1){let r=Im(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function vp(e){let t=yp(e),n={};for(let[x,j]of Object.entries(t)){let U=x.replace(/\./g,"-");n[`--persona-${U}`]=j.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"]??La,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Pa,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 s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let f=d?.artifact;if(f?.toolbar){let x=f.toolbar;x.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=x.iconHoverColor),x.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=x.iconHoverBackground),x.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=x.iconPadding),x.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=x.iconBorderRadius),x.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=x.iconBorder),x.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=x.toggleGroupGap),x.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=x.toggleBorderRadius),x.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=x.toggleGroupPadding),x.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=x.toggleGroupBorder),x.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=x.toggleGroupBorderRadius),x.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(e,x.toggleGroupBackground)??x.toggleGroupBackground),x.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=x.copyBackground),x.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=x.copyBorder),x.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=x.copyColor),x.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=x.copyBorderRadius),x.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=x.copyPadding),x.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=x.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??x.copyMenuBackground),x.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=x.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??x.copyMenuBorder),x.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=x.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??x.copyMenuShadow),x.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=x.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??x.copyMenuBorderRadius),x.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=x.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??x.copyMenuItemHoverBackground),x.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=x.iconBackground),x.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=x.toolbarBorder)}if(f?.tab){let x=f.tab;x.background&&(n["--persona-artifact-tab-bg"]=x.background),x.activeBackground&&(n["--persona-artifact-tab-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-artifact-tab-active-border"]=x.activeBorder),x.borderRadius&&(n["--persona-artifact-tab-radius"]=x.borderRadius),x.textColor&&(n["--persona-artifact-tab-color"]=x.textColor),x.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=x.hoverBackground),x.listBackground&&(n["--persona-artifact-tab-list-bg"]=x.listBackground),x.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=x.listBorderColor),x.listPadding&&(n["--persona-artifact-tab-list-padding"]=x.listPadding)}if(f?.pane){let x=f.pane;if(x.toolbarBackground){let j=Gt(e,x.toolbarBackground)??x.toolbarBackground;n["--persona-artifact-toolbar-bg"]=j}}if(f?.card){let x=f.card;x.background&&(n["--persona-artifact-card-bg"]=x.background),x.border&&(n["--persona-artifact-card-border"]=x.border),x.borderRadius&&(n["--persona-artifact-card-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=x.hoverBackground),x.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=x.hoverBorderColor)}if(f?.inline){let x=f.inline;x.background&&(n["--persona-artifact-inline-bg"]=Gt(e,x.background)??x.background),x.border&&(n["--persona-artifact-inline-border"]=x.border),x.borderRadius&&(n["--persona-artifact-inline-radius"]=x.borderRadius),x.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,x.mutedColor)??x.mutedColor),x.frameHeight&&(n["--persona-artifact-inline-frame-height"]=x.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Gt(e,v.background)??v.background));let C=n["--persona-surface"],R=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",L=n["--persona-palette-colors-gray-200"]??"#e5e7eb",E=n["--persona-palette-colors-gray-300"]??"#d1d5db",M=!R||R===C,_=M?B:R,G=M?L:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,M&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??E),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var Wm={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"}}},wp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},cl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Hm=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":cl()},xp=e=>Hm(e),Bm=e=>cr(e),Dm=e=>cr({...e,palette:{...e?.palette,colors:{...Wm.colors,...e?.palette?.colors}}},{validate:!1}),dr=e=>{let t=xp(e),n=wp(e?.theme),o=wp(e?.darkTheme);return t==="dark"?Dm(ls(n??{},o??{})):Bm(n)},Fm=e=>vp(e),cs=(e,t)=>{let n=dr(t),o=Fm(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xp(t))},Ia=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(cl())});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(cl());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 Mn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Cp(e){let t=Mn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ra(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(dr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(dr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);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=Ea(),s=cr();this.activeAssistantMessageId=null;let a=n?.contentParts&&yp(n.contentParts)?ka:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=cl(c,this.config.errorMessage);if(w){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=cr();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 s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=cl(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(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 s of this.messages)s.streaming&&s.id!==o&&(s.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(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}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(s=>s.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}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let v=c[g],x=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===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!==Un?!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(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},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=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??d;if(d===Un)return{dedupeKey:u,resumeKey:g,output:ol(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let x=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),P;if(!x)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await x}catch(F){let k=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return k||this.callbacks.onError?.(F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(p,fs(k?"Aborted by cancel()":Mp(F)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:P,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Un?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,fs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),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 v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);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(v)}catch(x){this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Un,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",g=a;try{let v;if(d?v=ol():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),a);return}let x=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||x||p.aborted)&&this.markWebMcpToolComplete(t,fs(x||p.aborted?"Aborted by cancel()":Mp(v)),a),x||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.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=io(this.config.features?.artifacts,t),r=ns(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}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.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(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=io(this.config.features?.artifacts,n),s=ns(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!==s&&(o.rawContent=s,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=import("./session-reconnect-JKIJBHS5.js").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=>cl(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=cr(),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(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=il(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Pa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=il(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,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Ep(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&Ep(g)&&r.toolCall?.status==="complete";(u||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),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(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ra={allowedTypes:zn,maxFileSize:10*1024*1024,maxFiles:4};function zm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function jm(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 gs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ra.allowedTypes,maxFileSize:t.maxFileSize??Ra.maxFileSize,maxFiles:t.maxFiles??Ra.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:Ra.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=wp(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 vp(n),s=La(n)?URL.createObjectURL(n):null,a={id:zm(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.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=La(t.file),o=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=jm(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=y("span");d.textContent=xp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.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 Lt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Wa=Vt+1;var Vm=8,qm=8,dl=10,pl=new WeakMap,kp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Km=e=>{let t=e.getRootNode?.();return kp(t)?t:e.ownerDocument.body},ul=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ot(e){pl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Vm,viewportPadding:a=qm}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,g=!1,v=!1,x=()=>(typeof o=="function"?o():o).trim(),P=()=>{u?.(),u=null,d?.remove(),d=null,c=null},F=()=>{if(!d)return;let ne=l(),D=p(),_=t.getBoundingClientRect(),Y=d.getBoundingClientRect(),ge=ne.documentElement.clientWidth||D.innerWidth,he=ne.documentElement.clientHeight||D.innerHeight,ce=ge-a-Y.width,Z=_.left+_.width/2-Y.width/2,de=ul(Z,a,ce),te=_.top-a,ie=he-a-_.bottom,J=Y.height+s,fe=te>=J||te>=ie?"top":"bottom",Ce=fe==="top"?_.top-s-Y.height:_.bottom+s,ye=he-a-Y.height,xe=ul(Ce,a,ye),ve=_.left+_.width/2,Ae=Math.max(dl,Y.width-dl),Te=ul(ve-de,dl,Ae);d.dataset.placement=fe,d.style.left=`${de}px`,d.style.top=`${xe}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Te}px`)},k=()=>{if(v||!r||d||!t.isConnected)return;let ne=x(),D=Km(t);if(!ne||!D)return;let _=l(),Y=p();d=_.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Wa),c=_.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=ne,d.appendChild(c);let ge=_.createElement("span");ge.className="persona-control-tooltip__arrow",d.appendChild(ge),D.appendChild(d),F(),d.dataset.state="open";let he=()=>{if(!t.isConnected){P();return}c&&(c.textContent=x()),F()};Y.addEventListener("scroll",he,!0),Y.addEventListener("resize",he);let ce=t.getRootNode(),Z=kp(ce)?ce:_.documentElement,de=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||P()});de?.observe(Z,{childList:!0,subtree:!0}),u=()=>{Y.removeEventListener("scroll",he,!0),Y.removeEventListener("resize",he),de?.disconnect()}},T=()=>{w||g?k():P()},M=()=>{let ne=p();(!ne.matchMedia||!ne.matchMedia("(hover: none)").matches)&&(w=!0,T())},U=()=>{w=!1,T()},j=()=>{g=!0,T()},A=()=>{g=!1,T()},V=ne=>{ne.key==="Escape"&&(w=!1,g=!1,P())};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",U),t.addEventListener("focus",j),t.addEventListener("blur",A),t.addEventListener("keydown",V);let K={get isOpen(){return d!==null},show:k,hide:P,reposition:F,destroy:()=>{v||(v=!0,P(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",U),t.removeEventListener("focus",j),t.removeEventListener("blur",A),t.removeEventListener("keydown",V),pl.delete(t))}};return pl.set(t,K),K}function Lp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=y("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-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ot({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:Lw,load:Gm}=nr({fallbackImport:()=>import("./context-mentions-BTSTIBFC.js")});var fl=Gm;var{setLoader:Rw,load:Qm}=nr({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Pp=Qm;function ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ie("span",{className:On("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=y("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 Ip(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Pd(t).filter(T=>T.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(T=>T.sources.some(M=>typeof M.matchCommand=="function")),r=T=>o.some(M=>M.trigger?M.position==="line-start"?T.split(`
|
|
23
|
+
`).some(j=>j.startsWith(M.trigger)):(M.position==="anywhere"?T:T.split(`
|
|
24
|
+
`)[0]).startsWith(M.trigger):!1),s=(T,M)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:M}))}catch{}},a=Ie("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,w=null,g=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let T=fl().then(M=>(l=M.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:k,emit:s}),l)).catch(M=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",M),p===T&&(p=null),null));return p=T,T},x=()=>{Pp().then(T=>{let M=T.mountInlineComposer({textarea:e.textarea,renderToken:j=>ms(j,{render:t.renderMentionToken}),onMentionRemoved:j=>l?.untrackMention(j)});c=M.input,u=M.destroy;let U=d;U.replaceWith(M.element),d=M.element,g={next:M.element,prev:U},w?.(M.element,U),l?l.rebindComposer(M.input):p&&p.then(j=>j?.rebindComposer(M.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&x();let P=[],F=new Map;for(let T of n){if(!T.showButton)continue;let M=Lp({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(U=>U?.openMenu(T.trigger))}});P.push(M),F.set(T.trigger,M.button)}let k=(T,M,U)=>{let j=F.get(M);j&&(j.setAttribute("aria-expanded",T?"true":"false"),T?j.setAttribute("aria-controls",U):j.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:a,handleInput:T=>{if(l){l.handleInput();return}if(!Ld(T))return;let M=d,U=M.selectionStart??0;kd(M.value,U,n)&&v().then(j=>j?.handleInput())},handleKeydown:T=>{if(l?.isMenuOpen())return l.handleKeydown(T);if(T.key==="Backspace"&&l?.hasMentions()&&!g){let M=d,U=M.selectionStart===0&&M.selectionEnd===0;if((M.value.length===0||U)&&l.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(l??await v())?.dispatchInlineCommand(T)??null:null,clear:()=>l?.clear(),prefetch:()=>{fl().catch(()=>{})},onComposerSwap:T=>{w=T,g&&T(g.next,g.prev)},destroy:()=>{l?.destroy(),u?.();for(let T of P)T.wrapper.remove();a.remove()}}}var Rp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function hs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Rp(s)&&Rp(r)?n[o]=hs(s,r):n[o]=r}return n}var jn="min(440px, calc(100vw - 24px))",Hp="440px",Xm={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:jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Xm,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 Wp(e,t){if(!(!e&&!t))return e?t?hs(e,t):e:t}function Ha(e){return e?{...rt,...e,theme:Wp(rt.theme,e.theme),darkTheme:Wp(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=rt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=rt.features?.streamAnimation,p=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},x=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...x!==void 0?{askUserQuestion:x}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var Ba="16px",Da="transparent",Jm={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"}},Ym={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"}},Zm={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:jn,maxWidth:Hp,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ba,canvasBackground:Da},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 Xt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Xt(e,o):o}function Bp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Xt(e,a);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 a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eh(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 Dp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Dp(s,r):n[o]=r}return n}function th(e,t){return t?Dp(e,t):e}function fr(e,t={}){let n={palette:Jm,semantic:Ym,components:Zm},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:th(n.components,e?.components)};if(t.validate!==!1){let r=eh(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Fp(e){let t=Bp(e),n={};for(let[A,V]of Object.entries(t)){let K=A.replace(/\./g,"-");n[`--persona-${K}`]=V.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"]??Ba,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Da,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 s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let g=d?.artifact;if(g?.toolbar){let A=g.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Xt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(g?.tab){let A=g.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(g?.pane){let A=g.pane;if(A.toolbarBackground){let V=Xt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=V}}if(g?.card){let A=g.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(g?.inline){let A=g.inline;A.background&&(n["--persona-artifact-inline-bg"]=Xt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Xt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Xt(e,v.background)??v.background));let x=n["--persona-surface"],P=n["--persona-container"],F=n["--persona-palette-colors-gray-100"]??"#f3f4f6",k=n["--persona-palette-colors-gray-200"]??"#e5e7eb",T=n["--persona-palette-colors-gray-300"]??"#d1d5db",M=!P||P===x,U=M?F:P,j=M?k:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??U,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??j,M&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??T),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??U,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??U,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??U,n}var nh={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"}}},Np=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},gl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",oh=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":gl()},Op=e=>oh(e),rh=e=>fr(e),sh=e=>fr({...e,palette:{...e?.palette,colors:{...nh.colors,...e?.palette?.colors}}},{validate:!1}),gr=e=>{let t=Op(e),n=Np(e?.theme),o=Np(e?.darkTheme);return t==="dark"?sh(hs(n??{},o??{})):rh(n)},ah=e=>Fp(e),ys=(e,t)=>{let n=gr(t),o=ah(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Op(t))},Fa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(gl())});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(gl());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 Ln(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function _p(e){let t=Ln(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Na(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
25
25
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
26
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
27
|
-
`).length,
|
|
26
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function bs(e){let t=_p(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 fo(e){switch(bs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=_p(e.path);return t?t.toUpperCase():"File"}}}function $p(e){let t=e.markdown??"";return e.file?{filename:Ln(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Na(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var ml="http://www.w3.org/2000/svg";function Up(e){let t=document.createElementNS(ml,"svg");t.setAttribute("class",On("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(ml,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(ml,"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 go=(e,t,n)=>{let o=n;for(let r of t){let s=y("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function zp(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)),go(e,t,0)}var hl="persona-artifact-status-label",jp="persona-artifact-status-detail",Vp="data-artifact-status-label",yl=new Map,qp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function mr(e){e&&yl.delete(e)}function ih(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?fo(t):e.artifactType==="component"?"Component":"Document"}function hr(e,t,n){let o=ih(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,l=yl.get(a);e.status!=="complete"&&l===void 0&&(l=qp(),yl.set(a,l));let p=l===void 0?0:Math.max(0,qp()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
|
|
27
|
+
`).length,g=e.artifactType==="markdown"?e.file:void 0,v={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:u,lines:w,elapsedMs:p,content:()=>d?"":c,surface:n};try{let x=s(v);return typeof x=="string"?{label:x}:x&&typeof x=="object"&&typeof x.label=="string"?{label:x.label,detail:typeof x.detail=="string"?x.detail:void 0}:{label:r}}catch{return{label:r}}}function lh(e){e.className=hl,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 Do(e,t,n){let o=e.querySelector(`:scope > .${hl}`);o||(o=y("span",hl),e.appendChild(o)),o.getAttribute(Vp)!==t.label&&(lh(o),zp(o,t.label,n),o.setAttribute(Vp,t.label));let r=e.querySelector(`:scope > .${jp}`),s=t.detail;s?(r||(r=y("span",jp),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var ch={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"},dh=15e4,Oa={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 ph(e,t){let n=(e||"").trim().toLowerCase();if(n&&Oa[n])return Oa[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Oa[r])return Oa[r]}}return null}function _a(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!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){s(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var uh=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"]),fh=[{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=>uh.has(e)?"keyword":"plain"}];function Kp(e){return _a(e,fh)}var gh=[{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 mh(e){let t=_a(e,gh);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 hh=[{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 Gp(e){let t=_a(e,hh),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 a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let l=t[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var yh=[{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 bh(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),l=a===-1?o:a+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),l=a===-1?o:a+1,p=e.slice(r,l);for(let c of _a(p,yh))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=w?r+w.index:o,v=e.slice(r,g),x=c==="script"?Kp(v):Gp(v);for(let P of x)t.push(P);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function vh(e,t){switch(t){case"html":return bh(e);case"css":return Gp(e);case"js":return Kp(e);case"json":return mh(e)}}function wh(e){let t=Md(),n=y("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=ch[r];if(a){let l=y("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
28
28
|
`);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
29
|
-
`)),n=h("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Ip(e,t,n){let o=e.length<=$m?zm(t,n):null,r=o?Xm(e,o):[{type:"plain",value:e}];return Jm(r)}function fr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ea)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let R=document.createElement("hr");a.appendChild(R)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let R=ie(f.icon,16,"currentColor",1.5);R&&v.appendChild(R)}let C=document.createElement("span");C.textContent=f.label,v.appendChild(C),v.addEventListener("click",R=>{R.stopPropagation(),c(),n(f.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Pt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ie(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Wo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=h("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ie(t,s??14,"currentColor",2);w&&c.appendChild(w)}let u=h("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function Ba(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=h("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=Pt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=h("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Rp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=e,d=h("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=h("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ie(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=fr({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",f=>{f.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let f=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var Da="persona-artifact-custom-action-btn";function gr(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 "+Da+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Da+(n?" persona-artifact-doc-icon-btn":"");o=h("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=h("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Wo({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-copy-btn":"")}):o=Pt({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function ps(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 Wp(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?Mn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?lo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);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 w=document.createElement("div");w.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 v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,R={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},B=ur(R,C,"card");Ro(v,B,C)}else s&&pr(s),v.textContent=d;if(w.append(f,v),c.append(u,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of C)try{if(L.visible===void 0||L.visible(B)){let E=gr(L);E.setAttribute("data-artifact-custom-action",L.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let R=Wo({label:"Download",className:"persona-flex-shrink-0"});R.title=`Download ${r}`,R.setAttribute("data-download-artifact",s),c.append(R)}return c}var Fa=(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:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Wp(e,t)});if(l)return l}return Wp(e,t)};var po=new WeakMap;function fl(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 s=po.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Np(e){return po.has(e)}function Ym(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 a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=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:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Hp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Mn(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 Zm(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 Bp=180,eh=240,th=.8,nh=300,oh=500,rh="cubic-bezier(0.2, 0, 0, 1)",Dp=240,sh=.35;function ah(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Bp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(oh,Math.max(nh,eh+d*th))),u=Math.round(c*sh),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:Dp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:rh});e.style.height=`${p}px`;let C=!1,R=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(R),window.setTimeout(R,Math.max(c,u+Dp)+120)},Bp)}function ih(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 us="--persona-artifact-inline-body-height";function lh(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function Fp(e,t){let n=Ym(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=ih(o),p=o?.inlineActions??[],d=lh(o),c=d.completeDisplay==="card",u=null,w=n,f=h("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 v=ee=>Fa(Zm(ee),t),C=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(us),f.replaceChildren(v(ee)),po.set(f,le=>{f.replaceChildren(v(le))})};if(c&&n.status==="complete")return C(n),f;let R=Na(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(R.el);let L=ee=>{let le=ee.status!=="complete",Y=le?d.streamingHeight:d.completeHeight,pe=typeof Y=="number";pe?f.style.setProperty(us,`${Y}px`):f.style.removeProperty(us);let xe=!!R.el.querySelector(".persona-code-pre"),ye=!!R.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",xe),B.classList.toggle("persona-artifact-inline-body--sized",pe&&ye),B.classList.toggle("persona-artifact-inline-body--cap",!le&&!ye&&typeof d.completeHeight=="number")},E=n.status,M=(ee,le)=>{E!=="complete"&&ee.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(us,`${d.completeHeight}px`):f.style.removeProperty(us),_p(B,le?.suppressTransition?"none":d.transition,ee.id,()=>{R.update(ee),L(ee)})):R.update(ee),L(ee),E=ee.status};L(n);let _=d.overflow==="clip"&&a&&!!n.id;if(_&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Hp(n).title} in panel`)),!r)return f.appendChild(B),po.set(f,M),f;let G=h("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=h("div","persona-artifact-inline-chrome-lead"),j=h("span","persona-flex persona-items-center persona-flex-shrink-0"),U=ie("file-text",16,"currentColor",2);U&&j.appendChild(U);let oe=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),F=h("span","persona-artifact-inline-type");x.append(j,oe,F);let $=h("div","persona-artifact-inline-chrome-actions"),X=h("span","persona-flex persona-items-center persona-gap-1"),me=()=>u??d.viewMode,he=l?Ba({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:me(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let le=ee==="source"?"source":"rendered";le!==me()&&(u=le,R.update(w),L(w))}}):null,Ae=s?Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ae&&n.id&&Ae.setAttribute("data-copy-artifact",n.id);let Z=a?Pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(X),he&&$.appendChild(he.element),Ae&&$.appendChild(Ae),Z&&$.appendChild(Z),G.append(x,$),f.append(G,B);let ce=ee=>{let{title:le,typeLabel:Y}=Hp(ee);oe.textContent=le,oe.title=le,_&&B.setAttribute("aria-label",`Open ${le} in panel`);let pe=ee.status!=="complete";if(pe){F.classList.contains("persona-artifact-inline-status")||(F.className="persona-artifact-inline-status",F.removeAttribute("data-preserve-animation"),F.replaceChildren());let xe=ur(ee,o,"inline-chrome");Ro(F,xe,o)}else pr(ee.id),F.className="persona-artifact-inline-type",F.removeAttribute("data-preserve-animation"),F.replaceChildren(),F.textContent=Y;if(Ae&&Ae.classList.toggle("persona-hidden",pe),he){let xe=ee.artifactType==="markdown"?ee.file:void 0,ye=!1;if(!pe&&xe&&d.viewMode!=="source"){let ve=ds(xe);ve==="markdown"?ye=!0:(ve==="html"||ve==="svg")&&(ye=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ye),he.setSelected(me())}if(X.replaceChildren(),!pe&&p.length>0){let xe=ps(ee);if(xe)for(let ye of p)try{if(ye.visible===void 0||ye.visible(xe)){let ve=gr(ye,{documentChrome:!0});ve.setAttribute("data-artifact-custom-action",ye.id),ve.classList.add("persona-flex-shrink-0"),X.appendChild(ve)}}catch{}}};return ce(n),po.set(f,(ee,le)=>{if(c&&E!=="complete"&&ee.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let pe=ee,xe=!1,ye=ve=>{pe=ve,xe=!0};po.set(f,ye),ah(f,Y,{swap:()=>{C(pe),xe=!1,po.set(f,ye)},onSettled:()=>{xe?C(pe):po.set(f,ve=>{f.replaceChildren(v(ve))})}});return}(ee.status!=="complete"||ee.id!==w.id)&&(u=null),w=ee,M(ee,le),ce(ee)}),f}var Op=(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:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Fp(e,t)});if(l)return l}return Fp(e,t)};var gl=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)})}},zn=new gl;zn.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});zn.register("PersonaArtifactInline",Op,{bubbleChrome:!1});function fs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ra(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var ml=!1;function ch(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function _p(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||ml||s){o();return}ml=!0;let a=ch(n);e.style.setProperty("view-transition-name",a);let l=()=>{ml=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var dh="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",ph="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function uh(e){let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=h("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 fh(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 gh=220;function mh(){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 hh(e){return`
|
|
30
|
-
<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 yh(e,t,n){let o=h("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=h("div","persona-artifact-frame-loading-indicator");r.appendChild(Sp());let s=null;return n.label!==!1&&(s=h("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function bh(e,t,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},u=(E,M)=>{let _=setTimeout(()=>{d.delete(_),E()},M);d.add(_)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let E=yh(r,s,o);a=E.el,e.appendChild(a),l=Date.now(),o.label!==!1&&u(E.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,gh))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",L)},R=()=>{if(p||(p=!0,C(),c(),!a))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?u(v,E):v()};function B(E){if(n===null)return;let M=E.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||E.source===t.contentWindow&&R()}function L(){let E=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};E(()=>E(()=>R()))}return u(f,o.delayMs),u(R,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",L),()=>{p=!0,c(),C(),w()}}function Na(e,t){let{config:n}=t,o=t.registry??zn,r=t.bodyLayout,s=n.markdown?ca(n.markdown):null,a=da(n.sanitize),l=e,p=!1,d=Z=>{let ce=Fn()!==null;s&&!ce&&!p&&(p=!0,la(()=>Ae(l)));let ee=s?s(Z):oo(Z);return s&&ce&&a?a(ee):ee},c=h("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},C=null,R=null,B=null,L=!1,E=()=>{C=null,R=null,B=null,L=!1},M=null,_=null,G=()=>{M=null,_=null},x=40,j=0,U=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),oe=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=x,F=Z=>{if(!r)return;let ce=Z.scrollHeight-Z.clientHeight>1,ee=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ce&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ce&&ee>1)},$=Z=>{j||(j=U(()=>{j=0,Z.scrollTop=Z.scrollHeight,F(Z)}))},X=(Z,ce,ee,le)=>{let Y=!!r,pe=ee.id+"|"+(Y?"w":"p");if(!C||B!==pe||C.parentElement!==c){v(),G(),c.replaceChildren();let ve=h("pre",dh+" persona-code-pre"),je=h("code","persona-code");if(ve.appendChild(je),Y){let Me=h("div","persona-artifact-source-window");if(Me.appendChild(ve),c.appendChild(Me),!(r?.overflow==="clip")&&typeof Me.addEventListener=="function"){let Qe=()=>Me.scrollHeight-Me.clientHeight>1;Me.addEventListener("scroll",()=>{oe(Me)&&(L=!1),F(Me)},{passive:!0}),Me.addEventListener("wheel",Ve=>{Qe()&&Ve.deltaY<0&&(L=!0)},{passive:!0}),Me.addEventListener("touchmove",()=>{Qe()&&(L=!0)},{passive:!0})}C=Me}else c.appendChild(ve),C=ve;R=je,B=pe}let xe=Y?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",le),xe.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let ye=xe?oe(xe):!0;if(R.replaceChildren(Ip(Z,ce?.language,ce?.path)),xe){let ve=ee.status!=="complete";le&&ve&&r?.followOutput&&!L&&ye?$(xe):ve||(L=!1),F(xe)}},me=Z=>{v(),E(),G(),c.replaceChildren();let ce=h("div",ph);ce.innerHTML=d(Z),c.appendChild(ce)},he=Z=>{let ce=Z.id,ee=n.features?.artifacts,le=ur(Z,ee,"status-body");if(M&&_===ce&&M.parentElement===c){let xe=M.querySelector(".persona-artifact-status-view-text");xe&&Ro(xe,le,ee);return}v(),E(),c.replaceChildren();let Y=h("div","persona-artifact-status-view"),pe=h("div","persona-artifact-status-view-text");Ro(pe,le,ee),Y.appendChild(pe),c.appendChild(Y),M=Y,_=ce},Ae=Z=>{l=Z;let ce=t.resolveViewMode?.(Z)??r?.viewMode??"rendered",ee=Z.artifactType==="markdown"?Z.file:void 0,le=Z.status!=="complete";le||pr(Z.id);let Y=le?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&le){he(Z);return}if(ee){let ye=Ra(Z.markdown??""),ve=ds(ee),je=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ce==="rendered"&&je&&(ve==="html"||ve==="svg")){let De=Z.id+"\0"+ye;if(u&&w===De&&u.parentElement===c)return;E(),G(),v(),c.replaceChildren();let Qe=n.features?.artifacts?.filePreview,Ve=Qe?.iframeSandbox??"allow-scripts";!Qe?.dangerouslyAllowSameOrigin&&Ve.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."),Ve=Ve.split(/\s+/).filter(It=>It&&It!=="allow-same-origin").join(" "));let Te=fh(Qe?.loading),Le=h("div","persona-artifact-frame"),Xe=h("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ve),Xe.setAttribute("data-artifact-id",Z.id);let Ht=null;Te.enabled&&Te.injectReadySignal?(Ht=mh(),Xe.srcdoc=ye+hh(Ht)):Xe.srcdoc=ye,Le.appendChild(Xe),c.appendChild(Le),Te.enabled&&(f=bh(Le,Xe,Ht,Te,Z.id,n)),u=Le,w=De;return}if(v(),!le&&ve==="markdown"&&ce==="rendered"){me(ye);return}X(ye,{language:ee.language,path:ee.path},Z,pe);return}if(Z.artifactType==="markdown"){if(ce==="source"){v(),X(Z.markdown??"",void 0,Z,pe);return}me(Z.markdown??"");return}v(),E(),G(),c.replaceChildren();let xe=Z.component?o.get(Z.component):void 0;if(xe){let ve={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let je=xe(Z.props??{},ve);if(je){c.appendChild(je);return}}catch{}}c.appendChild(uh(Z))};return Ae(e),{el:c,update(Z){Ae(Z)}}}import{Idiomorph as vh}from"idiomorph";var Oa=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;vh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){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 s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var $p=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hl={index:-1,draft:""};function zp(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function jp(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 Up(){return new Map}function Vp(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function qp(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Kp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Gp(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 _a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function En(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return En(e)-e.scrollTop<=t}function $a(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function za(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 Qp(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Xp(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 Jp(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var gs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wh=["pre","code","a","script","style"],ja=e=>({type:e?.type??gs.type,placeholder:e?.placeholder??gs.placeholder,speed:e?.speed??gs.speed,duration:e?.duration??gs.duration,buffer:e?.buffer??gs.buffer}),xh=[{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"}],Zp=new Map;for(let e of xh)Zp.set(e.name,e);var mr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zp.get(e)??null,Ua=(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 s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
-
`);return s<0?"":e.slice(0,s)}return e},Ch=(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},Ah=(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},yl=/\s/,Sh=(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},Th=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(yl.test(s[l])){let p=l;for(;p<s.length&&yl.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!yl.test(s[d]);)p.appendChild(Ch(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,e)},Mh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Ah(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},ms=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??wh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Sh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Th:Mh;for(let u of l)c(u,n,d);return r.innerHTML},Va=(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},hs=(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},Yp=new WeakMap,Eh=(e,t)=>{if(!e.styles)return;let n=Yp.get(t);if(n||(n=new Set,Yp.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))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)},bl=new WeakMap,kh=(e,t)=>{if(!e.onAttach)return;let n=bl.get(t);if(n||(n=new Map,bl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},eu=e=>{let t=bl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},qa=(e,t)=>{Eh(e,t),kh(e,t)};function vl(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var ys=0,fo=null;function wl(e=document){if(ys++,ys===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;fo={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,ys=Math.max(0,ys-1),ys===0&&fo)){let n=e.body,o=e.defaultView??window;n.style.overflow=fo.originalOverflow,n.style.position=fo.originalPosition,n.style.top=fo.originalTop,n.style.width=fo.originalWidth,o.scrollTo(0,fo.scrollY),fo=null}}}var bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Dt=e=>(e?.launcher?.mountMode??"floating")==="docked",vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",gn=e=>{let t=e?.launcher?.dock;return{side:t?.side??bs.side,width:t?.width??bs.width,animate:t?.animate??bs.animate,reveal:t?.reveal??bs.reveal,maxHeight:t?.maxHeight??bs.maxHeight}};var Cn={"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 Lh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ka=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lh,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",p=h("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Be("button",{className:Dn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Qt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ie(u,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),Ot({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},Ph="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{let{wrapperClassName:n=Ph,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",R=a.tooltipText??"Clear chat",B=a.showTooltip??!0,L=h("div",n),E=!!(u||w),M=Be("button",{className:Dn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":R},style:{height:l,width:l,color:d||Qt.actionIconColor,backgroundColor:c||void 0,border:E?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),_=ie(p,r,"currentColor",1);return _&&(_.style.display="block",M.appendChild(_)),L.appendChild(M),Ot({anchor:M,trigger:L,text:()=>M.getAttribute("aria-label")??R,enabled:B}),{button:M,wrapper:L}};var Qt={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))"},Ho=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??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Be("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,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 _=parseFloat(s)||24,G=ie(p,_*.6,"currentColor",1);G?d.replaceChildren(G):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=h("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,d.replaceChildren(_)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=h("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:Qt.titleColor}}),w=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},v=f.enabled??!0,C=f.placement??"inline",R=null,B=null;if(v){let G=Ga(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});R=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="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:E,wrapper:M}=Ka(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:E,closeButtonWrapper:M,clearChatButton:R,clearChatButtonWrapper:B}},ws=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Ih=e=>{let t=Ho({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 Rh(e,t,n){if(t?.length)for(let o of t){let r=h("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 s=ie(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let a=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Wh=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Rp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Qt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Qt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Rh(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let E=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||E()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),E())})}let L=r?.titleRowHover;L&&(d.style.borderRadius=L.borderRadius??"10px",d.style.padding=L.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=L.background??"",d.style.borderColor=L.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=h("div",""),f=h("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=a.closeButtonColor||Qt.actionIconColor;let v=a.closeButtonIconName??"x",C=ie(v,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let R=h("div");R.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:R,headerTitle:c,headerSubtitle:B,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},tu={default:Ih,minimal:Wh},Hh=e=>tu[e]??tu.default,Qa=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=h("div");l.style.display="none";let p=h("span"),d=h("span"),c=h("button");c.style.display="none";let u=h("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Hh(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&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Xa=e=>{let t=h("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 a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}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:s}},Ja=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",w=t.backgroundColor,f=t.textColor,v=h("div","persona-send-button-wrapper"),C=Be("button",{className:Dn("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&&!w&&"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&&w||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}}),R=null,B=null;if(n){let M=parseFloat(u)||24,_=f?.trim()||"currentColor";r?(R=ie(r,M,_,2),R?C.appendChild(R):C.textContent=o):C.textContent=o,B=ie(s,M,_,2)}else C.textContent=p;C.setAttribute("aria-label",a),v.appendChild(C),Ot({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let L="send";return{button:C,wrapper:v,setMode:M=>{if(M===L)return;L=M;let _=M==="stop"?l:a;if(C.setAttribute("aria-label",_),n){if(R&&B){let G=M==="stop"?B:R;C.replaceChildren(G)}}else C.textContent=M==="stop"?d:p}}},Ya=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 a=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,w=h("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:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ie(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let R=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return Ot({anchor:f,trigger:w,text:()=>f.getAttribute("aria-label")??R,enabled:B}),{button:f,wrapper:w}},Za=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=h("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=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??_n).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=h("div","persona-send-button-wrapper"),c=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ie(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},ei=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=h("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 s=t.idleText??"Online";if(t.idleLink){let a=h("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ti=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ni=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=ti(),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:s,attachAutoResize:a}=Xa(t);a();let l=Ja(t),p=Ya(t),d=Za(t),c=ei(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);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":""}}),w=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:f,setSendButtonMode:l.setMode}};var nu=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=h("span","persona-pill-peek__icon"),n=ie("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=ie("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ou=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ti(),r=ei(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Xa(t);s.style.maxHeight="100px",a();let l=Ja(t),p=Ya(t),d=Za(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Be("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var ru=e=>{let t=e?.launcher?.enabled??!0,n=Dt(e);if(vs(e)){let c=e?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Vt);let w=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Vt),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Cn[r.position]?Cn[r.position]:Cn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??$n;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},Bh=(e,t)=>{let n=h("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}=Ka(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 s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let M=Ga(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=M.button,l=M.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"}}),d=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"}});d.style.setProperty("scrollbar-gutter","stable");let c=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."}),w=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)"}},c,u),f=h("div","persona-flex persona-flex-col persona-gap-3"),v=e?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let R=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"}}),B=ou({config:e}),{root:L,textNode:E}=nu();return n.append(p,r,d,R),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:p,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:L,peekTextNode:E}},su=(e,t=!0)=>{if(vs(e))return Bh(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,s=o?Qa(e,o,{showClose:t}):Ho({config:e,showClose:t}),a=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"}});a.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."}),d=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Dt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=h("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=ni({config:e}),v=e?.layout?.showFooter!==!1;r?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let C=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 v||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,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:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.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 xl=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
|
|
29
|
+
`)),n=y("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Qp(e,t,n){let o=e.length<=dh?ph(t,n):null,r=o?vh(e,o):[{type:"plain",value:e}];return wh(r)}function yr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Wa)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let P=ae(g.icon,16,"currentColor",1.5);P&&v.appendChild(P)}let x=document.createElement("span");x.textContent=g.label,v.appendChild(x),v.addEventListener("click",P=>{P.stopPropagation(),c(),n(g.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Pt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,p=y("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Fo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=y("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ae(t,s??14,"currentColor",2);w&&c.appendChild(w)}let u=y("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,g]of Object.entries(p))c.setAttribute(w,g);return c}function $a(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=y("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=Pt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=y("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Xp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=e,d=y("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=y("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ae(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=yr({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",g=>{g.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let g=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var Ua="persona-artifact-custom-action-btn";function br(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 "+Ua+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+Ua+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Fo({icon:e.icon,label:e.label,className:Ua+(n?" persona-artifact-doc-copy-btn":"")}):o=Pt({icon:e.icon,label:e.label,className:Ua+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function vs(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 Jp(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?Ln(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?fo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);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 w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let x=t?.config?.features?.artifacts,P={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},F=hr(P,x,"card");Do(v,F,x)}else s&&mr(s),v.textContent=d;if(w.append(g,v),c.append(u,w),a==="complete"){let x=t?.config?.features?.artifacts?.cardActions;if(x&&x.length>0){let F={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let k of x)try{if(k.visible===void 0||k.visible(F)){let T=br(k);T.setAttribute("data-artifact-custom-action",k.id),T.className=`${T.className} persona-flex-shrink-0`,c.append(T)}}catch{}}let P=Fo({label:"Download",className:"persona-flex-shrink-0"});P.title=`Download ${r}`,P.setAttribute("data-download-artifact",s),c.append(P)}return c}var za=(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:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Jp(e,t)});if(l)return l}return Jp(e,t)};var mo=new WeakMap;function bl(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 s=mo.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function nu(e){return mo.has(e)}function xh(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 a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=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:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Yp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Ln(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?fo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ch(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 Zp=180,Ah=240,Sh=.8,Th=300,Mh=500,Eh="cubic-bezier(0.2, 0, 0, 1)",eu=240,kh=.35;function Lh(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Zp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let F of a)F.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(Mh,Math.max(Th,Ah+d*Sh))),u=Math.round(c*kh),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=w?w.animate([{opacity:0},{opacity:1}],{duration:eu,delay:u,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Eh});e.style.height=`${p}px`;let x=!1,P=()=>{x||(x=!0,l(),r())};Promise.allSettled([v.finished,g?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+eu)+120)},Zp)}function Ph(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 ws="--persona-artifact-inline-body-height";function Ih(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:g}}function tu(e,t){let n=xh(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Ph(o),p=o?.inlineActions??[],d=Ih(o),c=d.completeDisplay==="card",u=null,w=n,g=y("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let v=te=>za(Ch(te),t),x=te=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(ws),g.replaceChildren(v(te)),mo.set(g,ie=>{g.replaceChildren(v(ie))})};if(c&&n.status==="complete")return x(n),g;let P=ja(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),F=y("div","persona-artifact-inline-body");F.appendChild(P.el);let k=te=>{let ie=te.status!=="complete",J=ie?d.streamingHeight:d.completeHeight,fe=typeof J=="number";fe?g.style.setProperty(ws,`${J}px`):g.style.removeProperty(ws);let Ce=!!P.el.querySelector(".persona-code-pre"),ye=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");F.classList.toggle("persona-artifact-content-flush",Ce),F.classList.toggle("persona-artifact-inline-body--sized",fe&&ye),F.classList.toggle("persona-artifact-inline-body--cap",!ie&&!ye&&typeof d.completeHeight=="number")},T=n.status,M=(te,ie)=>{T!=="complete"&&te.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(ws,`${d.completeHeight}px`):g.style.removeProperty(ws),ru(F,ie?.suppressTransition?"none":d.transition,te.id,()=>{P.update(te),k(te)})):P.update(te),k(te),T=te.status};k(n);let U=d.overflow==="clip"&&a&&!!n.id;if(U&&(F.setAttribute("data-expand-artifact-inline",n.id),F.setAttribute("role","button"),F.setAttribute("tabindex","0"),F.classList.add("persona-cursor-pointer"),F.setAttribute("aria-label",`Open ${Yp(n).title} in panel`)),!r)return g.appendChild(F),mo.set(g,M),g;let j=y("div","persona-artifact-inline-chrome");j.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let A=y("div","persona-artifact-inline-chrome-lead"),V=y("span","persona-flex persona-items-center persona-flex-shrink-0"),K=ae("file-text",16,"currentColor",2);K&&V.appendChild(K);let ne=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=y("span","persona-artifact-inline-type");A.append(V,ne,D);let _=y("div","persona-artifact-inline-chrome-actions"),Y=y("span","persona-flex persona-items-center persona-gap-1"),ge=()=>u??d.viewMode,he=l?$a({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:ge(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:te=>{let ie=te==="source"?"source":"rendered";ie!==ge()&&(u=ie,P.update(w),k(w))}}):null,ce=s?Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ce&&n.id&&ce.setAttribute("data-copy-artifact",n.id);let Z=a?Pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),_.appendChild(Y),he&&_.appendChild(he.element),ce&&_.appendChild(ce),Z&&_.appendChild(Z),j.append(A,_),g.append(j,F);let de=te=>{let{title:ie,typeLabel:J}=Yp(te);ne.textContent=ie,ne.title=ie,U&&F.setAttribute("aria-label",`Open ${ie} in panel`);let fe=te.status!=="complete";if(fe){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let Ce=hr(te,o,"inline-chrome");Do(D,Ce,o)}else mr(te.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=J;if(ce&&ce.classList.toggle("persona-hidden",fe),he){let Ce=te.artifactType==="markdown"?te.file:void 0,ye=!1;if(!fe&&Ce&&d.viewMode!=="source"){let xe=bs(Ce);xe==="markdown"?ye=!0:(xe==="html"||xe==="svg")&&(ye=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ye),he.setSelected(ge())}if(Y.replaceChildren(),!fe&&p.length>0){let Ce=vs(te);if(Ce)for(let ye of p)try{if(ye.visible===void 0||ye.visible(Ce)){let xe=br(ye,{documentChrome:!0});xe.setAttribute("data-artifact-custom-action",ye.id),xe.classList.add("persona-flex-shrink-0"),Y.appendChild(xe)}}catch{}}};return de(n),mo.set(g,(te,ie)=>{if(c&&T!=="complete"&&te.status==="complete"){let J=g.isConnected?g.getBoundingClientRect().height:0;T="complete";let fe=te,Ce=!1,ye=xe=>{fe=xe,Ce=!0};mo.set(g,ye),Lh(g,J,{swap:()=>{x(fe),Ce=!1,mo.set(g,ye)},onSettled:()=>{Ce?x(fe):mo.set(g,xe=>{g.replaceChildren(v(xe))})}});return}(te.status!=="complete"||te.id!==w.id)&&(u=null),w=te,M(te,ie),de(te)}),g}var ou=(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:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>tu(e,t)});if(l)return l}return tu(e,t)};var vl=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)})}},Vn=new vl;Vn.register("PersonaArtifactCard",za,{bubbleChrome:!1});Vn.register("PersonaArtifactInline",ou,{bubbleChrome:!1});function xs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Na(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var wl=!1;function Rh(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ru(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||wl||s){o();return}wl=!0;let a=Rh(n);e.style.setProperty("view-transition-name",a);let l=()=>{wl=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Wh="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Hh="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Bh(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Dh(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 Fh=220;function Nh(){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 Oh(e){return`
|
|
30
|
+
<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 _h(e,t,n){let o=y("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=y("div","persona-artifact-frame-loading-indicator");r.appendChild(Up());let s=null;return n.label!==!1&&(s=y("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function $h(e,t,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},u=(T,M)=>{let U=setTimeout(()=>{d.delete(U),T()},M);d.add(U)},w=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let T=_h(r,s,o);a=T.el,e.appendChild(a),l=Date.now(),o.label!==!1&&u(T.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,Fh))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",F):t.removeEventListener("load",k)},P=()=>{if(p||(p=!0,x(),c(),!a))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-l));T>0?u(v,T):v()};function F(T){if(n===null)return;let M=T.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||T.source===t.contentWindow&&P()}function k(){let T=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};T(()=>T(()=>P()))}return u(g,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",F):t.addEventListener("load",k),()=>{p=!0,c(),x(),w()}}function ja(e,t){let{config:n}=t,o=t.registry??Vn,r=t.bodyLayout,s=n.markdown?ma(n.markdown):null,a=ha(n.sanitize),l=e,p=!1,d=Z=>{let de=_n()!==null;s&&!de&&!p&&(p=!0,ga(()=>ce(l)));let te=s?s(Z):ao(Z);return s&&de&&a?a(te):te},c=y("div","persona-artifact-preview-body"),u=null,w=null,g=null,v=()=>{g&&(g(),g=null),u=null,w=null},x=null,P=null,F=null,k=!1,T=()=>{x=null,P=null,F=null,k=!1},M=null,U=null,j=()=>{M=null,U=null},A=40,V=0,K=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),ne=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=A,D=Z=>{if(!r)return;let de=Z.scrollHeight-Z.clientHeight>1,te=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&de&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&de&&te>1)},_=Z=>{V||(V=K(()=>{V=0,Z.scrollTop=Z.scrollHeight,D(Z)}))},Y=(Z,de,te,ie)=>{let J=!!r,fe=te.id+"|"+(J?"w":"p");if(!x||F!==fe||x.parentElement!==c){v(),j(),c.replaceChildren();let xe=y("pre",Wh+" persona-code-pre"),ve=y("code","persona-code");if(xe.appendChild(ve),J){let Ae=y("div","persona-artifact-source-window");if(Ae.appendChild(xe),c.appendChild(Ae),!(r?.overflow==="clip")&&typeof Ae.addEventListener=="function"){let qe=()=>Ae.scrollHeight-Ae.clientHeight>1;Ae.addEventListener("scroll",()=>{ne(Ae)&&(k=!1),D(Ae)},{passive:!0}),Ae.addEventListener("wheel",ze=>{qe()&&ze.deltaY<0&&(k=!0)},{passive:!0}),Ae.addEventListener("touchmove",()=>{qe()&&(k=!0)},{passive:!0})}x=Ae}else c.appendChild(xe),x=xe;P=ve,F=fe}let Ce=J?x:null;Ce&&(Ce.classList.toggle("persona-artifact-source-window--fixed",ie),Ce.classList.toggle("persona-artifact-source-window--clip",ie&&r?.overflow==="clip"));let ye=Ce?ne(Ce):!0;if(P.replaceChildren(Qp(Z,de?.language,de?.path)),Ce){let xe=te.status!=="complete";ie&&xe&&r?.followOutput&&!k&&ye?_(Ce):xe||(k=!1),D(Ce)}},ge=Z=>{v(),T(),j(),c.replaceChildren();let de=y("div",Hh);de.innerHTML=d(Z),c.appendChild(de)},he=Z=>{let de=Z.id,te=n.features?.artifacts,ie=hr(Z,te,"status-body");if(M&&U===de&&M.parentElement===c){let Ce=M.querySelector(".persona-artifact-status-view-text");Ce&&Do(Ce,ie,te);return}v(),T(),c.replaceChildren();let J=y("div","persona-artifact-status-view"),fe=y("div","persona-artifact-status-view-text");Do(fe,ie,te),J.appendChild(fe),c.appendChild(J),M=J,U=de},ce=Z=>{l=Z;let de=t.resolveViewMode?.(Z)??r?.viewMode??"rendered",te=Z.artifactType==="markdown"?Z.file:void 0,ie=Z.status!=="complete";ie||mr(Z.id);let J=ie?r?.streamingHeight:r?.completeHeight,fe=!!r&&typeof J=="number";if(r?.streamingView==="status"&&ie){he(Z);return}if(te){let ye=Na(Z.markdown??""),xe=bs(te),ve=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ie&&de==="rendered"&&ve&&(xe==="html"||xe==="svg")){let Te=Z.id+"\0"+ye;if(u&&w===Te&&u.parentElement===c)return;T(),j(),v(),c.replaceChildren();let qe=n.features?.artifacts?.filePreview,ze=qe?.iframeSandbox??"allow-scripts";!qe?.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(It=>It&&It!=="allow-same-origin").join(" "));let Me=Dh(qe?.loading),Pe=y("div","persona-artifact-frame"),Ke=y("iframe","persona-artifact-iframe");Ke.setAttribute("sandbox",ze),Ke.setAttribute("data-artifact-id",Z.id);let Wt=null;Me.enabled&&Me.injectReadySignal?(Wt=Nh(),Ke.srcdoc=ye+Oh(Wt)):Ke.srcdoc=ye,Pe.appendChild(Ke),c.appendChild(Pe),Me.enabled&&(g=$h(Pe,Ke,Wt,Me,Z.id,n)),u=Pe,w=Te;return}if(v(),!ie&&xe==="markdown"&&de==="rendered"){ge(ye);return}Y(ye,{language:te.language,path:te.path},Z,fe);return}if(Z.artifactType==="markdown"){if(de==="source"){v(),Y(Z.markdown??"",void 0,Z,fe);return}ge(Z.markdown??"");return}v(),T(),j(),c.replaceChildren();let Ce=Z.component?o.get(Z.component):void 0;if(Ce){let xe={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ve=Ce(Z.props??{},xe);if(ve){c.appendChild(ve);return}}catch{}}c.appendChild(Bh(Z))};return ce(e),{el:c,update(Z){ce(Z)}}}import{Idiomorph as Uh}from"idiomorph";var Va=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Uh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){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 s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var su=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var xl={index:-1,draft:""};function au(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function iu(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 lu(){return new Map}function cu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function du(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function uu(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 qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Pn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ho(e,t){return Pn(e)-e.scrollTop<=t}function Ka(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ga(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 fu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gu(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 mu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},zh=["pre","code","a","script","style"],Qa=e=>({type:e?.type??Cs.type,placeholder:e?.placeholder??Cs.placeholder,speed:e?.speed??Cs.speed,duration:e?.duration??Cs.duration,buffer:e?.buffer??Cs.buffer}),jh=[{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"}],yu=new Map;for(let e of jh)yu.set(e.name,e);var vr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:yu.get(e)??null,Xa=(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 s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
+
`);return s<0?"":e.slice(0,s)}return e},Vh=(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},qh=(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},Cl=/\s/,Kh=(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},Gh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Cl.test(s[l])){let p=l;for(;p<s.length&&Cl.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!Cl.test(s[d]);)p.appendChild(Vh(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,e)},Qh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(qh(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},As=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??zh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Kh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Gh:Qh;for(let u of l)c(u,n,d);return r.innerHTML},Ja=(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},hu=new WeakMap,Xh=(e,t)=>{if(!e.styles)return;let n=hu.get(t);if(n||(n=new Set,hu.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))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)},Al=new WeakMap,Jh=(e,t)=>{if(!e.onAttach)return;let n=Al.get(t);if(n||(n=new Map,Al.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},bu=e=>{let t=Al.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ya=(e,t)=>{Xh(e,t),Jh(e,t)};function Sl(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Ts=0,yo=null;function Tl(e=document){if(Ts++,Ts===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;yo={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,Ts=Math.max(0,Ts-1),Ts===0&&yo)){let n=e.body,o=e.defaultView??window;n.style.overflow=yo.originalOverflow,n.style.position=yo.originalPosition,n.style.top=yo.originalTop,n.style.width=yo.originalWidth,o.scrollTo(0,yo.scrollY),yo=null}}}var Ms={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Dt=e=>(e?.launcher?.mountMode??"floating")==="docked",Es=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",hn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ms.side,width:t?.width??Ms.width,animate:t?.animate??Ms.animate,reveal:t?.reveal??Ms.reveal,maxHeight:t?.maxHeight??Ms.maxHeight}};var Ml=e=>e==="followUp"?"follow-up":e,Yh=(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"}},Zh=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'}},vu=new WeakSet,ey=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ty=e=>{ey()||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"})})},Za=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let u=getComputedStyle(e).direction==="rtl",w=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),g=4,v=w<=g,x=w>=c-g,P=u?!x:!v,F=u?!v:!x;e.toggleAttribute("data-scroll-left",P),e.toggleAttribute("data-scroll-right",F)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,u,w,g,v,x)=>{e.replaceChildren(),t.length=0,n.length=0;let P=x?.source??"config",F=x?.surface??(P==="config"?"starter":"followUp"),k=F==="followUp",T=x?.variant??"chip",M=x?.behavior??"send",U=x?.overflow??"wrap",j=x?.config??{},A=x?.plugins??[],V=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,K=k?"followUps":"starters";!vu.has(j)&&j.debug===!0&&T!=="chip"&&j.suggestions?.[K]?.overflow!==void 0&&(vu.add(j),console.info(`[persona] suggestions.${K}.overflow applies to the "chip" variant only; the "${T}" variant manages its own stacking.`));let ne=ce=>ce.map(Yh).filter(Z=>Z!==null).map(Z=>({...Z,behavior:Z.behavior??M})),D=ne(c??[]);A.forEach(ce=>{ce.transformSuggestions&&(D=ne(ce.transformSuggestions({suggestions:D.map(Z=>({...Z})),surface:F,source:P,config:j})))});let _=V===void 0?D:D.slice(0,V);if(!_.length){e.hidden=!0,o=null,s();return}if(!k&&(g??u.getMessages()).some(Z=>Z.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ml(F),e.dataset.variant=T,e.dataset.overflow=U;let Y=document.createDocumentFragment(),ge=u.isStreaming();_.forEach((ce,Z)=>{var Ce,ye,xe;let de=ce.behavior,te=()=>{if(u.isStreaming())return;let ve={suggestion:{...ce},surface:F,source:P,behavior:de},Ae=e.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:ve,bubbles:!0,composed:!0,cancelable:!0}));if(k&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:ce.prompt},bubbles:!0,composed:!0})),!!Ae){for(let Te of A)if(Te.onSuggestionSelect?.({suggestion:{...ce},surface:F,source:P,variant:T,config:j})===!1)return;if(de==="fill"){w.value=ce.prompt,w.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),w.focus();return}w.value="",u.sendMessage(ce.prompt)}},ie=()=>{let ve=y("button",`persona-suggestion persona-suggestion--${T}`);if(ve.type="button",ve.disabled=ge,ve.dataset.suggestionId=ce.id,ve.dataset.emphasis=ce.emphasis,ve.dataset.behavior=de,T==="chip"&&(v?.fontFamily&&(ve.style.fontFamily=Zh(v.fontFamily)),v?.fontWeight&&(ve.style.fontWeight=v.fontWeight),v?.paddingX&&(ve.style.paddingLeft=v.paddingX,ve.style.paddingRight=v.paddingX),v?.paddingY&&(ve.style.paddingTop=v.paddingY,ve.style.paddingBottom=v.paddingY)),ce.icon){let Te=ae(ce.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__icon"),ce.iconColor&&(Te.style.color=ce.iconColor),ve.appendChild(Te))}let Ae=y("span","persona-suggestion__copy");if(Ae.appendChild(Ie("span",{className:"persona-suggestion__label",text:ce.label})),ce.description&&Ae.appendChild(Ie("span",{className:"persona-suggestion__description",text:ce.description})),ve.appendChild(Ae),T!=="chip"){let Te=ae("arrow-right",16,"currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__arrow"),ve.appendChild(Te))}return ve.addEventListener("click",te),ve},J=null;for(let ve of A)if(ve.renderSuggestion&&(J=ve.renderSuggestion({suggestion:{...ce},index:Z,surface:F,source:P,variant:T,streaming:ge,config:j,defaultRenderer:ie,select:te}),J))break;J??(J=ie()),(Ce=J.dataset).suggestionId||(Ce.suggestionId=ce.id),(ye=J.dataset).behavior||(ye.behavior=de),(xe=J.dataset).emphasis||(xe.emphasis=ce.emphasis),J instanceof HTMLButtonElement||J.setAttribute("aria-disabled",ge?"true":"false"),Y.appendChild(J),n.push(J),[...J instanceof HTMLButtonElement?[J]:[],...Array.from(J.querySelectorAll("button"))].forEach(ve=>{t.includes(ve)||(ve.disabled=ge,t.push(ve))})}),e.appendChild(Y),a(),l();let he=JSON.stringify({normalized:_,surface:F,variant:T,source:P});he!==o&&(o=he,ty(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(ce=>({...ce})),surface:F,source:P,variant:T},bubbles:!0,composed:!0})),k&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(ce=>ce.prompt)},bubbles:!0,composed:!0})))}}};var Sn={"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 ny="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ei=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=ny,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",p=y("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ie("button",{className:On("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ae(u,s,"currentColor",1);return x?(x.style.display="block",v.appendChild(x)):v.textContent=w,p.appendChild(v),Ot({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},oy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ti=(e,t={})=>{let{wrapperClassName:n=oy,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",g=a.borderRadius??"",v=a.paddingX??"",x=a.paddingY??"",P=a.tooltipText??"Clear chat",F=a.showTooltip??!0,k=y("div",n),T=!!(u||w),M=Ie("button",{className:On("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:T?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),U=ae(p,r,"currentColor",1);return U&&(U.style.display="block",M.appendChild(U)),k.appendChild(M),Ot({anchor:M,trigger:k,text:()=>M.getAttribute("aria-label")??P,enabled:F}),{button:M,wrapper:k}};var Jt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},No=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??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Ie("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,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 U=parseFloat(s)||24,j=ae(p,U*.6,"currentColor",1);j?d.replaceChildren(j):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let U=y("img");U.src=t.launcher.iconUrl,U.alt="",U.className="persona-rounded-xl persona-object-cover",U.style.height=s,U.style.width=s,d.replaceChildren(U)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=y("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:Jt.titleColor}}),w=Ie("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let g=r.clearChat??{},v=g.enabled??!0,x=g.placement??"inline",P=null,F=null;if(v){let j=ti(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=j.button,F=j.wrapper,x==="top-right"&&(F.style.right="48px"),x==="inline"&&o.appendChild(F)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:T,wrapper:M}=ei(t,{showClose:n,wrapperClassName:k});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:T,closeButtonWrapper:M,clearChatButton:P,clearChatButtonWrapper:F}},ks=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var ry=e=>{let t=No({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 sy(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=y("div","persona-relative");s.appendChild(r);let a=yr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var ay=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Xp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=y("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Jt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),sy(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let T=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||T()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),T())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Jt.actionIconColor;let v=a.closeButtonIconName??"x",x=ae(v,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",o&&g.addEventListener("click",o),w.appendChild(g),l.appendChild(w);let P=y("div");P.style.display="none";let F=y("span");return F.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:F,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},wu={default:ry,minimal:ay},iy=e=>wu[e]??wu.default,ni=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=y("div");l.style.display="none";let p=y("span"),d=y("span"),c=y("button");c.style.display="none";let u=y("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=iy(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&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var oi=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let p=t.style.maxHeight;if(p!==s){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,a());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}},ri=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",w=t.backgroundColor,g=t.textColor,v=y("div","persona-send-button-wrapper"),x=Ie("button",{className:On("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&&!w&&"persona-bg-persona-primary",!n&&!g&&"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?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&w||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}}),P=null,F=null;if(n){let M=parseFloat(t.iconSize??"")||Math.round((parseFloat(u)||24)*.5),U=t.iconStrokeWidth??2,j=g?.trim()||"currentColor";r?(P=ae(r,M,j,U),P?x.appendChild(P):x.textContent=o):x.textContent=o,F=ae(s,M,j,U)}else x.textContent=p;x.setAttribute("aria-label",a),v.appendChild(x),Ot({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??"",enabled:c});let k="send";return{button:x,wrapper:v,setMode:M=>{if(M===k)return;k=M;let U=M==="stop"?l:a;if(x.setAttribute("aria-label",U),n){if(P&&F){let j=M==="stop"?F:P;x.replaceChildren(j)}}else x.textContent=M==="stop"?d:p}}},si=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 a=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,w=y("div","persona-send-button-wrapper"),g=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:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=ae(l,d,u||"currentColor",1.5);x?g.appendChild(x):g.textContent="\u{1F3A4}",w.appendChild(g);let P=t.tooltipText??"Start voice recognition",F=t.showTooltip??!1;return Ot({anchor:g,trigger:w,text:()=>g.getAttribute("aria-label")??P,enabled:F}),{button:g,wrapper:w}},ai=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??zn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=y("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-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ae(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},ii=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=y("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},li=()=>Ie("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ci=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=li(),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:s,attachAutoResize:a}=oi(t);a();let l=ri(t),p=si(t),d=ai(t),c=ii(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);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":""}}),w=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&g.append(p.wrapper),g.append(l.wrapper),u.append(w,g),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:g,setSendButtonMode:l.setMode}};var xu=()=>{let e=Ie("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Cu=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=li(),r=ii(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=oi(t);s.style.maxHeight="100px",a();let l=ri(t),p=si(t),d=ai(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ie("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var Au=e=>{let t=e?.launcher?.enabled??!0,n=Dt(e);if(Es(e)){let c=e?.launcher?.composerBar??{},u=y("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Vt);let w=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let g=y("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Vt),{wrapper:u,panel:w,pillRoot:g}}if(n){let c=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Sn[r.position]?Sn[r.position]:Sn["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??jn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},di=e=>{let t=Ie("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ml(e)}});return t.hidden=!0,t},ly=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ei(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 s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let j=ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,l=j.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"}}),d=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"}});d.style.setProperty("scrollbar-gutter","stable");let c=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."}),w=di("starter"),g=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)"}},c,u,w),v=y("div","persona-flex persona-flex-col persona-gap-3"),x=di("followUp"),P=e?.layout?.contentMaxWidth;P&&(v.style.maxWidth=P,v.style.marginLeft="auto",v.style.marginRight="auto",v.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,v,x);let k=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"}}),T=Cu({config:e}),{root:M,textNode:U}=xu();return n.append(p,r,d,k),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:v,starterSuggestions:w,transcriptSuggestions:x,composerOverlay:k,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:M,peekTextNode:U}},Su=(e,t=!0)=>{if(Es(e))return ly(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,s=o?ni(e,o,{showClose:t}):No({config:e,showClose:t}),a=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"}});a.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."}),d=di("starter"),c=Ie("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Dt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),w=di("followUp"),g=e?.layout?.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u,w);let x=ci({config:e}),P=e?.layout?.showFooter!==!1;r?ks(n,s,e):(s.header.style.display="none",ks(n,s,e)),n.append(a);let F=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 P||(x.footer.style.display="none"),n.append(x.footer),n.append(F),{container:n,body:a,messagesWrapper:u,starterSuggestions:d,transcriptSuggestions:w,composerOverlay:F,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,introTitle:l,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var El=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
32
32
|
<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>
|
|
33
33
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
34
34
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -36,14 +36,14 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
36
36
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
37
37
|
</span>
|
|
38
38
|
<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>
|
|
39
|
-
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Dt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let E=a.title??"Chat Assistant";p.textContent=E,p.setAttribute("title",E)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let E=a.subtitle??"Here to help you get answers fast";d.textContent=E,d.setAttribute("title",E)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let E=a.agentIconSize??"40px";if(u.style.height=E,u.style.width=E,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let M=parseFloat(E)||24,_=ie(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let E=a.agentIconSize??"40px";w.style.height=E,w.style.width=E,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let E=a.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let M=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,M=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",a.callToActionIconName){let _=parseFloat(E)||24,G=Math.max(_-M,8),x=ie(a.callToActionIconName,G,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&Cn[a.position]?Cn[a.position]:Cn["bottom-right"],C="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",R="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?R:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??Vt));let B="1px solid var(--persona-border, #e5e7eb)",L="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=a.border??B,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,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=a.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 au=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=ru(e),s=su(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},Cl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>xl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=xl(e,n);return{instance:r,element:r.element}};var Dh=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}},Fh=(e,t)=>{if(!e)return null;let n=Dh(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Nh=(e,t)=>{let n=h("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},Oh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Al=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(":"))},Sl=320,du=320,_h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uh=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=h("span","persona-mention-chip-icon"),s=ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Vh=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(is(o.ref,{readonly:!0,render:t}))}return n},iu="\uE000",lu="\uE001",qh=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${iu}${r}:${w}${lu}`,a=t.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!t.every((w,f)=>w.kind==="text"||l.includes(s(f)))){e.replaceChildren(Vh(t,o));return}e.innerHTML=l;let d=new RegExp(`${iu}${r}:(\\d+)${lu}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let f=w;for(let v=d.exec(f.data);v;v=d.exec(f.data)){let C=t[Number(v[1])],R=f.splitText(v.index);R.data=R.data.slice(v[0].length),C?.kind==="mention"&&R.parentNode?.insertBefore(is(C.ref,{readonly:!0,render:o}),R),f=R}}},Kh=(e,t,n)=>{if(e.length===0)return null;try{let o=h("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=h("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Sl}px`,d.style.maxHeight=`${du}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),Oh(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Gh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Al(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Sl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Qh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Al(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Sl}px`,r.style.maxHeight=`${du}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}},Xh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Al(o.data))return;let r=h("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}},xs=()=>{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},Jh=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:xs};if(t){let r=t(o);if(r!==null)return r}return xs()},Yh=(e,t)=>{let n=h("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=h("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},cu=(e,t,n="div")=>{let o=h(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},Tl=(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},Zh=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=h("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let f=(v,C,R)=>{let B=Pt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",R),B};return o&&w.appendChild(f("copy","Copy message","copy")),a&&w.appendChild(f("volume-2","Read aloud","read-aloud")),r&&w.appendChild(f("thumbs-up","Upvote","upvote")),s&&w.appendChild(f("thumbs-down","Downvote","downvote")),w},Ml=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",v=Tl(e.role,l),C=h("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let R=_h(e),B=e.content?.trim()??"",E=R.length>0&&B===Ca,M=ja(s?.widgetConfig?.features?.streamAnimation),_=s?.widgetConfig?.features?.streamAnimation?.plugins,G=e.role==="assistant"&&M.type!=="none"?mr(M.type,_):null,x=e.role==="assistant"&&G?.isAnimating?.(e)===!0,j=e.role==="assistant"&&G!==null&&(!!e.streaming||x);j&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),j&&G&&(G.containerClass&&U.classList.add(G.containerClass),U.style.setProperty("--persona-stream-step",`${M.speed}ms`),U.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let oe=j?Ua(e.content??"",M.buffer,G,e,!!e.streaming):e.content??"",F=()=>{let Y=t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent});return j&&G?.wrap==="char"?ms(Y,"char",e.id,{skipTags:G.skipTags}):j&&G?.wrap==="word"?ms(Y,"word",e.id,{skipTags:G.skipTags}):Y},$=null;if(E?($=document.createElement("div"),$.innerHTML=F(),$.style.display="none",U.appendChild($)):e.contentSegments?.length?qh(U,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):U.innerHTML=F(),j&&G?.useCaret&&!E&&B){let Y=Va(),pe=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=pe[pe.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(Y,xe.nextSibling);else{let ye=U.lastElementChild;ye?ye.appendChild(Y):U.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=cu(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=U.lastElementChild;pe?pe.appendChild(Y):U.appendChild(Y)}if(R.length>0){let Y=Kh(R,!E&&!!B,()=>{E&&$&&($.style.display="")});Y?C.appendChild(Y):E&&$&&($.style.display="")}let X=$h(e);if(X.length>0){let Y=Gh(X);Y&&C.appendChild(Y)}let me=zh(e);if(me.length>0){let Y=Qh(me);Y&&C.appendChild(Y)}let he=jh(e);if(he.length>0){let Y=Xh(he);Y&&C.appendChild(Y)}let Ae=e.contentSegments?.length?null:Uh(e.contextMentions);if(Ae&&C.appendChild(Ae),C.appendChild(U),u&&f==="below"&&e.createdAt){let Y=cu(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Z=e.role==="assistant"?Fh(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(oe&&oe.trim()),pe=M.placeholder==="skeleton",xe=pe&&M.buffer==="line"&&Y;if(Y)xe&&C.appendChild(hs());else if(pe)C.appendChild(hs());else{let ye=Jh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(Z&&e.stopReason&&!e.streaming&&(B||(U.style.display="none"),C.appendChild(Nh(e.stopReason,Z))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Zh(e,o,r);C.appendChild(Y)}if(!c||e.role==="system")return C;let ee=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=Yh(p,e.role);return w==="right"||w==="left"&&e.role==="user"?ee.append(C,le):ee.append(le,C),ee};var hr=new Set,ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ty=(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(`
|
|
40
|
-
`):""},
|
|
41
|
-
`);let r=
|
|
42
|
-
`):""},kl=(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)"},ry=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=oy(e,o?.previewMaxLines??3),a=n?qd(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=Zi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Zi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},uu=(e,t,n)=>{let o=yr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ie(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Ll=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=h("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 s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&yr.has(e.id),{summary:p,previewText:d,isActive:c}=ry(e,t),u=h("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");u.type="button",a&&(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 w=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let F=h("span","");return F.setAttribute("data-tool-elapsed",v),F.textContent=Zr(n),F},R=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Zr(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(f.textContent=R,w.appendChild(f)):R instanceof HTMLElement?w.appendChild(R):(f.textContent=p,w.appendChild(f));let B=s.loadingAnimation??"none",L=o.activeTextTemplate,E=o.completeTextTemplate,M=c?L:E,_=R instanceof HTMLElement,G=(F,$)=>{f.textContent="";let X=n.name?.trim()||"tool",me=va(F,X),he=0;for(let Ae of me){let Z=Ae.styles.length>0?(()=>{let ce=h("span",Ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(ce),ce})():f;if(Ae.isDuration&&c)Z.appendChild(C());else{let ce=Ae.isDuration?Zr(n):Ae.text;$?he=co(Z,ce,he):Z.appendChild(document.createTextNode(ce))}}};if(!_)if(c&&B!=="none"){let F=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),B==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),M&&G(M,!1);else if(f.classList.add(`persona-tool-loading-${B}`),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),B==="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)),M)G(M,!0);else{let $=f.textContent||p;f.textContent="",co(f,$,0)}}else M&&G(M,!1);let x=null;if(a){x=h("div","persona-flex persona-items-center");let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(x),u.append(w,X)}else u.append(w);let j=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let F=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});ny(j,F)||(j.textContent=d),j.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,j),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(U.style.display=l?"":"none",o.contentBackgroundColor&&(U.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(U.style.color=o.contentTextColor),o.contentPaddingX&&(U.style.paddingLeft=o.contentPaddingX,U.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(U.style.paddingTop=o.contentPaddingY,U.style.paddingBottom=o.contentPaddingY),n.name){let F=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?F.style.color=o.contentTextColor:o.headerTextColor&&(F.style.color=o.headerTextColor),F.textContent=n.name,U.appendChild(F)}if(n.args!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let X=h("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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.args),F.append($,X),U.appendChild(F)}if(n.chunks&&n.chunks.length){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let X=h("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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=n.chunks.join(""),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&n.result!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let X=h("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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.result),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&typeof n.duration=="number"){let F=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(F.style.color=o.contentTextColor),F.textContent=`Duration: ${n.duration}ms`,U.appendChild(F)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show"}U.style.display=l?"":"none",j.style.display=l?"none":j.textContent||j.childNodes.length?"":"none"})(),r.append(u,j,U),r};var Bo=new Map,oi=e=>{let n=(e.startsWith(Nn)?e.slice(Nn.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)},fu=e=>e?.approval!==!1?e?.approval:void 0,gu=(e,t)=>{let n=fu(t)?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},mu=(e,t,n)=>{let o=fu(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 s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ie(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},hu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=gu(e,n);mu(o,s,n),r.style.display=s?"":"none"};var ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=h("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.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 s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=h("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ie(p,20,d,2);c&&l.appendChild(c);let u=h("div","persona-flex-1 persona-min-w-0"),w=h("div","persona-flex persona-items-center persona-gap-2"),f=h("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",w.appendChild(f),!r){let x=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");x.setAttribute("data-approval-status",n.status),n.status==="approved"?(x.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",x.style.color="var(--persona-palette-colors-success-700, #15803d)",x.textContent="Approved"):n.status==="denied"?(x.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",x.style.color="var(--persona-palette-colors-error-700, #b91c1c)",x.textContent="Denied"):n.status==="timeout"&&(x.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",x.style.color="var(--persona-palette-colors-warning-700, #b45309)",x.textContent="Timeout"),w.appendChild(x)}u.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Nn)?Gr(n.toolName):void 0,R=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,L=R||(B?n.description:`The assistant wants to use \u201C${C??oi(n.toolName)}\u201D.`),E=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=L,u.appendChild(E),n.reason){let x=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");x.setAttribute("data-approval-reason","true"),o?.reasonColor?x.style.color=o.reasonColor:o?.descriptionColor&&(x.style.color=o.descriptionColor);let j=h("span","persona-font-medium");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,x.appendChild(j),x.appendChild(document.createTextNode(n.reason)),u.appendChild(x)}let M=o?.detailsDisplay??"collapsed",_=!!n.description&&!B,G=_||!!n.parameters;if(M!=="hidden"&&G){let x=gu(e.id,t),j=h("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");j.type="button",j.setAttribute("data-expand-header","true"),j.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span");U.setAttribute("data-approval-details-label","true");let oe=h("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),j.append(U,oe),mu(j,x,t),u.appendChild(j);let F=h("div");if(F.setAttribute("data-approval-details","true"),F.style.display=x?"":"none",_){let $=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,F.appendChild($)}if(n.parameters){let $=h("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&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=io(n.parameters),F.appendChild($)}u.appendChild(F)}if(r){let x=h("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let j=h("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");j.type="button",j.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",j.style.color=o?.approveButtonTextColor??"#ffffff",j.setAttribute("data-approval-action","approve");let U=ie("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);U&&(U.style.marginRight="4px",j.appendChild(U));let oe=document.createTextNode(o?.approveLabel??"Approve");j.appendChild(oe);let F=h("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");F.type="button",F.style.backgroundColor=o?.denyButtonColor??"transparent",F.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",F.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,F.setAttribute("data-approval-action","deny");let $=ie("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",F.appendChild($));let X=document.createTextNode(o?.denyLabel??"Deny");F.appendChild(X),x.append(j,F),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var sy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),yu=(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))},Do=(e,t)=>{yu(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)},ay=e=>e?.approval!==!1?e?.approval:void 0,iy=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},Pl=e=>{let t=h("span","persona-approval-kbd");return t.textContent=e,t},ly=(e,t)=>{let n=h("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Nn)?Gr(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??oi(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=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},cy=e=>{let t=h("div","persona-approval-resolved"),n=ie("ban",15,"currentColor",2);n&&t.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=e.toolName?oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},dy=(e,t,n,o,r,s,a)=>{let l=h("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&iy(t.id,o),f=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:f)):C.setAttribute("data-static","true");let R=h("span","persona-approval-logo"),B=ie("shield-check",16,"currentColor",2);B&&R.appendChild(B),C.appendChild(R);let L=ly(n,o);if(u){let j=h("span","persona-approval-toggle");j.setAttribute("aria-hidden","true");let U=ie("chevron-down",14,"currentColor",2);U&&j.appendChild(U),L.append(" "),L.appendChild(j)}C.appendChild(L),l.appendChild(C);let E=h("div","persona-approval-body");if(u){let j=h("div","persona-approval-details");if(j.setAttribute("data-role","params"),j.hidden=!w,d){let U=h("p","persona-approval-desc");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,j.appendChild(U)}if(c){let U=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(U.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.textContent=io(n.parameters),j.appendChild(U)}E.appendChild(j)}if(n.reason){let j=h("p","persona-approval-reason");o?.reasonColor?j.style.color=o.reasonColor:o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span","persona-approval-reason-label");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,j.append(U,document.createTextNode(n.reason)),E.appendChild(j)}let M=h("div","persona-approval-actions"),_=null,G=j=>{o?.approveButtonColor&&(j.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(j.style.color=o.approveButtonTextColor)},x=h("button","persona-approval-deny");if(x.type="button",x.setAttribute("data-action","deny"),o?.denyButtonColor&&(x.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(x.style.color=o.denyButtonTextColor),x.append(o?.denyLabel??"Deny"),a){let j=h("div","persona-approval-split"),U=h("button","persona-approval-primary");U.type="button",U.setAttribute("data-action","always"),G(U),U.append(o?.approveLabel??"Always allow",Pl("\u23CE"));let oe=h("button","persona-approval-caret");oe.type="button",oe.setAttribute("data-action","toggle-menu"),oe.setAttribute("aria-label","More options"),G(oe);let F=ie("chevron-down",15,"currentColor",2);F&&oe.appendChild(F),j.append(U,oe),M.append(j,x),x.append(Pl("Esc"));let $=h("div","persona-approval-menu"),X=h("button","persona-approval-menu-item");X.type="button",X.append("Allow once",Pl("\u2318\u23CE")),$.appendChild(X),_=fd({anchor:j,content:$,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),X.addEventListener("click",()=>{Do(e,t.id),r()})}else{let j=h("button","persona-approval-primary persona-approval-primary--solo");j.type="button",j.setAttribute("data-action","allow"),G(j),j.append(o?.approveLabel??"Allow"),M.append(j,x)}return E.appendChild(M),l.appendChild(E),l.addEventListener("click",j=>{let U=j.target instanceof Element?j.target.closest("[data-action]"):null;if(!U)return;let oe=U.getAttribute("data-action");if(oe==="toggle-params"){let F=l.querySelector('[data-role="params"]');if(F){let $=F.hidden;F.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?v:f),Bo.set(t.id,$)}return}if(oe==="toggle-menu"){_?.toggle();return}if(oe==="always"){Do(e,t.id),r({remember:!0});return}if(oe==="allow"){Do(e,t.id),r();return}if(oe==="deny"){Do(e,t.id),s();return}}),l},bu=()=>{let e=sy();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let p=ay(a);if(l.status!=="pending"){if(Do(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return cy(l)}yu(e,o.id);let d=p?.enableAlwaysAllow===!0,c=dy(e,o,l,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=w=>{gd(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Do(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Do(e,o);e.latestPendingApprovalId=null}}};var vu=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,l,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(R=>R.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=v=>{switch(v){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(v=>{let C=h("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");C.type="button",C.textContent=v,C.disabled=w,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Cs=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 As=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 a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.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 py=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),uy=new Set(["step_start","execution_start"]),fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),gy=new Set(["step_complete","agent_turn_complete"]),my=new Set(["flow_complete","agent_complete"]),wu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Cu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Fo=(e,t)=>{let n=e[t];return Cu(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function hy(e,t){return typeof t.type=="string"?t.type:e}function yy(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 by(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 xu(e){let t=Fo(e,"result"),n=[Fo(e,"tokens"),Fo(e,"totalTokens"),t?Fo(t,"tokens"):void 0,Fo(e,"usage"),t?Fo(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=rn(o.output)??rn(o.outputTokens)??rn(o.completionTokens);if(r!==void 0)return r}return rn(e.outputTokens)??rn(e.completionTokens)??(t?rn(t.outputTokens)??rn(t.completionTokens):void 0)}function vy(e){let t=Fo(e,"result");return rn(e.executionTime)??rn(e.executionTimeMs)??rn(e.execution_time)??rn(e.duration)??(t?rn(t.executionTime)??rn(t.executionTimeMs):void 0)}function wy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ss=class{constructor(t=wy){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:si(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(!Cu(n)){wu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=hy(t,n),r=this.now();if(py.has(o)){this.startRun(r);return}if(uy.has(o)){this.run||this.startRun(r);return}if(fy.has(o)){if(!by(o,n))return;let s=yy(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Il(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(gy.has(o)){if(!this.run)return;let s=this.run,a=xu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+Il(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:si(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(my.has(o)){if(!this.run)return;let s=this.run,a=xu(n),l=a??s.exactOutputTokens+Il(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:si(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(wu.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:vy(n)??o-t.startedAt}};function br(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xy={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)"}},Cy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ay=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sy=100;function Ty(e,t){let n={...xy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Cy}function My(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Ey(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"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ky(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("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Ly(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 Py(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 Iy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ry(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 Wy(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 s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=h("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=h("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 Rl(e,t,n,o,r,s,a,l){let p=r.has(e.id),d=h("div","persona-border-b persona-border-persona-divider persona-text-xs");br(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=h("div",""),f=h("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 v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ie(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let R=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";R.textContent=B==="relative"?My(e.timestamp,n):Ey(e.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let E=Ty(e.type,o.badgeColors),M=h("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");M.style.backgroundColor=E.bg,M.style.color=E.text,M.style.borderColor=E.text+"50",M.textContent=e.type;let _=o.descriptionFields??Ay,G=ky(e.payload,_),x=null;G&&(x=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=G);let j=h("div","persona-flex-1 persona-min-w-0"),U=h("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"),oe=ie("clipboard","12px","currentColor",1.5);return oe&&U.appendChild(oe),U.addEventListener("click",async F=>{F.stopPropagation(),await Ly(Py(e)),U.innerHTML="";let $=ie("check","12px","currentColor",1.5);$&&U.appendChild($),setTimeout(()=>{U.innerHTML="";let X=ie("clipboard","12px","currentColor",1.5);X&&U.appendChild(X)},1500)}),f.appendChild(v),f.appendChild(R),L&&f.appendChild(L),f.appendChild(M),x&&f.appendChild(x),f.appendChild(j),f.appendChild(U),w.appendChild(f),p&&w.appendChild(Wy(e,a,l)),w}}function Au(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return f();function f(){let v=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");br(C,v?.panel);let R=[],B="",L="",E=null,M=[],_={},G=0,x=_a(),j=0,U=0,oe=!1,F=null,$=!1,X=0,me=new Set,he=new Map,Ae="",Z="",ce=null,ee,le,Y,pe,xe=null,ye=null,ve=null;function je(){let H=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=h("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(br(z,v?.headerBar),a){ye=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",xe=h("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"),xe.textContent="-- tok/s",ve=h("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"),ve.style.display="none",ve.style.pointerEvents="none";let Fe=ye,Rt=ve,di=()=>{if(!Rt.textContent)return;let Ls=Fe.getBoundingClientRect(),Ps=H.getBoundingClientRect();Rt.style.left=`${Ls.left-Ps.left}px`,Rt.style.top=`${Ls.bottom-Ps.top+4}px`,Rt.style.display="block"},go=()=>{Rt.style.display="none"};ye.addEventListener("mouseenter",di),ye.addEventListener("mouseleave",go),ye.appendChild(xe)}let J=h("div","persona-flex-1");ee=h("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 qe=h("option","");qe.value="",qe.textContent="All events (0)",ee.appendChild(qe),le=h("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 Je=ie("clipboard-copy","12px","currentColor",1.5);Je&&le.appendChild(Je);let rt=h("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),ye&&z.appendChild(ye),z.appendChild(J),z.appendChild(ee),z.appendChild(le);let V=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");br(V,v?.searchBar);let _e=ie("search","14px","var(--persona-muted, #9ca3af)",1.5),be=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");_e&&be.appendChild(_e),Y=h("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"),br(Y,v?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",pe=h("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"),pe.type="button",pe.style.display="none";let $e=ie("x","12px","currentColor",2);return $e&&pe.appendChild($e),V.appendChild(be),V.appendChild(Y),V.appendChild(pe),H.appendChild(z),H.appendChild(V),ve&&H.appendChild(ve),H}let Me,De=s.find(H=>H.renderEventStreamToolbar);De?.renderEventStreamToolbar&&r?Me=De.renderEventStreamToolbar({config:r,defaultRenderer:()=>je(),eventCount:t.getSize(),filteredCount:0,onFilterChange:z=>{B=z,et(),se()},onSearchChange:z=>{L=z,et(),se()}})??je():Me=je();let Qe=h("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");Qe.style.display="none";function Ve(){if(!a||!xe||!ye)return;let H=a(),z=Iy(H);xe.textContent=z;let J=Ry(H);ve&&(ve.textContent=J,J||(ve.style.display="none")),ye.setAttribute("aria-label",J?`Throughput: ${z}, ${J}`:`Throughput: ${z}`)}let Te=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Le=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Le.style.height="100%";let Xe=h("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");br(Xe,v?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ht=ie(d,"14px","currentColor",2);Ht&&Xe.appendChild(Ht);let It=h("span","");It.textContent=c,Xe.appendChild(It);let qt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");qt.style.display="none",Te.appendChild(Le),Te.appendChild(qt),Te.appendChild(Xe),C.setAttribute("tabindex","0"),C.appendChild(Me),C.appendChild(Qe),C.appendChild(Te);function xt(){let H=t.getAll(),z={};for(let V of H)z[V.type]=(z[V.type]||0)+1;let J=Object.keys(z).sort(),qe=J.length!==M.length||!J.every((V,_e)=>V===M[_e]),Re=!qe&&J.some(V=>z[V]!==_[V]),Je=H.length!==Object.values(_).reduce((V,_e)=>V+_e,0);if(!qe&&!Re&&!Je||(M=J,_=z,!ee))return;let rt=ee.value;if(ee.options[0].textContent=`All events (${H.length})`,qe){for(;ee.options.length>1;)ee.remove(1);for(let V of J){let _e=h("option","");_e.value=V,_e.textContent=`${V} (${z[V]||0})`,ee.appendChild(_e)}rt&&J.includes(rt)?ee.value=rt:rt&&(ee.value="",B="")}else for(let V=1;V<ee.options.length;V++){let _e=ee.options[V];_e.textContent=`${_e.value} (${z[_e.value]||0})`}}function He(){let H=t.getAll();if(B&&(H=H.filter(z=>z.type===B)),L){let z=L.toLowerCase();H=H.filter(J=>J.type.toLowerCase().includes(z)||J.payload.toLowerCase().includes(z))}return H}function de(){return B!==""||L!==""}function et(){G=0,j=0,x.resume(),Xe.style.display="none"}function Ie(H){me.has(H)?me.delete(H):me.add(H),ce=H;let z=Le.scrollTop,J=x.isFollowing();$=!0,x.pause(),se(),Le.scrollTop=z,J&&x.resume(),$=!1}function fe(){return uo(Le,50)}function se(){U=Date.now(),oe=!1,Ve(),xt();let H=t.getEvictedCount();H>0?(Qe.textContent=`${H.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",R=He();let z=R.length,J=t.getSize()>0;z===0&&J&&de()?(qt.textContent=L?`No events matching '${L}'`:"No events matching filter",qt.style.display="",Le.style.display="none"):(qt.style.display="none",Le.style.display=""),le&&(le.title=de()?`Copy Filtered (${z})`:"Copy All"),p&&!x.isFollowing()&&z>G&&(j+=z-G,It.textContent=c?`${c}${j>0?` (${j})`:""}`:"",Xe.style.display=""),G=z;let qe=t.getAll(),Re=qe.length>0?qe[0].timestamp:0,Je=new Set(R.map(_e=>_e.id));for(let _e of me)Je.has(_e)||me.delete(_e);let rt=B!==Ae||L!==Z,V=he.size===0&&R.length>0;if(rt||V||R.length===0){Le.innerHTML="",he.clear();let _e=document.createDocumentFragment();for(let be=0;be<R.length;be++){let $e=Rl(R[be],be,Re,u,me,Ie,s,r);he.set(R[be].id,$e),_e.appendChild($e)}Le.appendChild(_e),Ae=B,Z=L,ce=null}else{if(ce!==null){let be=he.get(ce);if(be&&be.parentNode===Le){let $e=R.findIndex(Fe=>Fe.id===ce);if($e>=0){let Fe=Rl(R[$e],$e,Re,u,me,Ie,s,r);Le.insertBefore(Fe,be),be.remove(),he.set(ce,Fe)}}ce=null}let _e=new Set(R.map(be=>be.id));for(let[be,$e]of he)_e.has(be)||($e.remove(),he.delete(be));for(let be=0;be<R.length;be++){let $e=R[be];if(!he.has($e.id)){let Fe=Rl($e,be,Re,u,me,Ie,s,r);he.set($e.id,Fe),Le.appendChild(Fe)}}}x.isFollowing()&&(Le.scrollTop=Le.scrollHeight)}function Pe(){if(Date.now()-U>=Sy){F!==null&&(cancelAnimationFrame(F),F=null),se();return}oe||(oe=!0,F=requestAnimationFrame(()=>{F=null,se()}))}let it=(H,z)=>{if(!le)return;le.innerHTML="";let J=ie(H,"12px","currentColor",1.5);J&&le.appendChild(J);let qe=h("span","persona-text-xs");qe.textContent="Copy All",le.appendChild(qe),setTimeout(()=>{le.innerHTML="";let Re=ie("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Je=h("span","persona-text-xs");Je.textContent="Copy All",le.appendChild(Je),le.disabled=!1},z)},ue=async()=>{if(le){le.disabled=!0;try{let H;de()?H=R:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let z=H.map(J=>{try{return JSON.parse(J.payload)}catch{return J.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),it("check",1500)}catch{it("x",1500)}}},Ce=()=>{ee&&(B=ee.value,et(),se())},te=()=>{!Y||!pe||(pe.style.display=Y.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{L=Y.value,et(),se()},150))},S=()=>{!Y||!pe||(Y.value="",L="",pe.style.display="none",E&&clearTimeout(E),et(),se())},D=()=>{if($)return;let H=Le.scrollTop,{action:z,nextLastScrollTop:J}=$a({following:x.isFollowing(),currentScrollTop:H,lastScrollTop:X,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});X=J,z==="resume"?(x.resume(),j=0,Xe.style.display="none"):z==="pause"&&(x.pause(),p&&(It.textContent=c,Xe.style.display=""))},y=H=>{let z=za({following:x.isFollowing(),deltaY:H.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});z==="pause"?(x.pause(),p&&(It.textContent=c,Xe.style.display="")):z==="resume"&&(x.resume(),j=0,Xe.style.display="none")},P=()=>{p&&(Le.scrollTop=Le.scrollHeight,x.resume(),j=0,Xe.style.display="none")},T=H=>{let z=H.target;if(!z||z.closest("button"))return;let J=z.closest("[data-event-id]");if(!J)return;let qe=J.getAttribute("data-event-id");qe&&Ie(qe)},I=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Y?.focus(),Y?.select();return}H.key==="Escape"&&(Y&&document.activeElement===Y?(S(),Y.blur(),C.focus()):o&&o())};le&&le.addEventListener("click",ue),ee&&ee.addEventListener("change",Ce),Y&&Y.addEventListener("input",te),pe&&pe.addEventListener("click",S),Le.addEventListener("scroll",D),Le.addEventListener("wheel",y,{passive:!0}),Le.addEventListener("click",T),Xe.addEventListener("click",P),C.addEventListener("keydown",I);function q(){E&&clearTimeout(E),F!==null&&(cancelAnimationFrame(F),F=null),oe=!1,he.clear(),le&&le.removeEventListener("click",ue),ee&&ee.removeEventListener("change",Ce),Y&&Y.removeEventListener("input",te),pe&&pe.removeEventListener("click",S),Le.removeEventListener("scroll",D),Le.removeEventListener("wheel",y),Le.removeEventListener("click",T),Xe.removeEventListener("click",P),C.removeEventListener("keydown",I)}return{element:C,update:Pe,destroy:q}}}function Su(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&t.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,v)=>{f.setAttribute("role","tab");let C=v===w;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||w<0&&v===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Tu(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),$?.hide()};w&&w.addEventListener("click",()=>{f(),t.onDismiss?.()});let v=h("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");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=h("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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let R=h("span","persona-text-xs persona-font-medium persona-truncate");R.textContent=s;let B=Pt({icon:"x",label:a});B.addEventListener("click",()=>{f(),t.onDismiss?.()});let L="rendered",E=Ba({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:te=>{L=te==="source"?"source":"rendered",it()}}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,j=!!(G&&x&&x.length>0),U=null,oe,F=null,$=null;if(r&&(_||G)&&!j){if(oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let te=ie("chevron-down",14,"currentColor",2);te&&oe.appendChild(te)}}else r&&j?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F=Pt({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"}}),U.append(oe,F)):r?oe=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(oe=Pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&oe.classList.add("persona-hidden"));let X=r?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),me=r?Pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:a}),he=Pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let Ae=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=e.features?.artifacts?.toolbarActions??[],ce=()=>{let te=Te.find(P=>P.id===Le)??Te[Te.length-1],S=te?.id??null,D=te?.artifactType==="markdown"?te.markdown??"":"",y=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:D,jsonPayload:y,id:S}},ee=async()=>{let te=Te.find(S=>S.id===Le)??Te[Te.length-1];try{await navigator.clipboard.writeText(fs(te))}catch{}};if(oe.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&j){let{markdown:S,jsonPayload:D,id:y}=ce();try{await te({actionId:"primary",artifactId:y,markdown:S,jsonPayload:D})}catch{}return}await ee()}),F&&x?.length){let te=()=>v.closest("[data-persona-root]")??document.body,S=()=>{$=fr({items:x.map(D=>({id:D.id,label:D.label})),onSelect:async D=>{let{markdown:y,jsonPayload:P,id:T}=ce(),I=n?.onDocumentToolbarCopyMenuSelect;try{I?await I({actionId:D,artifactId:T,markdown:y,jsonPayload:P}):D==="markdown"||D==="md"?await navigator.clipboard.writeText(y):D==="json"||D==="source"?await navigator.clipboard.writeText(P):await navigator.clipboard.writeText(y||P)}catch{}},anchor:U??F,position:"bottom-right",portal:te()})};v.isConnected?S():requestAnimationFrame(S),F.addEventListener("click",D=>{D.stopPropagation(),$?.toggle()})}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),me.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=h("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)C.replaceChildren(),U?M.append(U,X,me):M.append(oe,X,me),M.insertBefore(Ae,me),M.insertBefore(he,me),C.append(E.element,le,M);else{let te=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(oe,Ae,he,B),C.appendChild(R),C.appendChild(te)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Y=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let pe=e.features?.artifacts?.renderTabBar,xe=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Su(Y,{onSelect:te=>t.onSelect(Te[te].id)}),ve=te=>{let S=te.scrollWidth-te.clientWidth,D=S>1,y=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",c&&D&&y>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&D&&y<S-1)},je=0,Me=()=>{if(je)return;let te=()=>{je=0,ve(Y)};je=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};Y.addEventListener("scroll",()=>Me(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ve(Y)).observe(Y);let De=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Qe=()=>{De.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Qe):setTimeout(Qe,0)};if(l){for(let te of[Y,xe])te.style.paddingLeft=l,te.style.paddingRight=l;De.style.padding=l}v.appendChild(C),v.appendChild(Y),v.appendChild(xe),v.appendChild(De);let Te=[],Le=null,Xe=!1,Ht=!1,It=!0,qt=!1,xt=null,He="",de=null,et=!1,Ie=te=>te.artifactType==="markdown"&&!!te.file||r?L:"rendered",fe=te=>{r||(te&&!et?(C.insertBefore(E.element,R),et=!0):!te&&et&&(E.element.remove(),et=!1))},se=()=>Le&&Te.find(te=>te.id===Le)||Te[Te.length-1],Pe=()=>{let te=ps(se());if(!te){Ae.replaceChildren();return}let S=Z.filter(D=>D.visible===void 0||D.visible(te)).map(D=>gr(D,{documentChrome:r,onClick:()=>{let y=ps(se());if(y)try{Promise.resolve(D.onClick(y)).catch(()=>{})}catch{}}}));Ae.replaceChildren(...S)},it=()=>{Pe();let te=r&&Te.length<=1,S=!!pe;if(Y.classList.toggle("persona-hidden",te||S),xe.classList.toggle("persona-hidden",te||!S),S&&pe){let P=Te.map(T=>T.id).join("|")+" "+(Le??"");if(P!==He){He=P;let T=pe({records:Te,selectedId:Le,onSelect:t.onSelect});xe.firstElementChild!==T&&xe.replaceChildren(T)}}else{ye.beforeRender(),Y.replaceChildren();let P=[],T=-1;for(let[I,q]of Te.entries()){let H=h("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");H.type="button";let z=q.artifactType==="markdown"?q.file:void 0,J=z?Mn(z.path):q.title||q.id.slice(0,8),qe=z?.path||q.title||J;H.textContent=J,H.title=qe,H.setAttribute("aria-label",qe),q.id===Le&&(H.classList.add("persona-bg-persona-container","persona-border-persona-border"),T=I),H.addEventListener("click",()=>t.onSelect(q.id)),Y.appendChild(H),P.push(H)}if(ye.render(P,T),T>=0&&Le!==xt){xt=Le;let I=P[T];typeof I.scrollIntoView=="function"&&I.scrollIntoView({block:"nearest",inline:"nearest"})}ve(Y)}let D=Le&&Te.find(P=>P.id===Le)||Te[Te.length-1];if(!D){De.replaceChildren(),de=null,fe(!1);return}let y=D.artifactType==="markdown"?D.file:void 0;if(fe(!!y),r){let P=y?lo(y):D.artifactType==="markdown"?"MD":D.component??"Component",T=(D.title||"Document").trim(),I=y?Mn(y.path):T.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${I} \xB7 ${P}`}else R.textContent=y?Mn(y.path):s;de?(de.el.parentElement!==De&&De.replaceChildren(de.el),de.update(D)):(de=Na(D,{config:e,resolveViewMode:Ie}),De.replaceChildren(de.el)),De.classList.toggle("persona-artifact-content-flush",!!De.querySelector(".persona-code-pre"))},ue=()=>{let te=Te.length>0;if(v.classList.toggle("persona-hidden",!te),w){let y=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;te&&y&&Xe?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},Ce=()=>{qt=!1,it(),ue()};return{element:v,backdrop:w,update(te){let S=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,D=S!==Le;Te=te.artifacts,Le=S,Te.length>0&&(Xe=!0),qt=!0,It&&Ce(),D&&Qe()},setMobileOpen(te){Xe=te,!te&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(te){te!==Ht&&(Ht=te,Ve());let S=ie(te?"minimize":"maximize",16,"currentColor",2);S&&he.replaceChildren(S);let D=te?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",D),he.title=D},setExpandToggleVisible(te){he.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||oe.classList.toggle("persona-hidden",!te)},setCustomActions(te){Z=te,Pe()},setTabFade(te){let S=d(te);S.start===c&&S.end===u||(c=S.start,u=S.end,ve(Y))},setRenderTabBar(te){te!==pe&&(pe=te,He="",it())},setVisible(te){te!==It&&(It=te,te&&qt&&Ce())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Mu(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"),!Xt(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 Hy(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 Eu=["panel","seamless","detached"];function Wl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Eu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Hl(e){return!e||!Xt(e)?!1:Wl(e)==="detached"}function Ts(e,t){if(!Xt(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"),Hy(e),Mu(e,t);return}let n=t.features?.artifacts?.layout,o=Wl(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 s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):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"),Mu(e,t)}function Ms(e,t){for(let l of Eu)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"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=Wl(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ku(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var By=new Set(["__proto__","prototype","constructor"]),Dy=new Set(["collapsed","card","panel","inline"]),Lu=new Set(["markdown","component"]),Fy=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,No=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ii=e=>!By.has(e),Bl=e=>typeof e=="string"&&Dy.has(e),Oo=e=>Object.keys(e).length>0;function kn(e,t,n,o){e.push({path:t,code:n,message:o})}var Ny="Ignored because this key is not part of the persisted preference schema.",ai="Ignored an unsupported value.",Oy="Expected collapsed, panel, or inline.",_y='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Pu={kind:"mode",message:ai},vr={kind:"string",message:"Expected a CSS length string."},jn={kind:"boolean"},$y={paneWidth:vr,paneMaxWidth:vr,paneMinWidth:vr,expandedPanelWidth:vr,resizableMinWidth:vr,resizableMaxWidth:vr,expandLauncherPanelWhenOpen:jn,resizable:jn},zy={kind:"object",message:"Expected a preference object.",children:{showToolCalls:jn,showReasoning:jn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ai},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ai},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ai},expandable:jn,grouped:jn}},reasoningDisplay:{kind:"object",children:{expandable:jn,activePreview:jn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Pu,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Pu,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Lu,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Lu}}},filePreview:{kind:"object",children:{enabled:jn}},layout:{kind:"object",children:$y}}}}};function Iu(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:kn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:kn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:kn(o,n,"invalid_value",t.message);case"mode":return Bl(e)?un(e):kn(o,n,"invalid_value",t.message);case"modeMap":{if(!No(e))return kn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let p=r?a:er(a);ii(a)&&(r?r.has(a):Fy.test(p))?Bl(l)?s[p]=un(l):kn(o,`${n}.${a}`,"invalid_value",Oy):kn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":_y)}return Oo(s)?s:void 0}case"object":{if(t.bareMode&&Bl(e))return un(e);if(!No(e))return kn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!ii(l)||!r.includes(l))&&kn(o,s(l),"unknown_key",Ny);let a={};for(let l of r){let p=t.children[l],d=Iu(e[l],p,s(l),o);if(p.deprecated&&e[l]!==void 0&&kn(o,s(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,u=a[c];a[c]=No(u)&&No(d)?{...u,...d}:d}return Oo(a)?a:void 0}}}function jy(e){let t=[];return{preferences:(e===null?void 0:Iu(e,zy,"",t))??{},issues:t}}function wr(e){if(Array.isArray(e))return e.map(wr);if(!No(e))return e;let t={};for(let[n,o]of Object.entries(e))ii(n)&&o!==void 0&&(t[n]=wr(o));return t}function Ru(e,t){let n=wr(e);for(let[o,r]of Object.entries(t)){if(!ii(o)||r===void 0)continue;let s=n[o];n[o]=No(s)&&No(r)?Ru(s,r):wr(r)}return n}function Uy(e){let t={},n;for(let r of e){let s=jy(r).preferences;n=Wu(n,s.artifacts?.display),t=Ru(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Vy(e,t){if(t===void 0)return e===void 0?void 0:wr(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},s={...o?{default:o}:{},...Oo(r)?{byMediaType:r}:{}};return Oo(s)?s:void 0}function Wu(e,t){if(t===void 0)return e===void 0?void 0:wr(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},s=Vy(n.files,t.files),a={...o?{default:o}:{},...Oo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Oo(a)?a:void 0}function qy(e={},t){let n=Uy(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??{},s={...r};if(n.artifacts.display!==void 0){let a=Wu(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Dl(e){let t=e.preferences;return!t||!Oo(t)?e:{...e,features:qy(e.features??{},[t])}}function Ky(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 Gy(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 Qy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Xy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Fl(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 s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Hu(e,t,n,o,r,s){let a=Ky(r,200),l=Xy(t,n,o,200);l=Math.max(a,l);let p=Gy(s);return p!==null&&(l=Math.min(l,p)),Qy(e,a,l)}var Bu={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"}},Nl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Bu[a]??Bu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),d=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=h("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${v.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=v.label,C.appendChild(R);let B=v.type??"text",L;B==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=B),L.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",L.id=`${t.id}-${a}-${v.name}`,L.name=v.name,L.placeholder=v.placeholder??"",v.required&&(L.required=!0),C.appendChild(L),c.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("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(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",R=new FormData(c),B={};R.forEach((L,E)=>{B[E]=L}),B.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let L=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let E=await L.json();w.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(L){w.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ol=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(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},_l=new Ol;var Du=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Fu=(e,t,n)=>{if(!Du(e)||!Du(t)||Jy.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Fu(e[r],t[r],s)}return o};function Nu(e,t){let n=Fu(e,t,"");return ka(n)}var Ou=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Yy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zy=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 s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},zl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yy(e),n=Zy(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},$l=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$l(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=$l(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:$l(n.text)}}},_u=e=>Array.isArray(e)?e.map(t=>String(t)):[],jl=e=>{let t=new Set(_u(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(_u(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let p={action:l,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var eb=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}},tb=e=>e.map(t=>({...t,streaming:!1})),nb=e=>e.map(t=>({...t,status:"complete"})),$u=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?eb(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?tb(n.messages):void 0,artifacts:n.artifacts?nb(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)}}}};import{parse as $A,STR as zA,OBJ as jA}from"partial-json";function zu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function ju(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 Ul(e){let t=ju(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 Uu(e){let t=ju(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 ob=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vu(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=ob}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,f.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),w.appendChild(f);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-csat",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${d[G-1]}`),x.title=d[G-1],x.dataset.rating=String(G),x.innerHTML=`
|
|
39
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Dt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=a.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let T=a.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let T=a.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let M=parseFloat(T)||24,U=ae(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",2);U?(u.appendChild(U),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let T=a.agentIconSize??"40px";w.style.height=T,w.style.width=T,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let T=a.callToActionIconSize??"32px";g.style.height=T,g.style.width=T,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let M=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,M=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let U=parseFloat(T)||24,j=Math.max(U-M,8),A=ae(a.callToActionIconName,j,"currentColor",2);A?g.appendChild(A):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&Sn[a.position]?Sn[a.position]:Sn["bottom-right"],x="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",P="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?P:`${x} ${v}`,l||(n.style.zIndex=String(a.zIndex??Vt));let F="1px solid var(--persona-border, #e5e7eb)",k="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=a.border??F,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:k,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=a.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 Tu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Au(e),s=Su(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},kl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>El(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=El(e,n);return{instance:r,element:r.element}};var cy=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}},dy=(e,t)=>{if(!e)return null;let n=cy(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},py=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},uy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ll=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(":"))},Pl=320,Lu=320,fy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),my=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),hy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),yy=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=y("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ie("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},by=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:t}))}return n},Mu="\uE000",Eu="\uE001",vy=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${Mu}${r}:${w}${Eu}`,a=t.map((w,g)=>w.kind==="text"?w.text:s(g)).join(""),l=n(a);if(!t.every((w,g)=>w.kind==="text"||l.includes(s(g)))){e.replaceChildren(by(t,o));return}e.innerHTML=l;let d=new RegExp(`${Mu}${r}:(\\d+)${Eu}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let g=w;for(let v=d.exec(g.data);v;v=d.exec(g.data)){let x=t[Number(v[1])],P=g.splitText(v.index);P.data=P.data.slice(v[0].length),x?.kind==="mention"&&P.parentNode?.insertBefore(ms(x.ref,{readonly:!0,render:o}),P),g=P}}},wy=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=y("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Pl}px`,d.style.maxHeight=`${Lu}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),uy(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},xy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Ll(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Ll(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pl}px`,r.style.maxHeight=`${Lu}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}},Ay=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Ll(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ls=()=>{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},Sy=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ls};if(t){let r=t(o);if(r!==null)return r}return Ls()},Ty=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},ku=(e,t,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Il=(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},My=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=y("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let g=(v,x,P)=>{let F=Pt({icon:v,label:x,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",P),F};return o&&w.appendChild(g("copy","Copy message","copy")),a&&w.appendChild(g("volume-2","Read aloud","read-aloud")),r&&w.appendChild(g("thumbs-up","Upvote","upvote")),s&&w.appendChild(g("thumbs-down","Downvote","downvote")),w},Rl=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",g=d?.position??"below",v=Il(e.role,l),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=fy(e),F=e.content?.trim()??"",T=P.length>0&&F===ka,M=Qa(s?.widgetConfig?.features?.streamAnimation),U=s?.widgetConfig?.features?.streamAnimation?.plugins,j=e.role==="assistant"&&M.type!=="none"?vr(M.type,U):null,A=e.role==="assistant"&&j?.isAnimating?.(e)===!0,V=e.role==="assistant"&&j!==null&&(!!e.streaming||A);V&&j?.bubbleClass&&x.classList.add(j.bubbleClass);let K=document.createElement("div");K.classList.add("persona-message-content"),e.streaming&&K.classList.add("persona-content-streaming"),V&&j&&(j.containerClass&&K.classList.add(j.containerClass),K.style.setProperty("--persona-stream-step",`${M.speed}ms`),K.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let ne=V?Xa(e.content??"",M.buffer,j,e,!!e.streaming):e.content??"",D=()=>{let J=t({text:ne,message:e,streaming:!!e.streaming,raw:e.rawContent});return V&&j?.wrap==="char"?As(J,"char",e.id,{skipTags:j.skipTags}):V&&j?.wrap==="word"?As(J,"word",e.id,{skipTags:j.skipTags}):J},_=null;if(T?(_=document.createElement("div"),_.innerHTML=D(),_.style.display="none",K.appendChild(_)):e.contentSegments?.length?vy(K,e.contentSegments,J=>t({text:J,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):K.innerHTML=D(),V&&j?.useCaret&&!T&&F){let J=Ja(),fe=K.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=fe[fe.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(J,Ce.nextSibling);else{let ye=K.lastElementChild;ye?ye.appendChild(J):K.appendChild(J)}}if(u&&g==="inline"&&e.createdAt){let J=ku(e,d,"span");J.classList.add("persona-timestamp-inline");let fe=K.lastElementChild;fe?fe.appendChild(J):K.appendChild(J)}if(P.length>0){let J=wy(P,!T&&!!F,()=>{T&&_&&(_.style.display="")});J?x.appendChild(J):T&&_&&(_.style.display="")}let Y=gy(e);if(Y.length>0){let J=xy(Y);J&&x.appendChild(J)}let ge=my(e);if(ge.length>0){let J=Cy(ge);J&&x.appendChild(J)}let he=hy(e);if(he.length>0){let J=Ay(he);J&&x.appendChild(J)}let ce=e.contentSegments?.length?null:yy(e.contextMentions);if(ce&&x.appendChild(ce),x.appendChild(K),u&&g==="below"&&e.createdAt){let J=ku(e,d);J.classList.add("persona-mt-1"),x.appendChild(J)}let Z=e.role==="assistant"?dy(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(ne&&ne.trim()),fe=M.placeholder==="skeleton",Ce=fe&&M.buffer==="line"&&J;if(J)Ce&&x.appendChild(Ss());else if(fe)x.appendChild(Ss());else{let ye=Sy("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&x.appendChild(ye)}}if(Z&&e.stopReason&&!e.streaming&&(F||(K.style.display="none"),x.appendChild(py(e.stopReason,Z))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let J=My(e,o,r);x.appendChild(J)}if(!c||e.role==="system")return x;let te=y("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ie=Ty(p,e.role);return w==="right"||w==="left"&&e.role==="user"?te.append(x,ie):te.append(ie,x),te};var wr=new Set,Ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ky=(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(`
|
|
40
|
+
`):""},Pu=(e,t)=>{let n=wr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Wl=(e,t)=>{let n=e.reasoning,o=y("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??{},s=r.expandable!==!1,a=s&&wr.has(e.id),l=n.status!=="complete",p=ky(e,r.previewMaxLines??3),d=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",g=t?.reasoning??{},v=String(n.startedAt??Date.now()),x=()=>{let ge=y("span","");return ge.setAttribute("data-tool-elapsed",v),ge.textContent=Sa(n),ge},P=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:t??{},elapsed:Sa(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(u.textContent=P,c.appendChild(u)):P instanceof HTMLElement?c.appendChild(P):(u.textContent=w,c.appendChild(u));let F=y("span","persona-text-xs persona-text-persona-primary");F.textContent=cp(n),c.appendChild(F);let k=r.loadingAnimation??"none",T=g.activeTextTemplate,M=g.completeTextTemplate,U=l?T:M,j=P instanceof HTMLElement,A=(ge,he)=>{u.textContent="";let ce=Ta(ge,""),Z=0;for(let de of ce){let te=de.styles.length>0?(()=>{let ie=y("span",de.styles.map(J=>`persona-tool-text-${J}`).join(" "));return u.appendChild(ie),ie})():u;if(de.isDuration&&l)te.appendChild(x());else{let ie=de.isDuration?Sa(n):de.text;he?Z=go(te,ie,Z):te.appendChild(document.createTextNode(ie))}}};if(!j&&U)if(F.style.display="none",u.style.display="",l&&k!=="none"){let ge=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),k==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),A(U,!1)):(u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),A(U,!0))}else A(U,!1);else if(!j&&l&&k!=="none"){u.style.display="";let ge=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),k==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`);else{u.classList.add(`persona-tool-loading-${k}`),u.style.setProperty("--persona-tool-anim-duration",`${ge}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let he=u.textContent||w;u.textContent="",go(u,he,0)}n.status==="complete"&&(u.style.display="none")}else j||(n.status==="complete"?u.style.display="none":u.style.display="");let V=null;if(s){V=y("div","persona-flex persona-items-center");let he=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);he?V.appendChild(he):V.textContent=a?"Hide":"Show";let ce=y("div","persona-flex persona-items-center persona-ml-auto");ce.append(V),d.append(c,ce)}else d.append(c);let K=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(K.setAttribute("data-persona-collapsed-preview","reasoning"),K.style.display="none",K.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let ge=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});Ey(K,ge)||(K.textContent=p),K.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,K),o;let ne=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");ne.style.display=a?"":"none";let D=n.chunks.join(""),_=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return _.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),ne.appendChild(_),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),V){V.innerHTML="";let he=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);he?V.appendChild(he):V.textContent=a?"Hide":"Show"}ne.style.display=a?"":"none",K.style.display=a?"none":K.textContent||K.childNodes.length?"":"none"})(),o.append(d,K,ne),o};var xr=new Set,Ly=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Py=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
41
|
+
`);let r=uo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
+
`):""},Hl=(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)"},Iy=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Py(e,o?.previewMaxLines??3),a=n?dp(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=rl(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=rl(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},Iu=(e,t,n)=>{let o=xr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ae(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Bl=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("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 s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&xr.has(e.id),{summary:p,previewText:d,isActive:c}=Iy(e,t),u=y("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");u.type="button",a&&(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 w=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),x=()=>{let D=y("span","");return D.setAttribute("data-tool-elapsed",v),D.textContent=is(n),D},P=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:is(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(g.textContent=P,w.appendChild(g)):P instanceof HTMLElement?w.appendChild(P):(g.textContent=p,w.appendChild(g));let F=s.loadingAnimation??"none",k=o.activeTextTemplate,T=o.completeTextTemplate,M=c?k:T,U=P instanceof HTMLElement,j=(D,_)=>{g.textContent="";let Y=n.name?.trim()||"tool",ge=Ta(D,Y),he=0;for(let ce of ge){let Z=ce.styles.length>0?(()=>{let de=y("span",ce.styles.map(te=>`persona-tool-text-${te}`).join(" "));return g.appendChild(de),de})():g;if(ce.isDuration&&c)Z.appendChild(x());else{let de=ce.isDuration?is(n):ce.text;_?he=go(Z,de,he):Z.appendChild(document.createTextNode(de))}}};if(!U)if(c&&F!=="none"){let D=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),F==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),M&&j(M,!1);else if(g.classList.add(`persona-tool-loading-${F}`),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),F==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),M)j(M,!0);else{let _=g.textContent||p;g.textContent="",go(g,_,0)}}else M&&j(M,!1);let A=null;if(a){A=y("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",_=ae(l?"chevron-up":"chevron-down",16,D,2);_?A.appendChild(_):A.textContent=l?"Hide":"Show";let Y=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(A),u.append(w,Y)}else u.append(w);let V=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","tool"),V.style.display="none",V.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Ly(V,D)||(V.textContent=d),V.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,V),r;let K=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(K.style.display=l?"":"none",o.contentBackgroundColor&&(K.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(K.style.color=o.contentTextColor),o.contentPaddingX&&(K.style.paddingLeft=o.contentPaddingX,K.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(K.style.paddingTop=o.contentPaddingY,K.style.paddingBottom=o.contentPaddingY),n.name){let D=y("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,K.appendChild(D)}if(n.args!==void 0){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Arguments";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=uo(n.args),D.append(_,Y),K.appendChild(D)}if(n.chunks&&n.chunks.length){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Activity";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=n.chunks.join(""),D.append(_,Y),K.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Result";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=uo(n.result),D.append(_,Y),K.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,K.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),A){A.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",_=ae(l?"chevron-up":"chevron-down",16,D,2);_?A.appendChild(_):A.textContent=l?"Hide":"Show"}K.style.display=l?"":"none",V.style.display=l?"none":V.textContent||V.childNodes.length?"":"none"})(),r.append(u,V,K),r};var Oo=new Map,pi=e=>{let n=(e.startsWith($n)?e.slice($n.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)},Ru=e=>e?.approval!==!1?e?.approval:void 0,Wu=(e,t)=>{let n=Ru(t)?.detailsDisplay??"collapsed";return Oo.get(e)??n==="expanded"},Hu=(e,t,n)=>{let o=Ru(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 s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Bu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Wu(e,n);Hu(o,s,n),r.style.display=s?"":"none"};var ui=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.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 s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ae(p,20,d,2);c&&l.appendChild(c);let u=y("div","persona-flex-1 persona-min-w-0"),w=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",w.appendChild(g),!r){let A=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");A.setAttribute("data-approval-status",n.status),n.status==="approved"?(A.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",A.style.color="var(--persona-palette-colors-success-700, #15803d)",A.textContent="Approved"):n.status==="denied"?(A.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",A.style.color="var(--persona-palette-colors-error-700, #b91c1c)",A.textContent="Denied"):n.status==="timeout"&&(A.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",A.style.color="var(--persona-palette-colors-warning-700, #b45309)",A.textContent="Timeout"),w.appendChild(A)}u.appendChild(w);let x=n.toolType==="webmcp"||n.toolName.startsWith($n)?ts(n.toolName):void 0,P=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),F=!n.toolName,k=P||(F?n.description:`The assistant wants to use \u201C${x??pi(n.toolName)}\u201D.`),T=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=k,u.appendChild(T),n.reason){let A=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");A.setAttribute("data-approval-reason","true"),o?.reasonColor?A.style.color=o.reasonColor:o?.descriptionColor&&(A.style.color=o.descriptionColor);let V=y("span","persona-font-medium");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,A.appendChild(V),A.appendChild(document.createTextNode(n.reason)),u.appendChild(A)}let M=o?.detailsDisplay??"collapsed",U=!!n.description&&!F,j=U||!!n.parameters;if(M!=="hidden"&&j){let A=Wu(e.id,t),V=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");V.type="button",V.setAttribute("data-expand-header","true"),V.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(V.style.color=o.descriptionColor);let K=y("span");K.setAttribute("data-approval-details-label","true");let ne=y("span","persona-inline-flex persona-items-center");ne.setAttribute("data-approval-details-chevron","true"),V.append(K,ne),Hu(V,A,t),u.appendChild(V);let D=y("div");if(D.setAttribute("data-approval-details","true"),D.style.display=A?"":"none",U){let _=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(_.style.color=o.descriptionColor),_.textContent=n.description,D.appendChild(_)}if(n.parameters){let _=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(_.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(_.style.color=o.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=uo(n.parameters),D.appendChild(_)}u.appendChild(D)}if(r){let A=y("div","persona-flex persona-gap-2 persona-mt-2");A.setAttribute("data-approval-buttons","true");let V=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",V.style.color=o?.approveButtonTextColor??"#ffffff",V.setAttribute("data-approval-action","approve");let K=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);K&&(K.style.marginRight="4px",V.appendChild(K));let ne=document.createTextNode(o?.approveLabel??"Approve");V.appendChild(ne);let D=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");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 _=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);_&&(_.style.marginRight="4px",D.appendChild(_));let Y=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(Y),A.append(V,D),u.appendChild(A)}return a.append(l,u),s.appendChild(a),s};var Ry=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Du=(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))},_o=(e,t)=>{Du(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)},Wy=e=>e?.approval!==!1?e?.approval:void 0,Hy=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Oo.get(e)??n==="expanded"},Dl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},By=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith($n)?ts(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??pi(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=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Dy=e=>{let t=y("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=e.toolName?pi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Fy=(e,t,n,o,r,s,a)=>{let l=y("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&Hy(t.id,o),g=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",w?"true":"false"),x.setAttribute("aria-label",w?v:g)):x.setAttribute("data-static","true");let P=y("span","persona-approval-logo"),F=ae("shield-check",16,"currentColor",2);F&&P.appendChild(F),x.appendChild(P);let k=By(n,o);if(u){let V=y("span","persona-approval-toggle");V.setAttribute("aria-hidden","true");let K=ae("chevron-down",14,"currentColor",2);K&&V.appendChild(K),k.append(" "),k.appendChild(V)}x.appendChild(k),l.appendChild(x);let T=y("div","persona-approval-body");if(u){let V=y("div","persona-approval-details");if(V.setAttribute("data-role","params"),V.hidden=!w,d){let K=y("p","persona-approval-desc");o?.descriptionColor&&(K.style.color=o.descriptionColor),K.textContent=n.description,V.appendChild(K)}if(c){let K=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(K.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(K.style.color=o.parameterTextColor),K.textContent=uo(n.parameters),V.appendChild(K)}T.appendChild(V)}if(n.reason){let V=y("p","persona-approval-reason");o?.reasonColor?V.style.color=o.reasonColor:o?.descriptionColor&&(V.style.color=o.descriptionColor);let K=y("span","persona-approval-reason-label");K.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,V.append(K,document.createTextNode(n.reason)),T.appendChild(V)}let M=y("div","persona-approval-actions"),U=null,j=V=>{o?.approveButtonColor&&(V.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(V.style.color=o.approveButtonTextColor)},A=y("button","persona-approval-deny");if(A.type="button",A.setAttribute("data-action","deny"),o?.denyButtonColor&&(A.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(A.style.color=o.denyButtonTextColor),A.append(o?.denyLabel??"Deny"),a){let V=y("div","persona-approval-split"),K=y("button","persona-approval-primary");K.type="button",K.setAttribute("data-action","always"),j(K),K.append(o?.approveLabel??"Always allow",Dl("\u23CE"));let ne=y("button","persona-approval-caret");ne.type="button",ne.setAttribute("data-action","toggle-menu"),ne.setAttribute("aria-label","More options"),j(ne);let D=ae("chevron-down",15,"currentColor",2);D&&ne.appendChild(D),V.append(K,ne),M.append(V,A),A.append(Dl("Esc"));let _=y("div","persona-approval-menu"),Y=y("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",Dl("\u2318\u23CE")),_.appendChild(Y),U=Id({anchor:V,content:_,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,U),Y.addEventListener("click",()=>{_o(e,t.id),r()})}else{let V=y("button","persona-approval-primary persona-approval-primary--solo");V.type="button",V.setAttribute("data-action","allow"),j(V),V.append(o?.approveLabel??"Allow"),M.append(V,A)}return T.appendChild(M),l.appendChild(T),l.addEventListener("click",V=>{let K=V.target instanceof Element?V.target.closest("[data-action]"):null;if(!K)return;let ne=K.getAttribute("data-action");if(ne==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let _=D.hidden;D.hidden=!_,x.setAttribute("aria-expanded",_?"true":"false"),x.setAttribute("aria-label",_?v:g),Oo.set(t.id,_)}return}if(ne==="toggle-menu"){U?.toggle();return}if(ne==="always"){_o(e,t.id),r({remember:!0});return}if(ne==="allow"){_o(e,t.id),r();return}if(ne==="deny"){_o(e,t.id),s();return}}),l},Fu=()=>{let e=Ry();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let p=Wy(a);if(l.status!=="pending"){if(_o(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Dy(l)}Du(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Fy(e,o,l,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=w=>{Rd(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),_o(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])_o(e,o);e.latestPendingApprovalId=null}}};var Ps=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 Is=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 a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.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 Ny=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Oy=new Set(["step_start","execution_start"]),_y=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),$y=new Set(["step_complete","agent_turn_complete"]),Uy=new Set(["flow_complete","agent_complete"]),Nu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),_u=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,$o=(e,t)=>{let n=e[t];return _u(n)?n:void 0};function Fl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function zy(e,t){return typeof t.type=="string"?t.type:e}function jy(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 Vy(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 Ou(e){let t=$o(e,"result"),n=[$o(e,"tokens"),$o(e,"totalTokens"),t?$o(t,"tokens"):void 0,$o(e,"usage"),t?$o(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function qy(e){let t=$o(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function Ky(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=Ky){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:fi(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(!_u(n)){Nu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=zy(t,n),r=this.now();if(Ny.has(o)){this.startRun(r);return}if(Oy.has(o)){this.run||this.startRun(r);return}if(_y.has(o)){if(!Vy(o,n))return;let s=jy(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Fl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:fi(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if($y.has(o)){if(!this.run)return;let s=this.run,a=Ou(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+Fl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:fi(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Uy.has(o)){if(!this.run)return;let s=this.run,a=Ou(n),l=a??s.exactOutputTokens+Fl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:fi(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Nu.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:qy(n)??o-t.startedAt}};function Cr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Gy={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)"}},Qy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Xy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Jy=100;function Yy(e,t){let n={...Gy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Qy}function Zy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function eb(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"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function tb(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("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function nb(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 ob(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 rb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function sb(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 ab(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 s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Nl(e,t,n,o,r,s,a,l){let p=r.has(e.id),d=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Cr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=y("div",""),g=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);x&&v.appendChild(x);let P=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),F=o.timestampFormat??"relative";P.textContent=F==="relative"?Zy(e.timestamp,n):eb(e.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let T=Yy(e.type,o.badgeColors),M=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");M.style.backgroundColor=T.bg,M.style.color=T.text,M.style.borderColor=T.text+"50",M.textContent=e.type;let U=o.descriptionFields??Xy,j=tb(e.payload,U),A=null;j&&(A=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),A.textContent=j);let V=y("div","persona-flex-1 persona-min-w-0"),K=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),ne=ae("clipboard","12px","currentColor",1.5);return ne&&K.appendChild(ne),K.addEventListener("click",async D=>{D.stopPropagation(),await nb(ob(e)),K.innerHTML="";let _=ae("check","12px","currentColor",1.5);_&&K.appendChild(_),setTimeout(()=>{K.innerHTML="";let Y=ae("clipboard","12px","currentColor",1.5);Y&&K.appendChild(Y)},1500)}),g.appendChild(v),g.appendChild(P),k&&g.appendChild(k),g.appendChild(M),A&&g.appendChild(A),g.appendChild(V),g.appendChild(K),w.appendChild(g),p&&w.appendChild(ab(e,a,l)),w}}function $u(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return g();function g(){let v=u.classNames,x=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Cr(x,v?.panel);let P=[],F="",k="",T=null,M=[],U={},j=0,A=qa(),V=0,K=0,ne=!1,D=null,_=!1,Y=0,ge=new Set,he=new Map,ce="",Z="",de=null,te,ie,J,fe,Ce=null,ye=null,xe=null;function ve(){let R=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Q=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Cr(Q,v?.headerBar),a){ye=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",Ce=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ce.textContent="-- tok/s",xe=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),xe.style.display="none",xe.style.pointerEvents="none";let De=ye,Ht=xe,vt=()=>{if(!Ht.textContent)return;let Fs=De.getBoundingClientRect(),Kn=R.getBoundingClientRect();Ht.style.left=`${Fs.left-Kn.left}px`,Ht.style.top=`${Fs.bottom-Kn.top+4}px`,Ht.style.display="block"},Gt=()=>{Ht.style.display="none"};ye.addEventListener("mouseenter",vt),ye.addEventListener("mouseleave",Gt),ye.appendChild(Ce)}let se=y("div","persona-flex-1");te=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ee=y("option","");Ee.value="",Ee.textContent="All events (0)",te.appendChild(Ee),ie=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ie.type="button",ie.title="Copy All";let nt=ae("clipboard-copy","12px","currentColor",1.5);nt&&ie.appendChild(nt);let tt=y("span","persona-event-copy-all persona-text-xs");tt.textContent="Copy All",ie.appendChild(tt),ye&&Q.appendChild(ye),Q.appendChild(se),Q.appendChild(te),Q.appendChild(ie);let _e=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Cr(_e,v?.searchBar);let Je=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),q=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Je&&q.appendChild(Je),J=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Cr(J,v?.searchInput),J.type="text",J.placeholder="Search event payloads...",fe=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),fe.type="button",fe.style.display="none";let $e=ae("x","12px","currentColor",2);return $e&&fe.appendChild($e),_e.appendChild(q),_e.appendChild(J),_e.appendChild(fe),R.appendChild(Q),R.appendChild(_e),xe&&R.appendChild(xe),R}let Ae,Te=s.find(R=>R.renderEventStreamToolbar);Te?.renderEventStreamToolbar&&r?Ae=Te.renderEventStreamToolbar({config:r,defaultRenderer:()=>ve(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{F=Q,Xe(),le()},onSearchChange:Q=>{k=Q,Xe(),le()}})??ve():Ae=ve();let qe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");qe.style.display="none";function ze(){if(!a||!Ce||!ye)return;let R=a(),Q=rb(R);Ce.textContent=Q;let se=sb(R);xe&&(xe.textContent=se,se||(xe.style.display="none")),ye.setAttribute("aria-label",se?`Throughput: ${Q}, ${se}`:`Throughput: ${Q}`)}let Me=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Pe=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Pe.style.height="100%";let Ke=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Cr(Ke,v?.scrollIndicator),Ke.style.display="none",Ke.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Wt=ae(d,"14px","currentColor",2);Wt&&Ke.appendChild(Wt);let It=y("span","");It.textContent=c,Ke.appendChild(It);let qt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");qt.style.display="none",Me.appendChild(Pe),Me.appendChild(qt),Me.appendChild(Ke),x.setAttribute("tabindex","0"),x.appendChild(Ae),x.appendChild(qe),x.appendChild(Me);function xt(){let R=t.getAll(),Q={};for(let _e of R)Q[_e.type]=(Q[_e.type]||0)+1;let se=Object.keys(Q).sort(),Ee=se.length!==M.length||!se.every((_e,Je)=>_e===M[Je]),we=!Ee&&se.some(_e=>Q[_e]!==U[_e]),nt=R.length!==Object.values(U).reduce((_e,Je)=>_e+Je,0);if(!Ee&&!we&&!nt||(M=se,U=Q,!te))return;let tt=te.value;if(te.options[0].textContent=`All events (${R.length})`,Ee){for(;te.options.length>1;)te.remove(1);for(let _e of se){let Je=y("option","");Je.value=_e,Je.textContent=`${_e} (${Q[_e]||0})`,te.appendChild(Je)}tt&&se.includes(tt)?te.value=tt:tt&&(te.value="",F="")}else for(let _e=1;_e<te.options.length;_e++){let Je=te.options[_e];Je.textContent=`${Je.value} (${Q[Je.value]||0})`}}function Be(){let R=t.getAll();if(F&&(R=R.filter(Q=>Q.type===F)),k){let Q=k.toLowerCase();R=R.filter(se=>se.type.toLowerCase().includes(Q)||se.payload.toLowerCase().includes(Q))}return R}function ue(){return F!==""||k!==""}function Xe(){j=0,V=0,A.resume(),Ke.style.display="none"}function We(R){ge.has(R)?ge.delete(R):ge.add(R),de=R;let Q=Pe.scrollTop,se=A.isFollowing();_=!0,A.pause(),le(),Pe.scrollTop=Q,se&&A.resume(),_=!1}function me(){return ho(Pe,50)}function le(){K=Date.now(),ne=!1,ze(),xt();let R=t.getEvictedCount();R>0?(qe.textContent=`${R.toLocaleString()} older events truncated`,qe.style.display=""):qe.style.display="none",P=Be();let Q=P.length,se=t.getSize()>0;Q===0&&se&&ue()?(qt.textContent=k?`No events matching '${k}'`:"No events matching filter",qt.style.display="",Pe.style.display="none"):(qt.style.display="none",Pe.style.display=""),ie&&(ie.title=ue()?`Copy Filtered (${Q})`:"Copy All"),p&&!A.isFollowing()&&Q>j&&(V+=Q-j,It.textContent=c?`${c}${V>0?` (${V})`:""}`:"",Ke.style.display=""),j=Q;let Ee=t.getAll(),we=Ee.length>0?Ee[0].timestamp:0,nt=new Set(P.map(Je=>Je.id));for(let Je of ge)nt.has(Je)||ge.delete(Je);let tt=F!==ce||k!==Z,_e=he.size===0&&P.length>0;if(tt||_e||P.length===0){Pe.innerHTML="",he.clear();let Je=document.createDocumentFragment();for(let q=0;q<P.length;q++){let $e=Nl(P[q],q,we,u,ge,We,s,r);he.set(P[q].id,$e),Je.appendChild($e)}Pe.appendChild(Je),ce=F,Z=k,de=null}else{if(de!==null){let q=he.get(de);if(q&&q.parentNode===Pe){let $e=P.findIndex(De=>De.id===de);if($e>=0){let De=Nl(P[$e],$e,we,u,ge,We,s,r);Pe.insertBefore(De,q),q.remove(),he.set(de,De)}}de=null}let Je=new Set(P.map(q=>q.id));for(let[q,$e]of he)Je.has(q)||($e.remove(),he.delete(q));for(let q=0;q<P.length;q++){let $e=P[q];if(!he.has($e.id)){let De=Nl($e,q,we,u,ge,We,s,r);he.set($e.id,De),Pe.appendChild(De)}}}A.isFollowing()&&(Pe.scrollTop=Pe.scrollHeight)}function Re(){if(Date.now()-K>=Jy){D!==null&&(cancelAnimationFrame(D),D=null),le();return}ne||(ne=!0,D=requestAnimationFrame(()=>{D=null,le()}))}let Kt=(R,Q)=>{if(!ie)return;ie.innerHTML="";let se=ae(R,"12px","currentColor",1.5);se&&ie.appendChild(se);let Ee=y("span","persona-text-xs");Ee.textContent="Copy All",ie.appendChild(Ee),setTimeout(()=>{ie.innerHTML="";let we=ae("clipboard-copy","12px","currentColor",1.5);we&&ie.appendChild(we);let nt=y("span","persona-text-xs");nt.textContent="Copy All",ie.appendChild(nt),ie.disabled=!1},Q)},pt=async()=>{if(ie){ie.disabled=!0;try{let R;ue()?R=P:n?(R=await n(),R.length===0&&(R=t.getAll())):R=t.getAll();let Q=R.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),Kt("check",1500)}catch{Kt("x",1500)}}},mt=()=>{te&&(F=te.value,Xe(),le())},z=()=>{!J||!fe||(fe.style.display=J.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{k=J.value,Xe(),le()},150))},C=()=>{!J||!fe||(J.value="",k="",fe.style.display="none",T&&clearTimeout(T),Xe(),le())},$=()=>{if(_)return;let R=Pe.scrollTop,{action:Q,nextLastScrollTop:se}=Ka({following:A.isFollowing(),currentScrollTop:R,lastScrollTop:Y,nearBottom:me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=se,Q==="resume"?(A.resume(),V=0,Ke.style.display="none"):Q==="pause"&&(A.pause(),p&&(It.textContent=c,Ke.style.display=""))},h=R=>{let Q=Ga({following:A.isFollowing(),deltaY:R.deltaY,nearBottom:me(),resumeWhenNearBottom:!0});Q==="pause"?(A.pause(),p&&(It.textContent=c,Ke.style.display="")):Q==="resume"&&(A.resume(),V=0,Ke.style.display="none")},L=()=>{p&&(Pe.scrollTop=Pe.scrollHeight,A.resume(),V=0,Ke.style.display="none")},I=R=>{let Q=R.target;if(!Q||Q.closest("button"))return;let se=Q.closest("[data-event-id]");if(!se)return;let Ee=se.getAttribute("data-event-id");Ee&&We(Ee)},H=R=>{if((R.metaKey||R.ctrlKey)&&R.key==="f"){R.preventDefault(),J?.focus(),J?.select();return}R.key==="Escape"&&(J&&document.activeElement===J?(C(),J.blur(),x.focus()):o&&o())};ie&&ie.addEventListener("click",pt),te&&te.addEventListener("change",mt),J&&J.addEventListener("input",z),fe&&fe.addEventListener("click",C),Pe.addEventListener("scroll",$),Pe.addEventListener("wheel",h,{passive:!0}),Pe.addEventListener("click",I),Ke.addEventListener("click",L),x.addEventListener("keydown",H);function B(){T&&clearTimeout(T),D!==null&&(cancelAnimationFrame(D),D=null),ne=!1,he.clear(),ie&&ie.removeEventListener("click",pt),te&&te.removeEventListener("change",mt),J&&J.removeEventListener("input",z),fe&&fe.removeEventListener("click",C),Pe.removeEventListener("scroll",$),Pe.removeEventListener("wheel",h),Pe.removeEventListener("click",I),Ke.removeEventListener("click",L),x.removeEventListener("keydown",H)}return{element:x,update:Re,destroy:B}}}function Uu(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(g=>g===w||g.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let g=w;if(u.key===r)g=Math.min(w+1,s.length-1);else if(u.key===o)g=Math.max(w-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==w&&t.onSelect(g)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((g,v)=>{g.setAttribute("role","tab");let x=v===w;g.setAttribute("aria-selected",x?"true":"false"),g.tabIndex=x||w<0&&v===0?0:-1}),a){let g=(w>=0?u[w]:void 0)??u[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function zu(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=z=>({start:z===!1?!1:typeof z=="object"&&z?z.start!==!1:!0,end:z===!1?!1:typeof z=="object"&&z?z.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),_?.hide()};w&&w.addEventListener("click",()=>{g(),t.onDismiss?.()});let v=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let x=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");x.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&x.classList.add("persona-artifact-toolbar-document");let P=y("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let F=Pt({icon:"x",label:a});F.addEventListener("click",()=>{g(),t.onDismiss?.()});let k="rendered",T=$a({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:z=>{k=z==="source"?"source":"rendered",Kt()}}),M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=n?.documentToolbarShowCopyLabel===!0,j=n?.documentToolbarShowCopyChevron===!0,A=n?.documentToolbarCopyMenuItems,V=!!(j&&A&&A.length>0),K=null,ne,D=null,_=null;if(r&&(U||j)&&!V){if(ne=U?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),j){let z=ae("chevron-down",14,"currentColor",2);z&&ne.appendChild(z)}}else r&&V?(K=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ne=U?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Pt({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"}}),K.append(ne,D)):r?ne=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(ne=Pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&ne.classList.add("persona-hidden"));let Y=r?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),ge=r?Pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:a}),he=Pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let ce=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=e.features?.artifacts?.toolbarActions??[],de=()=>{let z=Me.find(L=>L.id===Pe)??Me[Me.length-1],C=z?.id??null,$=z?.artifactType==="markdown"?z.markdown??"":"",h=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:$,jsonPayload:h,id:C}},te=async()=>{let z=Me.find(C=>C.id===Pe)??Me[Me.length-1];try{await navigator.clipboard.writeText(xs(z))}catch{}};if(ne.addEventListener("click",async()=>{let z=n?.onDocumentToolbarCopyMenuSelect;if(z&&V){let{markdown:C,jsonPayload:$,id:h}=de();try{await z({actionId:"primary",artifactId:h,markdown:C,jsonPayload:$})}catch{}return}await te()}),D&&A?.length){let z=()=>v.closest("[data-persona-root]")??document.body,C=()=>{_=yr({items:A.map($=>({id:$.id,label:$.label})),onSelect:async $=>{let{markdown:h,jsonPayload:L,id:I}=de(),H=n?.onDocumentToolbarCopyMenuSelect;try{H?await H({actionId:$,artifactId:I,markdown:h,jsonPayload:L}):$==="markdown"||$==="md"?await navigator.clipboard.writeText(h):$==="json"||$==="source"?await navigator.clipboard.writeText(L):await navigator.clipboard.writeText(h||L)}catch{}},anchor:K??D,position:"bottom-right",portal:z()})};v.isConnected?C():requestAnimationFrame(C),D.addEventListener("click",$=>{$.stopPropagation(),_?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Kt()}),ge.addEventListener("click",()=>{g(),t.onDismiss?.()});let ie=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)x.replaceChildren(),K?M.append(K,Y,ge):M.append(ne,Y,ge),M.insertBefore(ce,ge),M.insertBefore(he,ge),x.append(T.element,ie,M);else{let z=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");z.append(ne,ce,he,F),x.appendChild(P),x.appendChild(z)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let J=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&J.style.setProperty("--persona-artifact-tab-fade-size",p);let fe=e.features?.artifacts?.renderTabBar,Ce=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Uu(J,{onSelect:z=>t.onSelect(Me[z].id)}),xe=z=>{let C=z.scrollWidth-z.clientWidth,$=C>1,h=Math.abs(z.scrollLeft);z.classList.toggle("persona-artifact-tab-fade-start",c&&$&&h>1),z.classList.toggle("persona-artifact-tab-fade-end",u&&$&&h<C-1)},ve=0,Ae=()=>{if(ve)return;let z=()=>{ve=0,xe(J)};ve=typeof requestAnimationFrame=="function"?requestAnimationFrame(z):setTimeout(z,0)};J.addEventListener("scroll",()=>Ae(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>xe(J)).observe(J);let Te=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),qe=()=>{Te.scrollLeft=0},ze=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(qe):setTimeout(qe,0)};if(l){for(let z of[J,Ce])z.style.paddingLeft=l,z.style.paddingRight=l;Te.style.padding=l}v.appendChild(x),v.appendChild(J),v.appendChild(Ce),v.appendChild(Te);let Me=[],Pe=null,Ke=!1,Wt=!1,It=!0,qt=!1,xt=null,Be="",ue=null,Xe=!1,We=z=>z.artifactType==="markdown"&&!!z.file||r?k:"rendered",me=z=>{r||(z&&!Xe?(x.insertBefore(T.element,P),Xe=!0):!z&&Xe&&(T.element.remove(),Xe=!1))},le=()=>Pe&&Me.find(z=>z.id===Pe)||Me[Me.length-1],Re=()=>{let z=vs(le());if(!z){ce.replaceChildren();return}let C=Z.filter($=>$.visible===void 0||$.visible(z)).map($=>br($,{documentChrome:r,onClick:()=>{let h=vs(le());if(h)try{Promise.resolve($.onClick(h)).catch(()=>{})}catch{}}}));ce.replaceChildren(...C)},Kt=()=>{Re();let z=r&&Me.length<=1,C=!!fe;if(J.classList.toggle("persona-hidden",z||C),Ce.classList.toggle("persona-hidden",z||!C),C&&fe){let L=Me.map(I=>I.id).join("|")+" "+(Pe??"");if(L!==Be){Be=L;let I=fe({records:Me,selectedId:Pe,onSelect:t.onSelect});Ce.firstElementChild!==I&&Ce.replaceChildren(I)}}else{ye.beforeRender(),J.replaceChildren();let L=[],I=-1;for(let[H,B]of Me.entries()){let R=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");R.type="button";let Q=B.artifactType==="markdown"?B.file:void 0,se=Q?Ln(Q.path):B.title||B.id.slice(0,8),Ee=Q?.path||B.title||se;R.textContent=se,R.title=Ee,R.setAttribute("aria-label",Ee),B.id===Pe&&(R.classList.add("persona-bg-persona-container","persona-border-persona-border"),I=H),R.addEventListener("click",()=>t.onSelect(B.id)),J.appendChild(R),L.push(R)}if(ye.render(L,I),I>=0&&Pe!==xt){xt=Pe;let H=L[I];typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",inline:"nearest"})}xe(J)}let $=Pe&&Me.find(L=>L.id===Pe)||Me[Me.length-1];if(!$){Te.replaceChildren(),ue=null,me(!1);return}let h=$.artifactType==="markdown"?$.file:void 0;if(me(!!h),r){let L=h?fo(h):$.artifactType==="markdown"?"MD":$.component??"Component",I=($.title||"Document").trim(),H=h?Ln(h.path):I.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${H} \xB7 ${L}`}else P.textContent=h?Ln(h.path):s;ue?(ue.el.parentElement!==Te&&Te.replaceChildren(ue.el),ue.update($)):(ue=ja($,{config:e,resolveViewMode:We}),Te.replaceChildren(ue.el)),Te.classList.toggle("persona-artifact-content-flush",!!Te.querySelector(".persona-code-pre"))},pt=()=>{let z=Me.length>0;if(v.classList.toggle("persona-hidden",!z),w){let h=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;z&&h&&Ke?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},mt=()=>{qt=!1,Kt(),pt()};return{element:v,backdrop:w,update(z){let C=z.selectedId??z.artifacts[z.artifacts.length-1]?.id??null,$=C!==Pe;Me=z.artifacts,Pe=C,Me.length>0&&(Ke=!0),qt=!0,It&&mt(),$&&qe()},setMobileOpen(z){Ke=z,!z&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):pt()},setExpanded(z){z!==Wt&&(Wt=z,ze());let C=ae(z?"minimize":"maximize",16,"currentColor",2);C&&he.replaceChildren(C);let $=z?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",$),he.title=$},setExpandToggleVisible(z){he.classList.toggle("persona-hidden",!z)},setCopyButtonVisible(z){r||ne.classList.toggle("persona-hidden",!z)},setCustomActions(z){Z=z,Re()},setTabFade(z){let C=d(z);C.start===c&&C.end===u||(c=C.start,u=C.end,xe(J))},setRenderTabBar(z){z!==fe&&(fe=z,Be="",Kt())},setVisible(z){z!==It&&(It=z,z&&qt&&mt())}}}function Yt(e){return e?.features?.artifacts?.enabled===!0}function ju(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"),!Yt(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 ib(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 Vu=["panel","seamless","detached"];function Ol(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Vu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _l(e){return!e||!Yt(e)?!1:Ol(e)==="detached"}function Ws(e,t){if(!Yt(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"),ib(e),ju(e,t);return}let n=t.features?.artifacts?.layout,o=Ol(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 s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):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"),ju(e,t)}function Hs(e,t){for(let l of Vu)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"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=Ol(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function qu(e,t){return!t||!Yt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var lb=new Set(["__proto__","prototype","constructor"]),cb=new Set(["collapsed","card","panel","inline"]),Ku=new Set(["markdown","component"]),db=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Uo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mi=e=>!lb.has(e),$l=e=>typeof e=="string"&&cb.has(e),zo=e=>Object.keys(e).length>0;function In(e,t,n,o){e.push({path:t,code:n,message:o})}var pb="Ignored because this key is not part of the persisted preference schema.",gi="Ignored an unsupported value.",ub="Expected collapsed, panel, or inline.",fb='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gu={kind:"mode",message:gi},Ar={kind:"string",message:"Expected a CSS length string."},qn={kind:"boolean"},gb={paneWidth:Ar,paneMaxWidth:Ar,paneMinWidth:Ar,expandedPanelWidth:Ar,resizableMinWidth:Ar,resizableMaxWidth:Ar,expandLauncherPanelWhenOpen:qn,resizable:qn},mb={kind:"object",message:"Expected a preference object.",children:{showToolCalls:qn,showReasoning:qn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:gi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:gi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:gi},expandable:qn,grouped:qn}},reasoningDisplay:{kind:"object",children:{expandable:qn,activePreview:qn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gu,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gu,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Ku,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Ku}}},filePreview:{kind:"object",children:{enabled:qn}},layout:{kind:"object",children:gb}}}}};function Qu(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:In(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:In(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:In(o,n,"invalid_value",t.message);case"mode":return $l(e)?gn(e):In(o,n,"invalid_value",t.message);case"modeMap":{if(!Uo(e))return In(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let p=r?a:rr(a);mi(a)&&(r?r.has(a):db.test(p))?$l(l)?s[p]=gn(l):In(o,`${n}.${a}`,"invalid_value",ub):In(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":fb)}return zo(s)?s:void 0}case"object":{if(t.bareMode&&$l(e))return gn(e);if(!Uo(e))return In(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!mi(l)||!r.includes(l))&&In(o,s(l),"unknown_key",pb);let a={};for(let l of r){let p=t.children[l],d=Qu(e[l],p,s(l),o);if(p.deprecated&&e[l]!==void 0&&In(o,s(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,u=a[c];a[c]=Uo(u)&&Uo(d)?{...u,...d}:d}return zo(a)?a:void 0}}}function hb(e){let t=[];return{preferences:(e===null?void 0:Qu(e,mb,"",t))??{},issues:t}}function Sr(e){if(Array.isArray(e))return e.map(Sr);if(!Uo(e))return e;let t={};for(let[n,o]of Object.entries(e))mi(n)&&o!==void 0&&(t[n]=Sr(o));return t}function Xu(e,t){let n=Sr(e);for(let[o,r]of Object.entries(t)){if(!mi(o)||r===void 0)continue;let s=n[o];n[o]=Uo(s)&&Uo(r)?Xu(s,r):Sr(r)}return n}function yb(e){let t={},n;for(let r of e){let s=hb(r).preferences;n=Ju(n,s.artifacts?.display),t=Xu(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function bb(e,t){if(t===void 0)return e===void 0?void 0:Sr(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},s={...o?{default:o}:{},...zo(r)?{byMediaType:r}:{}};return zo(s)?s:void 0}function Ju(e,t){if(t===void 0)return e===void 0?void 0:Sr(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},s=bb(n.files,t.files),a={...o?{default:o}:{},...zo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return zo(a)?a:void 0}function vb(e={},t){let n=yb(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??{},s={...r};if(n.artifacts.display!==void 0){let a=Ju(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ul(e){let t=e.preferences;return!t||!zo(t)?e:{...e,features:vb(e.features??{},[t])}}function wb(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 xb(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 Cb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Ab(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function zl(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 s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Yu(e,t,n,o,r,s){let a=wb(r,200),l=Ab(t,n,o,200);l=Math.max(a,l);let p=xb(s);return p!==null&&(l=Math.min(l,p)),Cb(e,a,l)}var Zu={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"}},jl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Zu[a]??Zu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),d=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=y("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let x=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${t.id}-${a}-${v.name}`;let P=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=v.label,x.appendChild(P);let F=v.type??"text",k;F==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=F),k.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",k.id=`${t.id}-${a}-${v.name}`,k.name=v.name,k.placeholder=v.placeholder??"",v.required&&(k.required=!0),x.appendChild(k),c.appendChild(x)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let x=n.formEndpoint??"/form",P=new FormData(c),F={};P.forEach((k,T)=>{F[T]=k}),F.type=a,g.disabled=!0,w.textContent="Submitting\u2026";try{let k=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let T=await k.json();w.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(k){w.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Vl=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(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ql=new Vl;var ef=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sb=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),tf=(e,t,n)=>{if(!ef(e)||!ef(t)||Sb.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=tf(e[r],t[r],s)}return o};function nf(e,t){let n=tf(e,t,"");return Ha(n)}var of=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Tb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Mb=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 s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Gl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Tb(e),n=Mb(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Kl=e=>typeof e=="string"?e:e==null?"":String(e),Bs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Kl(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Kl(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:Kl(n.text)}}},rf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ql=e=>{let t=new Set(rf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(rf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.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=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let p={action:l,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var Eb=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}},kb=e=>e.map(t=>({...t,streaming:!1})),Lb=e=>e.map(t=>({...t,status:"complete"})),sf=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Eb(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?kb(n.messages):void 0,artifacts:n.artifacts?Lb(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)}}}};import{parse as hS,STR as yS,OBJ as bS}from"partial-json";function af(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Vn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function lf(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 Xl(e){let t=lf(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 cf(e){let t=lf(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 Pb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function df(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=Pb}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,g.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,g.appendChild(x),w.appendChild(g);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let F=[];for(let j=1;j<=5;j++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${j} star${j>1?"s":""}: ${d[j-1]}`),A.title=d[j-1],A.dataset.rating=String(j),A.innerHTML=`
|
|
43
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
44
44
|
<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>
|
|
45
45
|
</svg>
|
|
46
|
-
`,x.addEventListener("click",()=>{u=G,B.forEach((j,U)=>{let oe=U<G;j.classList.toggle("selected",oe),j.setAttribute("aria-checked",U===G-1?"true":"false")})}),B.push(x),R.appendChild(x)}w.appendChild(R);let L=null;if(p){let G=document.createElement("div");G.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),G.appendChild(L),w.appendChild(G)}let E=document.createElement("div");E.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let G=L?.value.trim()||void 0;await t(u,G),c.remove()}catch(G){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",G)}}),E.appendChild(M),E.appendChild(_),w.appendChild(E),c.appendChild(w),c}function qu(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:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let R=document.createElement("p");R.className="persona-feedback-subtitle",R.textContent=r,v.appendChild(R),f.appendChild(v);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=c,L.appendChild(E),L.appendChild(M);let _=document.createElement("div");_.className="persona-feedback-numbers";let G=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{w=F,G.forEach((X,me)=>{X.classList.toggle("selected",me===F),X.setAttribute("aria-checked",me===F?"true":"false")})}),G.push($),_.appendChild($)}B.appendChild(L),B.appendChild(_),f.appendChild(B);let x=null;if(p){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),f.appendChild(F)}let j=document.createElement("div");j.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=l,U.addEventListener("click",()=>{n?.(),u.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(w===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let F=x?.value.trim()||void 0;await t(w,F),u.remove()}catch(F){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),j.appendChild(U),j.appendChild(oe),f.appendChild(j),u.appendChild(f),u}var xr="persona-chat-history",rb=30*1e3,sb=641,ab={"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 ib(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 s=ab[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{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 li(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 lb(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 cb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Vl=e=>!e||typeof e!="object"?{}:{...e},Ku=e=>e.map(t=>({...t,streaming:!1})),Gu=(e,t,n)=>{let o=e?.markdown?ca(e.markdown):null,r=da(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."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Fn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?bd(a):a,u=o(c);d=r&&p?r(u):u}else d=oo(a);return d}};function Qu(e){let t=h("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)",s=e?.iconStrokeWidth??.5,a=ie(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=h("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var db=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},pb=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:db(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Xu=(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=ka(t),r=o.features;o=Dl(o);let s=_l.getForInstance(o.plugins),{plugin:a,teardown:l}=bu();o.components&&zn.registerAll(o.components);let p=Ou(),c=o.persistState===!1?null:o.storageAdapter??$u(),u={},w=null,f=!1,v=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:m,open:b}=g;return b&&(f=!0),m}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")w=i.then(g=>v(g??{messages:[],metadata:{}}));else{let m=v(i??{messages:[],metadata:{}});m.metadata&&(u=Vl(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=v({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let C=()=>u,R=i=>{u=i({...u})??{},Si()},B=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick],E=jl({parsers:B,handlers:L,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,G=o.autoFocusInput??!1,x=_,j=M,U=o.layout?.header?.layout,oe=!1,F=()=>vs(o),$=()=>M||F(),X=F()?!1:M?_:!0,me=!1,he=null,Ae=()=>{me=!0,he&&clearTimeout(he),he=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Z=Gu(o,E,Ae),ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Y=o.features?.scrollToBottom??{},pe=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ve=le?new As(ye):null,je=o.features?.eventStream?.maxEvents??2e3,Me=le?new Cs(je,ve):null,De=le?new Ss:null,Qe=null,Ve=!1,Te=null,Le=0;ve?.open().then(()=>Me?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Xe={onCopy:i=>{p.emit("message:copy",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},It=i=>i==="idle"?Ht.idleText??Lt.idle:i==="connecting"?Ht.connectingText??Lt.connecting:i==="connected"?Ht.connectedText??Lt.connected:i==="error"?Ht.errorText??Lt.error:i==="paused"?Ht.pausedText??Lt.paused:i==="resuming"?Ht.resumingText??Lt.resuming:Lt[i];function qt(i,g,m,b){if(b==="idle"&&m.idleLink){i.textContent="";let A=document.createElement("a");A.href=m.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=g,A.style.color="inherit",A.style.textDecoration="none",i.appendChild(A)}else i.textContent=g}let xt=au({config:o,showClose:$()}),{wrapper:He,panel:de,pillRoot:et}=xt.shell,Ie=xt.panelElements,{container:fe,body:se,messagesWrapper:Pe,suggestions:it,textarea:ue,sendButton:Ce,sendButtonWrapper:te,composerForm:S,statusText:D,introTitle:y,introSubtitle:P,closeButton:T,iconHolder:I,headerTitle:q,headerSubtitle:H,header:z,footer:J,actionsRow:qe,rightActions:Re}=Ie,Je=Ie.leftActions,rt=Ie.setSendButtonMode,V=Ie.micButton,_e=Ie.micButtonWrapper,be=Ie.attachmentButton,$e=Ie.attachmentButtonWrapper,Fe=Ie.attachmentInput,Rt=Ie.attachmentPreviewsContainer;fe.classList.add("persona-relative"),se.classList.add("persona-relative");let di=12,go=()=>Y.label??"",Ls=()=>Y.iconName??"arrow-down",Ps=()=>Y.enabled!==!1,sn=()=>pe.mode??"anchor-top",Un=()=>sn()==="follow"||sn()==="anchor-top"&&Rr,Yl=()=>pe.anchorTopOffset??16,cf=()=>pe.restorePosition??"bottom",Zl=()=>pe.pauseOnInteraction===!0,ec=()=>pe.showActivityWhilePinned!==!1,tc=()=>pe.announce===!0,Tt=h("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");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Ar=h("span","persona-flex persona-items-center"),pi=h("span",""),mo=h("span","");mo.setAttribute("data-persona-scroll-to-bottom-count",""),mo.style.display="none",Tt.append(Ar,pi,mo),fe.appendChild(Tt);let Vn=h("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",se.appendChild(Vn);let ho=h("div","persona-sr-only");ho.setAttribute("aria-live","polite"),ho.setAttribute("aria-atomic","true"),ho.setAttribute("role","status"),ho.setAttribute("data-persona-live-region",""),Object.assign(ho.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(ho);let Sr=null,Is=null,nc=i=>{!tc()||!i||(Is=i,Sr===null&&(Sr=setTimeout(()=>{Sr=null,Is&&tc()&&(ho.textContent=Is),Is=null},400)))},_o=()=>{let g=J.style.display==="none"?0:J.offsetHeight;Tt.style.bottom=`${g+di}px`};_o();let oc=()=>{let i=!!go();Tt.setAttribute("aria-label",go()||"Jump to latest"),Tt.title=go(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ar.innerHTML="";let g=ie(Ls(),"14px","currentColor",2);g?(Ar.appendChild(g),Ar.style.display=""):Ar.style.display="none",pi.textContent=go(),pi.style.display=i?"":"none"};oc();let Ct=null,Zt=null,rc=null,sc=s.find(i=>i.renderHeader);if(sc?.renderHeader){let i=sc.renderHeader({config:o,defaultRenderer:()=>{let g=Ho({config:o,showClose:$()});return ws(fe,g,o),g.header},onClose:()=>dt(!1,"user")});if(i){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),z=i,xt.header.element=i)}}let ui=()=>{if(!Me)return;if(Ve=!0,!Qe&&Me&&(Qe=Au({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Tr(),config:o,plugins:s,getThroughput:()=>De?.getMetric()??{status:"idle"}})),Qe&&(se.style.display="none",J.parentNode?.insertBefore(Qe.element,J),Qe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(m=>m&&tt.classList.add(m))}let i=()=>{if(!Ve)return;let g=Date.now();g-Le>=200&&(Qe?.update(),Le=g),Te=requestAnimationFrame(i)};Le=0,Te=requestAnimationFrame(i),tn(),p.emit("eventStream:opened",{timestamp:Date.now()})},Tr=()=>{if(Ve){if(Ve=!1,Qe&&Qe.element.remove(),se.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&tt.classList.remove(g))}Te!==null&&(cancelAnimationFrame(Te),Te=null),tn(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){let i=o.features?.eventStream?.classNames,g="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=h("button",g),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let m=ie("activity","18px","currentColor",1.5);m&&tt.appendChild(m);let b=Ie.clearChatButtonWrapper,A=Ie.closeButtonWrapper,k=b||A;k&&k.parentNode===z?z.insertBefore(tt,k):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}let df=i=>{let g=o.attachments;if(!g?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let A=i.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(m,A):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let A=h("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??_n).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(A)}},ac=s.find(i=>i.renderComposer);if(ac?.renderComposer){let i=o.composer,g=ac.renderComposer({config:o,defaultRenderer:()=>ni({config:o}).footer,onSubmit:m=>{if(!O||O.isStreaming())return;let b=m.trim(),A=Ct?.hasAttachments()??!1;if(!b&&!A)return;Dc();let k;A&&(k=[],k.push(...Ct.getContentParts()),b&&k.push(ar(b))),O.sendMessage(b,{contentParts:k}),A&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{rc?.()}:void 0});g&&(xt.replaceComposer(g),J=xt.composer.footer)}let pf=i=>{let g=(...ge)=>{for(let re of ge){let we=i.querySelector(re);if(we)return we}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),A=i.querySelector("[data-persona-composer-submit]"),k=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");m&&(S=m),b&&(ue=b),A&&(Ce=A),k&&(V=k,_e=k.parentElement),Q&&(D=Q);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(it=N);let K=g("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(be=K,$e=K.parentElement),Fe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Rt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(qe=ae),Je=g(".persona-widget-composer__left-actions")};df(J),pf(J);let qn=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(qn&&(Pe.style.maxWidth=qn,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%"),qn&&S&&!F()&&(S.style.maxWidth=qn,S.style.marginLeft="auto",S.style.marginRight="auto"),qn&&it&&!F()&&(it.style.maxWidth=qn,it.style.marginLeft="auto",it.style.marginRight="auto"),qn&&Rt&&!F()&&(Rt.style.maxWidth=qn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Rt){Ct=as.fromConfig(o.attachments),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=Qu(i);fe.appendChild(g)}let uf=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&ue&&(Zt=fp({config:o,textarea:ue,anchor:S??ue,getMessages:()=>O.getMessages(),liveRegionHost:fe}),Zt)){let i=ue;i.parentElement?.insertBefore(Zt.contextRow,i);let g=Zt.affordanceButtons;for(let m=g.length-1;m>=0;m--){let b=g[m];Je?Je.insertBefore(b,Je.firstChild):S?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Pe;case"footer-top":return it;case"composer":return S;case"footer-bottom":return D;default:return null}},m=(b,A)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")z.insertBefore(A,z.firstChild);else if(b==="header-right")z.appendChild(A);else{let k=z.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(A,k.nextSibling):z.appendChild(A)}break;case"body-top":{let k=se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");k?k.replaceWith(A):se.insertBefore(A,se.firstChild);break}case"body-bottom":se.appendChild(A);break;case"footer-top":it.replaceWith(A);break;case"footer-bottom":D.replaceWith(A);break;default:break}};for(let[b,A]of Object.entries(i))if(A)try{let k=A({config:o,defaultContent:()=>g(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})();let ic=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let k=m.getAttribute("data-bubble-type");if(k==="reasoning")hr.has(A)?hr.delete(A):hr.add(A),pu(A,b);else if(k==="tool")yr.has(A)?yr.delete(A):yr.add(A),uu(A,b,o);else if(k==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=Bo.get(A)??N;Bo.set(A,!K),hu(A,b,o)}wo.delete(A)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let m=Pe.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),k=$p(A);!k||k===A||(g.setData("text/plain",k),i.preventDefault())});let fi=new Map,lc=null,cc="idle",ff={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},gf=(i,g)=>{let{icon:m,label:b}=ff[g];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",g==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",g!=="idle"),i.classList.toggle("persona-message-action-loading",g==="loading");let A=ie(m,14,"currentColor",2);A&&(i.innerHTML="",i.appendChild(A))},dc=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;gf(g,b&&b===lc?cc:"idle")})};Pe.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let A=b.getAttribute("data-actions-for");if(!A)return;let k=m.getAttribute("data-action");if(k==="copy"){let N=O.getMessages().find(K=>K.id===A);if(N&&Xe.onCopy){let K=N.content||"";navigator.clipboard.writeText(K).then(()=>{m.classList.add("persona-message-action-success");let ae=ie("check",14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ge=ie("copy",14,"currentColor",2);ge&&(m.innerHTML="",m.appendChild(ge))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),Xe.onCopy(N)}}else if(k==="read-aloud")O.toggleReadAloud(A);else if(k==="upvote"||k==="downvote"){let N=(fi.get(A)??null)===k,K=k==="upvote"?"thumbs-up":"thumbs-down";if(N){fi.delete(A),m.classList.remove("persona-message-action-active");let ae=ie(K,14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae))}else{let ae=k==="upvote"?"downvote":"upvote",ge=b.querySelector(`[data-action="${ae}"]`);if(ge){ge.classList.remove("persona-message-action-active");let nt=ie(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ge.innerHTML="",ge.appendChild(nt))}fi.set(A,k),m.classList.add("persona-message-action-active");let re=ie(K,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(re)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=O.getMessages().find(pt=>pt.id===A);Ue&&Xe.onFeedback&&Xe.onFeedback({type:k,messageId:Ue.id,message:Ue})}}}),Pe.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let k=m.getAttribute("data-approval-action");if(!k)return;let Q=k==="approve"?"approved":"denied",K=O.getMessages().find(ge=>ge.id===A);if(!K?.approval)return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?O.resolveWebMcpApproval(A,Q):O.resolveApproval(K.approval,Q)});let Ye=null,Mr=null,Er=()=>{},kr="none",Rs=null,mn={artifacts:[],selectedId:null},Ln=!1,hn=!1,Lr=!1,$o=!1,pc=()=>$o||mn.artifacts.some(i=>ro(o.features?.artifacts,i)==="panel"),Ws=()=>mn.artifacts.length>0&&!Ln&&pc(),lt={current:null},gi=(i,g)=>{let m=O.getArtifactById(g),b=m?.markdown,A=m?.title||"artifact",k=m?.file,Q=m?.artifactType??"markdown";if(!b){let ae=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let re=O.getMessages().find(we=>we.id===ae);if(re?.rawContent)try{let we=JSON.parse(re.rawContent);b=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(k=we.props.file),!m&&typeof we?.props?.artifactType=="string"&&(Q=we.props.artifactType)}catch{}}}return{markdown:b,title:A,file:k,artifactType:Q}};Pe.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:Q,file:N}=gi(m,b);if(!k)return;let{filename:K,mime:ae,content:ge}=Ap({title:Q,markdown:k,file:N}),re=new Blob([ge],{type:ae}),we=URL.createObjectURL(re),Ue=document.createElement("a");Ue.href=we,Ue.download=K,Ue.click(),URL.revokeObjectURL(we)}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let A=m.closest("[data-artifact-inline]"),k=A?null:m.closest("[data-open-artifact]"),Q=A?A.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,K=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===b);if(!K)return;let{markdown:ae,title:ge,file:re,artifactType:we}=gi(m,Q??""),Ue={artifactId:Q,title:ge,artifactType:we,markdown:ae,file:re};try{Promise.resolve(K.onClick(Ue)).catch(()=>{})}catch{}}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let A=O.getArtifactById(b),k="";if(A)k=fs(A);else{let{markdown:Q,file:N,artifactType:K}=gi(m,b);K==="markdown"&&(k=fs({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...N?{file:N}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let Q=ie("check",16,"currentColor",2);Q&&(m.replaceChildren(Q),setTimeout(()=>{let N=ie("copy",16,"currentColor",2);N&&m.replaceChildren(N)},1500))}).catch(()=>{})}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(Ln=!1,$o=!0,hn=!0,Lr=!0,O.selectArtifact(b),Pn())}),Pe.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let m=g.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),Ln=!1,$o=!0,O.selectArtifact(b),Pn())}),Pe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let zo=Ie.composerOverlay,jo=(i,g,m)=>{let b=g.trim();if(!b||!lt.current)return;let A=i.getAttribute("data-tool-call-id")??"",k=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:k,source:m.source},bubbles:!0,composed:!0})),rr(zo,A);let Q=lt.current.getMessages().find(N=>N.toolCall?.id===A);Q?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(Q,m.structured??b):lt.current.sendMessage(b)},yo=i=>{let g=lt.current;if(!g)return;let m=i.getAttribute("data-tool-call-id")??"",b=g.getMessages().find(A=>A.toolCall?.id===m);b&&g.persistAskUserQuestionProgress(b,{answers:fa(i,b),currentIndex:fn(i)})},uc=i=>Object.entries(i).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),mi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=fn(i),m=or(i);if(g>=m-1)return;let b=lt.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ma(i,b,o,g+1),yo(i))};zo.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;let A=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),A==="dismiss"){let k=b.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k);let Q=lt.current?.getMessages().find(N=>N.toolCall?.id===k);Q?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Q),lt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(A==="pick"){let k=m.getAttribute("data-option-label");if(!k)return;let Q=b.getAttribute("data-multi-select")==="true",N=so(b);if(N&&Q){let K=Po(b)[fn(b)],ae=new Set(Array.isArray(K)?K:[]);ae.has(k)?ae.delete(k):ae.add(k),ao(b,Array.from(ae)),yo(b);return}if(N){ao(b,k),yo(b),mi(b);return}if(Q){let K=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",K?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!K);let ae=b.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=Xi(b).length===0);return}jo(b,k,{source:"pick",values:[k]});return}if(A==="submit-multi"){let k=Xi(b);if(k.length===0)return;jo(b,k.join(", "),{source:"multi",values:k});return}if(A==="open-free-text"){let k=b.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let Q=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(so(b)){ao(b,Q.trim()),yo(b),mi(b);return}jo(b,Q,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let re=Po(b)[fn(b)];(typeof re!="string"||re!==K)&&ao(b,K)}let ae=A==="next"?1:-1,ge=fn(b)+ae;ma(b,Q,o,ge),yo(b);return}if(A==="submit-all"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&ao(b,K);let ae=fa(b,Q);lt.current.persistAskUserQuestionProgress(Q,{answers:ae,currentIndex:fn(b)});let ge=uc(ae);jo(b,ge||"(submitted)",{source:"submit-all",structured:ae});return}if(A==="skip"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(we=>we.toolCall?.id===k);if(!Q)return;let N=so(b),K=fn(b),ae=or(b),ge=K>=ae-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k),Q.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(Q),lt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}ao(b,"");let re=b.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),ge){let we=fa(b,Q),Ue=uc(we);jo(b,Ue||"(skipped)",{source:"submit-all",structured:we});return}ma(b,Q,o,K+1),yo(b);return}}),zo.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let A=m.value;if(A.trim()){if(so(b)){ao(b,A.trim()),yo(b),mi(b);return}jo(b,A,{source:"free-text"})}});let fc=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let m=zo.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",fc);let Kn=null,yt=null,Pr=null,Hs=null,hi=()=>{},gc=!1,Bs="",Ds="";function yi(){Hs?.(),Hs=null}let mc=()=>{if(!Kn||!yt)return;let i=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,m=g.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){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 b=Kn.firstElementChild;if(!b||b===yt)return;let A=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${A}px`,yt.style.zIndex="5";let k=Fl(Kn,g),Q=b.offsetWidth+k/2-A/2;yt.style.left=`${Math.max(0,Q)}px`},Fs=()=>{},mf=()=>{let i=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>m?!1:M||Dt(o)},Ns=()=>!Xt(o)||!Ws()||e.classList.contains("persona-artifact-narrow-host")||mf()||(e.ownerDocument.defaultView??window).innerWidth<sb?"none":Hl(o)?"detached":"welded",Pn=()=>{if(!Ye||!Xt(o))return;Ts(e,o),Ms(e,o),Fs();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let m=Ws();Ye.setVisible(m),Ye.update(mn),Ln?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1):mn.artifacts.length>0&&pc()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(b),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),!b&&!Lr&&(hn=!1),hn!==gc){let k=Ye.element;hn?(Bs=k.style.width,Ds=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Bs&&(k.style.width=Bs),Ds&&(k.style.maxWidth=Ds),Bs="",Ds=""),gc=hn}e.classList.toggle("persona-artifact-expanded",hn),Ye.setExpanded(hn);let A=Ns();A!==kr&&(kr=A,Er()),hi()};if(Xt(o)){de.style.position="relative";let i=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(fe),Ye=Tu(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{Ln=!0,Pn()},onToggleExpand:()=>{let m=!hn,b=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(hn=m,m||(Lr=!1),Pn())}}),Ye.element.classList.add("persona-hidden"),Kn=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&de.appendChild(Ye.backdrop),de.appendChild(g),hi=()=>{if(!Kn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!yt){let b=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let A=e.ownerDocument,k=A.defaultView??window,Q=N=>{if(!Ye||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;N.preventDefault(),yi();let K=N.clientX,ae=Ye.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,re=Ue=>{let pt=Kn.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),nn=Fl(Kn,k),At=nt?0:b.getBoundingClientRect().width||6,Et=ae-(Ue.clientX-K),W=Hu(Et,pt,nn,At,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ye.element.style.width=`${W}px`,Ye.element.style.maxWidth="none",mc()},we=()=>{A.removeEventListener("pointermove",re),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),Hs=null;try{b.releasePointerCapture(N.pointerId)}catch{}};Hs=we,A.addEventListener("pointermove",re),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{b.setPointerCapture(N.pointerId)}catch{}};b.addEventListener("pointerdown",Q),yt=b,Kn.insertBefore(b,Ye.element),Pr=()=>{b.removeEventListener("pointerdown",Q)}}if(yt){let b=Ws();yt.classList.toggle("persona-hidden",!b),mc()}},Fs=()=>{if(!M||!Ye||(o.launcher?.sidebarMode??!1)||Dt(o)&&gn(o).reveal==="emerge")return;let b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(A&&b.innerWidth<=k||!ku(o,M))return;let Q=o.launcher?.width??o.launcherWidth??$n,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ws()?(de.style.width=N,de.style.maxWidth=N):(de.style.width=Q,de.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(Mr=new ResizeObserver(()=>{Pn()}),Mr.observe(de))}else de.appendChild(fe);F()&&et&&(Ie.peekBanner&&et.appendChild(Ie.peekBanner),et.appendChild(J)),e.appendChild(He),et&&e.appendChild(et);let Os=()=>{if(F()){de.style.width="100%",de.style.maxWidth="100%";let St=o.launcher?.composerBar??{},Yt=He.dataset.state==="expanded",oa=St.expandedSize??"anchored";if(!(Yt&&oa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let qr=o.theme?.components?.panel,ra=dr(o),Jo=(Hn,ko)=>Hn==null||Hn===""?ko:Gt(ra,Hn)??Hn,sa="1px solid var(--persona-border)",Oi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Eo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Jo(qr?.border,sa),fe.style.borderRadius=Jo(qr?.borderRadius,Eo),fe.style.boxShadow=Jo(qr?.shadow,Oi),fe.style.overflow="hidden";return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,Q=dr(o),N=(St,Yt)=>St==null||St===""?Yt:Gt(Q,St)??St,K=e.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,re=K.innerWidth<=ge,we=ae&&re&&M,Ue=i&&ae&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",nn=o.launcher?.zIndex??Vt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Et="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ee=A&&!we&&!Ue;Ee?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ne=Ee?At:g||we?"none":At,Se=Ee?Et:we?"none":g?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))":b?"none":Et;i&&!we&&!Ee&&(Se="none",Ne="none");let wt=Ee?W:g||we?"0":W,ut=N(k?.border,Ne),Bt=N(k?.shadow,Se),ft=N(k?.borderRadius,wt),Jt=Ns(),kt=Jt==="detached",ke=Jt==="welded";e.classList.toggle("persona-artifact-detached-split",kt),e.classList.toggle("persona-artifact-welded-split",ke);let Oe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&Hl(o)&&b&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let ct=kt||vt?"none":Bt,gt=kt?At:ke?"none":ut,Ze=kt?W:ft;vt&&(gt="none",Ze="0");let We=k?.borderRadius!=null&&k.borderRadius!=="",ht=vt&&!We?"0":ft,zt=se.scrollTop;e.style.cssText="",He.style.cssText="",de.style.cssText="",fe.style.cssText="",se.style.cssText="",J.style.cssText="",Ve&&(se.style.display="none"),(m||b)&&(e.style.minWidth="0");let pn=()=>{if(zt<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===zt)return;let Yt=se.scrollHeight-se.clientHeight;Yt<=0||(se.scrollTop=Math.min(zt,Yt))})};if(we){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=`
|
|
46
|
+
`,A.addEventListener("click",()=>{u=j,F.forEach((V,K)=>{let ne=K<j;V.classList.toggle("selected",ne),V.setAttribute("aria-checked",K===j-1?"true":"false")})}),F.push(A),P.appendChild(A)}w.appendChild(P);let k=null;if(p){let j=document.createElement("div");j.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),j.appendChild(k),w.appendChild(j)}let T=document.createElement("div");T.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),c.remove()});let U=document.createElement("button");return U.type="button",U.className="persona-feedback-btn persona-feedback-btn-submit",U.textContent=a,U.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let j=k?.value.trim()||void 0;await t(u,j),c.remove()}catch(j){U.disabled=!1,U.textContent=a,console.error("[CSAT Feedback] Failed to submit:",j)}}),T.appendChild(M),T.appendChild(U),w.appendChild(T),c.appendChild(w),c}function pf(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:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,v.appendChild(x);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=r,v.appendChild(P),g.appendChild(v);let F=document.createElement("div");F.className="persona-feedback-rating persona-feedback-rating-nps",F.setAttribute("role","radiogroup"),F.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=c,k.appendChild(T),k.appendChild(M);let U=document.createElement("div");U.className="persona-feedback-numbers";let j=[];for(let D=0;D<=10;D++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${D} out of 10`),_.textContent=String(D),_.dataset.rating=String(D),D<=6?_.classList.add("persona-feedback-detractor"):D<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{w=D,j.forEach((Y,ge)=>{Y.classList.toggle("selected",ge===D),Y.setAttribute("aria-checked",ge===D?"true":"false")})}),j.push(_),U.appendChild(_)}F.appendChild(k),F.appendChild(U),g.appendChild(F);let A=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),D.appendChild(A),g.appendChild(D)}let V=document.createElement("div");V.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=l,K.addEventListener("click",()=>{n?.(),u.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=a,ne.addEventListener("click",async()=>{if(w===null){U.classList.add("persona-feedback-shake"),setTimeout(()=>U.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let D=A?.value.trim()||void 0;await t(w,D),u.remove()}catch(D){ne.disabled=!1,ne.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),V.appendChild(K),V.appendChild(ne),g.appendChild(V),u.appendChild(g),u}var Tr="persona-chat-history",Ib=30*1e3,Rb=641,Wb={"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 Hb(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 s=Wb[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{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 hi(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 Bb(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 Db(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Jl=e=>!e||typeof e!="object"?{}:{...e},uf=e=>e.map(t=>({...t,streaming:!1})),ff=(e,t,n)=>{let o=e?.markdown?ma(e.markdown):null,r=ha(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."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=_n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Dd(a):a,u=o(c);d=r&&p?r(u):u}else d=ao(a);return d}};function gf(e){let t=y("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=y("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var Fb=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Nb=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Fb(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),mf=(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=Ha(t),r=o.features;o=Ul(o);let s=ql.getForInstance(o.plugins),{plugin:a,teardown:l}=Fu();o.components&&Vn.registerAll(o.components);let p=of(),c=o.persistState===!1?null:o.storageAdapter??sf(),u={},w=null,g=!1,v=i=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(i);if(f&&typeof f=="object"&&"state"in f){let{state:m,open:b}=f;return b&&(g=!0),m}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")w=i.then(f=>v(f??{messages:[],metadata:{}}));else{let m=v(i??{messages:[],metadata:{}});m.metadata&&(u=Jl(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=v({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let x=()=>u,P=i=>{u=i({...u})??{},Pi()},F=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gl],k=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick],T=Ql({parsers:F,handlers:k,getSessionMetadata:x,updateSessionMetadata:P,emit:p.emit,documentRef:typeof document<"u"?document:null});T.syncFromMetadata();let M=o.launcher?.enabled??!0,U=o.launcher?.autoExpand??!1,j=o.autoFocusInput??!1,A=U,V=M,K=o.layout?.header?.layout,ne=!1,D=()=>Es(o),_=()=>M||D(),Y=D()?!1:M?U:!0,ge=!1,he=null,ce=()=>{ge=!0,he&&clearTimeout(he),he=setTimeout(()=>{ge&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ge=!1)},1e4)},Z=ff(o,T,ce),de=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,J=o.features?.scrollToBottom??{},fe=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,xe=ie?new Is(ye):null,ve=o.features?.eventStream?.maxEvents??2e3,Ae=ie?new Ps(ve,xe):null,Te=ie?new Rs:null,qe=null,ze=!1,Me=null,Pe=0;xe?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ke={onCopy:i=>{p.emit("message:copy",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.messageId,i.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(i)}},Wt=o.statusIndicator??{},It=i=>i==="idle"?Wt.idleText??Lt.idle:i==="connecting"?Wt.connectingText??Lt.connecting:i==="connected"?Wt.connectedText??Lt.connected:i==="error"?Wt.errorText??Lt.error:i==="paused"?Wt.pausedText??Lt.paused:i==="resuming"?Wt.resumingText??Lt.resuming:Lt[i];function qt(i,f,m,b){if(b==="idle"&&m.idleLink){i.textContent="";let S=document.createElement("a");S.href=m.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=f,S.style.color="inherit",S.style.textDecoration="none",i.appendChild(S)}else i.textContent=f}let xt=Tu({config:o,showClose:_()}),{wrapper:Be,panel:ue,pillRoot:Xe}=xt.shell,We=xt.panelElements,{container:me,body:le,messagesWrapper:Re,starterSuggestions:Kt,transcriptSuggestions:pt,suggestions:mt,textarea:z,sendButton:C,sendButtonWrapper:$,composerForm:h,statusText:L,introTitle:I,introSubtitle:H,closeButton:B,iconHolder:R,headerTitle:Q,headerSubtitle:se,header:Ee,footer:we,actionsRow:nt,rightActions:tt}=We,_e=We.leftActions,Je=We.setSendButtonMode,q=We.micButton,$e=We.micButtonWrapper,De=We.attachmentButton,Ht=We.attachmentButtonWrapper,vt=We.attachmentInput,Gt=We.attachmentPreviewsContainer;me.classList.add("persona-relative"),le.classList.add("persona-relative");let Fs=12,Kn=()=>J.label??"",Ef=()=>J.iconName??"arrow-down",kf=()=>J.enabled!==!1,ln=()=>fe.mode??"anchor-top",Gn=()=>ln()==="follow"||ln()==="anchor-top"&&Or,rc=()=>fe.anchorTopOffset??16,Lf=()=>fe.restorePosition??"bottom",sc=()=>fe.pauseOnInteraction===!0,ac=()=>fe.showActivityWhilePinned!==!1,ic=()=>fe.announce===!0,Tt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Er=y("span","persona-flex persona-items-center"),bi=y("span",""),bo=y("span","");bo.setAttribute("data-persona-scroll-to-bottom-count",""),bo.style.display="none",Tt.append(Er,bi,bo),me.appendChild(Tt);let Qn=y("div","persona-stream-anchor-spacer");Qn.setAttribute("aria-hidden","true"),Qn.setAttribute("data-persona-anchor-spacer",""),Qn.style.flexShrink="0",Qn.style.pointerEvents="none",Qn.style.height="0px",le.appendChild(Qn);let vo=y("div","persona-sr-only");vo.setAttribute("aria-live","polite"),vo.setAttribute("aria-atomic","true"),vo.setAttribute("role","status"),vo.setAttribute("data-persona-live-region",""),Object.assign(vo.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"}),me.appendChild(vo);let kr=null,Ns=null,lc=i=>{!ic()||!i||(Ns=i,kr===null&&(kr=setTimeout(()=>{kr=null,Ns&&ic()&&(vo.textContent=Ns),Ns=null},400)))},jo=()=>{let f=we.style.display==="none"?0:we.offsetHeight;Tt.style.bottom=`${f+Fs}px`};jo();let cc=()=>{let i=!!Kn();Tt.setAttribute("aria-label",Kn()||"Jump to latest"),Tt.title=Kn(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Er.innerHTML="";let f=ae(Ef(),"14px","currentColor",2);f?(Er.appendChild(f),Er.style.display=""):Er.style.display="none",bi.textContent=Kn(),bi.style.display=i?"":"none"};cc();let Ct=null,tn=null,dc=null,pc=s.find(i=>i.renderHeader);if(pc?.renderHeader){let i=pc.renderHeader({config:o,defaultRenderer:()=>{let f=No({config:o,showClose:_()});return ks(me,f,o),f.header},onClose:()=>it(!1,"user")});if(i){let f=me.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(i),Ee=i,xt.header.element=i)}}let vi=()=>{if(!Ae)return;if(ze=!0,!qe&&Ae&&(qe=$u({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>Lr(),config:o,plugins:s,getThroughput:()=>Te?.getMetric()??{status:"idle"}})),qe&&(le.style.display="none",we.parentNode?.insertBefore(qe.element,we),qe.update()),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(m=>m&&Ye.classList.add(m))}let i=()=>{if(!ze)return;let f=Date.now();f-Pe>=200&&(qe?.update(),Pe=f),Me=requestAnimationFrame(i)};Pe=0,Me=requestAnimationFrame(i),on(),p.emit("eventStream:opened",{timestamp:Date.now()})},Lr=()=>{if(ze){if(ze=!1,qe&&qe.element.remove(),le.style.display="",Ye){Ye.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(f=>f&&Ye.classList.remove(f))}Me!==null&&(cancelAnimationFrame(Me),Me=null),on(),p.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(ie){let i=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Ye=y("button",f),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Jt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&Ye.appendChild(m);let b=We.clearChatButtonWrapper,S=We.closeButtonWrapper,E=b||S;E&&E.parentNode===Ee?Ee.insertBefore(Ye,E):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{ze?Lr():vi()})}let Pf=i=>{let f=o.attachments;if(!f?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let S=i.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(m,S):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let S=y("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(f.allowedTypes??zn).join(","),S.multiple=(f.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),i.appendChild(S)}},uc=s.find(i=>i.renderComposer);if(uc?.renderComposer){let i=o.composer,f=uc.renderComposer({config:o,defaultRenderer:()=>ci({config:o}).footer,onSubmit:m=>{if(!N||N.isStreaming())return;let b=m.trim(),S=Ct?.hasAttachments()??!1;if(!b&&!S)return;ed();let E;S&&(E=[],E.push(...Ct.getContentParts()),b&&E.push(dr(b))),N.sendMessage(b,{contentParts:E}),S&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{vt?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{dc?.()}:void 0});f&&(xt.replaceComposer(f),we=xt.composer.footer)}let If=i=>{let f=(...pe)=>{for(let re of pe){let be=i.querySelector(re);if(be)return be}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),S=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),X=i.querySelector("[data-persona-composer-status]");m&&(h=m),b&&(z=b),S&&(C=S),E&&(q=E,$e=E.parentElement),X&&(L=X);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(mt=O);let G=f("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(De=G,Ht=G.parentElement),vt=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Gt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ee=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ee&&(nt=ee),_e=f(".persona-widget-composer__left-actions")};Pf(we),If(we);let Tn=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Tn&&(Re.style.maxWidth=Tn,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",Kt.style.maxWidth=Tn,pt.style.maxWidth=Tn,pt.style.marginLeft="auto",pt.style.marginRight="auto",pt.style.width="100%"),Tn&&h&&!D()&&(h.style.maxWidth=Tn,h.style.marginLeft="auto",h.style.marginRight="auto"),Tn&&mt&&!D()&&(mt.style.maxWidth=Tn,mt.style.marginLeft="auto",mt.style.marginRight="auto"),Tn&&Gt&&!D()&&(Gt.style.maxWidth=Tn,Gt.style.marginLeft="auto",Gt.style.marginRight="auto"),o.attachments?.enabled&&vt&&Gt){Ct=gs.fromConfig(o.attachments),Ct.setPreviewsContainer(Gt),vt.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,f=gf(i);me.appendChild(f)}let Rf=()=>tn?.prefetch();if(o.contextMentions?.enabled&&z&&(tn=Ip({config:o,textarea:z,anchor:h??z,getMessages:()=>N.getMessages(),liveRegionHost:me}),tn)){let i=z;i.parentElement?.insertBefore(tn.contextRow,i);let f=tn.affordanceButtons;for(let m=f.length-1;m>=0;m--){let b=f[m];_e?_e.insertBefore(b,_e.firstChild):h?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},f=b=>{switch(b){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Re;case"footer-top":return mt;case"composer":return h;case"footer-bottom":return L;default:return null}},m=(b,S)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")Ee.insertBefore(S,Ee.firstChild);else if(b==="header-right")Ee.appendChild(S);else{let E=Ee.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(S,E.nextSibling):Ee.appendChild(S)}break;case"body-top":{let E=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");E?E.replaceWith(S):le.insertBefore(S,le.firstChild);break}case"body-bottom":le.appendChild(S);break;case"footer-top":mt.replaceWith(S);break;case"footer-bottom":L.replaceWith(S);break;default:break}};for(let[b,S]of Object.entries(i))if(S)try{let E=S({config:o,defaultContent:()=>f(b)});E&&m(b,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,E)}})();let fc=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let E=m.getAttribute("data-bubble-type");if(E==="reasoning")wr.has(S)?wr.delete(S):wr.add(S),Pu(S,b);else if(E==="tool")xr.has(S)?xr.delete(S):xr.add(S),Iu(S,b,o);else if(E==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Oo.get(S)??O;Oo.set(S,!G),Bu(S,b,o)}So.delete(S)};Re.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),fc(i))}),Re.addEventListener("keydown",i=>{let f=i.target;(i.key==="Enter"||i.key===" ")&&f.closest('button[data-expand-header="true"]')&&(i.preventDefault(),fc(i))}),Re.addEventListener("copy",i=>{let{clipboardData:f}=i;if(!f)return;let m=Re.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),E=su(S);!E||E===S||(f.setData("text/plain",E),i.preventDefault())});let wi=new Map,gc=null,mc="idle",Wf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Hf=(i,f)=>{let{icon:m,label:b}=Wf[f];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",f==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",f!=="idle"),i.classList.toggle("persona-message-action-loading",f==="loading");let S=ae(m,14,"currentColor",2);S&&(i.innerHTML="",i.appendChild(S))},hc=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let b=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Hf(f,b&&b===gc?mc:"idle")})};Re.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let E=m.getAttribute("data-action");if(E==="copy"){let O=N.getMessages().find(G=>G.id===S);if(O&&Ke.onCopy){let G=O.content||"";navigator.clipboard.writeText(G).then(()=>{m.classList.add("persona-message-action-success");let ee=ae("check",14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let pe=ae("copy",14,"currentColor",2);pe&&(m.innerHTML="",m.appendChild(pe))},2e3)}).catch(ee=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ee)}),Ke.onCopy(O)}}else if(E==="read-aloud")N.toggleReadAloud(S);else if(E==="upvote"||E==="downvote"){let O=(wi.get(S)??null)===E,G=E==="upvote"?"thumbs-up":"thumbs-down";if(O){wi.delete(S),m.classList.remove("persona-message-action-active");let ee=ae(G,14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee))}else{let ee=E==="upvote"?"downvote":"upvote",pe=b.querySelector(`[data-action="${ee}"]`);if(pe){pe.classList.remove("persona-message-action-active");let Ze=ae(ee==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ze&&(pe.innerHTML="",pe.appendChild(Ze))}wi.set(S,E),m.classList.add("persona-message-action-active");let re=ae(G,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(re)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=N.getMessages().find(lt=>lt.id===S);Ue&&Ke.onFeedback&&Ke.onFeedback({type:E,messageId:Ue.id,message:Ue})}}}),Re.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let E=m.getAttribute("data-approval-action");if(!E)return;let X=E==="approve"?"approved":"denied",G=N.getMessages().find(pe=>pe.id===S);if(!G?.approval)return;let ee=b.querySelector("[data-approval-buttons]");ee&&ee.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?N.resolveWebMcpApproval(S,X):N.resolveApproval(G.approval,X)});let Ge=null,Pr=null,Ir=()=>{},Rr="none",Os=null,yn={artifacts:[],selectedId:null},Rn=!1,bn=!1,Wr=!1,Vo=!1,yc=()=>Vo||yn.artifacts.some(i=>io(o.features?.artifacts,i)==="panel"),_s=()=>yn.artifacts.length>0&&!Rn&&yc(),st={current:null},xi=(i,f)=>{let m=N.getArtifactById(f),b=m?.markdown,S=m?.title||"artifact",E=m?.file,X=m?.artifactType??"markdown";if(!b){let ee=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ee){let re=N.getMessages().find(be=>be.id===ee);if(re?.rawContent)try{let be=JSON.parse(re.rawContent);b=be?.props?.markdown,S=be?.props?.title||S,be?.props?.file&&typeof be.props.file=="object"&&(E=be.props.file),!m&&typeof be?.props?.artifactType=="string"&&(X=be.props.artifactType)}catch{}}}return{markdown:b,title:S,file:E,artifactType:X}};Re.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:E,title:X,file:O}=xi(m,b);if(!E)return;let{filename:G,mime:ee,content:pe}=$p({title:X,markdown:E,file:O}),re=new Blob([pe],{type:ee}),be=URL.createObjectURL(re),Ue=document.createElement("a");Ue.href=be,Ue.download=G,Ue.click(),URL.revokeObjectURL(be)}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let S=m.closest("[data-artifact-inline]"),E=S?null:m.closest("[data-open-artifact]"),X=S?S.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,G=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(lt=>lt.id===b);if(!G)return;let{markdown:ee,title:pe,file:re,artifactType:be}=xi(m,X??""),Ue={artifactId:X,title:pe,artifactType:be,markdown:ee,file:re};try{Promise.resolve(G.onClick(Ue)).catch(()=>{})}catch{}}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let S=N.getArtifactById(b),E="";if(S)E=xs(S);else{let{markdown:X,file:O,artifactType:G}=xi(m,b);G==="markdown"&&(E=xs({id:b,artifactType:"markdown",status:"complete",markdown:X??"",...O?{file:O}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let X=ae("check",16,"currentColor",2);X&&(m.replaceChildren(X),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&m.replaceChildren(O)},1500))}).catch(()=>{})}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(Rn=!1,Vo=!0,bn=!0,Wr=!0,N.selectArtifact(b),Wn())}),Re.addEventListener("click",i=>{let f=i.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let m=f.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),Rn=!1,Vo=!0,N.selectArtifact(b),Wn())}),Re.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let f=i.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),f.click())});let qo=We.composerOverlay,Ko=(i,f,m)=>{let b=f.trim();if(!b||!st.current)return;let S=i.getAttribute("data-tool-call-id")??"",E=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:E,source:m.source},bubbles:!0,composed:!0})),lr(qo,S);let X=st.current.getMessages().find(O=>O.toolCall?.id===S);X?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(X,m.structured??b):st.current.sendMessage(b)},wo=i=>{let f=st.current;if(!f)return;let m=i.getAttribute("data-tool-call-id")??"",b=f.getMessages().find(S=>S.toolCall?.id===m);b&&f.persistAskUserQuestionProgress(b,{answers:va(i,b),currentIndex:mn(i)})},bc=i=>Object.entries(i).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),Ci=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=mn(i),m=ir(i);if(f>=m-1)return;let b=st.current?.getMessages().find(S=>S.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(xa(i,b,o,f+1),wo(i))};qo.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),S==="dismiss"){let E=b.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),lr(qo,E);let X=st.current?.getMessages().find(O=>O.toolCall?.id===E);X?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(X),st.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(S==="pick"){let E=m.getAttribute("data-option-label");if(!E)return;let X=b.getAttribute("data-multi-select")==="true",O=lo(b);if(O&&X){let G=Ho(b)[mn(b)],ee=new Set(Array.isArray(G)?G:[]);ee.has(E)?ee.delete(E):ee.add(E),co(b,Array.from(ee)),wo(b);return}if(O){co(b,E),wo(b),Ci(b);return}if(X){let G=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",G?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!G);let ee=b.querySelector('[data-ask-user-action="submit-multi"]');ee&&(ee.disabled=nl(b).length===0);return}Ko(b,E,{source:"pick",values:[E]});return}if(S==="submit-multi"){let E=nl(b);if(E.length===0)return;Ko(b,E.join(", "),{source:"multi",values:E});return}if(S==="open-free-text"){let E=b.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let X=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(lo(b)){co(b,X.trim()),wo(b),Ci(b);return}Ko(b,X,{source:"free-text"});return}if(S==="next"||S==="back"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(re=>re.toolCall?.id===E);if(!X)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let re=Ho(b)[mn(b)];(typeof re!="string"||re!==G)&&co(b,G)}let ee=S==="next"?1:-1,pe=mn(b)+ee;xa(b,X,o,pe),wo(b);return}if(S==="submit-all"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(re=>re.toolCall?.id===E);if(!X)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&co(b,G);let ee=va(b,X);st.current.persistAskUserQuestionProgress(X,{answers:ee,currentIndex:mn(b)});let pe=bc(ee);Ko(b,pe||"(submitted)",{source:"submit-all",structured:ee});return}if(S==="skip"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(be=>be.toolCall?.id===E);if(!X)return;let O=lo(b),G=mn(b),ee=ir(b),pe=G>=ee-1;if(!O){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),lr(qo,E),X.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(X),st.current.resolveAskUserQuestion(X,"(dismissed)"));return}co(b,"");let re=b.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),pe){let be=va(b,X),Ue=bc(be);Ko(b,Ue||"(skipped)",{source:"submit-all",structured:be});return}xa(b,X,o,G+1),wo(b);return}}),qo.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let S=m.value;if(S.trim()){if(lo(b)){co(b,S.trim()),wo(b),Ci(b);return}Ko(b,S,{source:"free-text"})}});let vc=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let f=i.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let m=qo.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),E=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",vc);let Xn=null,ht=null,Hr=null,$s=null,Ai=()=>{},wc=!1,Us="",zs="";function Si(){$s?.(),$s=null}let xc=()=>{if(!Xn||!ht)return;let i=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,m=f.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let b=Xn.firstElementChild;if(!b||b===ht)return;let S=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${S}px`,ht.style.zIndex="5";let E=zl(Xn,f),X=b.offsetWidth+E/2-S/2;ht.style.left=`${Math.max(0,X)}px`},js=()=>{},Bf=()=>{let i=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!f||i.innerWidth>m?!1:M||Dt(o)},Vs=()=>!Yt(o)||!_s()||e.classList.contains("persona-artifact-narrow-host")||Bf()||(e.ownerDocument.defaultView??window).innerWidth<Rb?"none":_l(o)?"detached":"welded",Wn=()=>{if(!Ge||!Yt(o))return;Ws(e,o),Hs(e,o),js();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=i);let m=_s();Ge.setVisible(m),Ge.update(yn),Rn?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),Ge.backdrop?.classList.add("persona-hidden"),bn=!1,Wr=!1):yn.artifacts.length>0&&yc()?(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)):(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),Ge.backdrop?.classList.add("persona-hidden"),bn=!1,Wr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ge.setExpandToggleVisible(b),Ge.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ge.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ge.setTabFade(o.features?.artifacts?.layout?.tabFade),Ge.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Wr&&(bn=!1),bn!==wc){let E=Ge.element;bn?(Us=E.style.width,zs=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(Us&&(E.style.width=Us),zs&&(E.style.maxWidth=zs),Us="",zs=""),wc=bn}e.classList.toggle("persona-artifact-expanded",bn),Ge.setExpanded(bn);let S=Vs();S!==Rr&&(Rr=S,Ir()),Ai()};if(Yt(o)){ue.style.position="relative";let i=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(me),Ge=zu(o,{onSelect:m=>st.current?.selectArtifact(m),onDismiss:()=>{Rn=!0,Wn()},onToggleExpand:()=>{let m=!bn,b=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(bn=m,m||(Wr=!1),Wn())}}),Ge.element.classList.add("persona-hidden"),Xn=f,f.appendChild(i),f.appendChild(Ge.element),Ge.backdrop&&ue.appendChild(Ge.backdrop),ue.appendChild(f),Ai=()=>{if(!Xn||!Ge)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Hr?.(),Hr=null,Si(),ht&&(ht.remove(),ht=null),Ge.element.style.removeProperty("width"),Ge.element.style.removeProperty("maxWidth");return}if(!ht){let b=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let S=e.ownerDocument,E=S.defaultView??window,X=O=>{if(!Ge||O.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;O.preventDefault(),Si();let G=O.clientX,ee=Ge.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,re=Ue=>{let lt=Xn.getBoundingClientRect().width,Ze=e.classList.contains("persona-artifact-welded-split"),rn=zl(Xn,E),At=Ze?0:b.getBoundingClientRect().width||6,Et=ee-(Ue.clientX-G),W=Yu(Et,lt,rn,At,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ge.element.style.width=`${W}px`,Ge.element.style.maxWidth="none",xc()},be=()=>{S.removeEventListener("pointermove",re),S.removeEventListener("pointerup",be),S.removeEventListener("pointercancel",be),$s=null;try{b.releasePointerCapture(O.pointerId)}catch{}};$s=be,S.addEventListener("pointermove",re),S.addEventListener("pointerup",be),S.addEventListener("pointercancel",be);try{b.setPointerCapture(O.pointerId)}catch{}};b.addEventListener("pointerdown",X),ht=b,Xn.insertBefore(b,Ge.element),Hr=()=>{b.removeEventListener("pointerdown",X)}}if(ht){let b=_s();ht.classList.toggle("persona-hidden",!b),xc()}},js=()=>{if(!M||!Ge||(o.launcher?.sidebarMode??!1)||Dt(o)&&hn(o).reveal==="emerge")return;let b=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(S&&b.innerWidth<=E||!qu(o,M))return;let X=o.launcher?.width??o.launcherWidth??jn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(ue.style.width=O,ue.style.maxWidth=O):(ue.style.width=X,ue.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Pr=new ResizeObserver(()=>{Wn()}),Pr.observe(ue))}else ue.appendChild(me);D()&&Xe&&(We.peekBanner&&Xe.appendChild(We.peekBanner),Xe.appendChild(we)),e.appendChild(Be),Xe&&e.appendChild(Xe);let qs=()=>{if(D()){ue.style.width="100%",ue.style.maxWidth="100%";let St=o.launcher?.composerBar??{},en=Be.dataset.state==="expanded",ca=St.expandedSize??"anchored";if(!(en&&ca!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Zr=o.theme?.components?.panel,da=gr(o),tr=(Fn,Ro)=>Fn==null||Fn===""?Ro:Xt(da,Fn)??Fn,pa="1px solid var(--persona-border)",Vi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=tr(Zr?.border,pa),me.style.borderRadius=tr(Zr?.borderRadius,Io),me.style.boxShadow=tr(Zr?.shadow,Vi),me.style.overflow="hidden";return}let i=Dt(o),f=o.launcher?.sidebarMode??!1,m=i||f||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,X=gr(o),O=(St,en)=>St==null||St===""?en:Xt(X,St)??St,G=e.ownerDocument.defaultView??window,ee=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,re=G.innerWidth<=pe,be=ee&&re&&M,Ue=i&&ee&&re,lt=o.launcher?.position??"bottom-left",Ze=lt==="bottom-left"||lt==="top-left",rn=o.launcher?.zIndex??Vt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Et="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=S&&!be&&!Ue;ke?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=ke?At:f||be?"none":At,Se=ke?Et:be?"none":f?Ze?"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))":b?"none":Et;i&&!be&&!ke&&(Se="none",Fe="none");let wt=ke?W:f||be?"0":W,ct=O(E?.border,Fe),Bt=O(E?.shadow,Se),dt=O(E?.borderRadius,wt),Zt=Vs(),kt=Zt==="detached",Le=Zt==="welded";e.classList.toggle("persona-artifact-detached-split",kt),e.classList.toggle("persona-artifact-welded-split",Le);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)))))",bt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(o)&&_l(o)&&b&&!i;e.classList.toggle("persona-artifact-chat-flush",bt);let at=kt||bt?"none":Bt,ut=kt?At:Le?"none":ct,Qe=kt?W:dt;bt&&(ut="none",Qe="0");let He=E?.borderRadius!=null&&E.borderRadius!=="",gt=bt&&!He?"0":dt,Ut=le.scrollTop;e.style.cssText="",Be.style.cssText="",ue.style.cssText="",me.style.cssText="",le.style.cssText="",we.style.cssText="",ze&&(le.style.display="none"),(m||b)&&(e.style.minWidth="0");let fn=()=>{if(Ut<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===Ut)return;let en=le.scrollHeight-le.clientHeight;en<=0||(le.scrollTop=Math.min(Ut,en))})};if(be){Be.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"),Be.style.cssText=`
|
|
47
47
|
position: fixed !important;
|
|
48
48
|
inset: 0 !important;
|
|
49
49
|
width: 100% !important;
|
|
@@ -53,9 +53,9 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
53
53
|
padding: 0 !important;
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
|
-
z-index: ${
|
|
56
|
+
z-index: ${rn} !important;
|
|
57
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
58
|
-
`,
|
|
58
|
+
`,ue.style.cssText=`
|
|
59
59
|
position: relative !important;
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
68
|
padding: 0 !important;
|
|
69
69
|
box-shadow: none !important;
|
|
70
70
|
border-radius: 0 !important;
|
|
71
|
-
`,
|
|
71
|
+
`,me.style.cssText=`
|
|
72
72
|
display: flex !important;
|
|
73
73
|
flex-direction: column !important;
|
|
74
74
|
flex: 1 1 0% !important;
|
|
@@ -79,7 +79,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
79
79
|
overflow: hidden !important;
|
|
80
80
|
border-radius: 0 !important;
|
|
81
81
|
border: none !important;
|
|
82
|
-
`,
|
|
82
|
+
`,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",we.style.flexShrink="0",ne=!0,fn();return}let la=o?.launcher?.width??o?.launcherWidth??jn;if(!f&&!i)b&&m?(ue.style.width="100%",ue.style.maxWidth="100%"):(ue.style.width=la,ue.style.maxWidth=la);else if(i)if(hn(o).reveal==="emerge"&&!S){let en=hn(o).width;ue.style.width=en,ue.style.maxWidth=en}else ue.style.width="100%",ue.style.maxWidth="100%";if(js(),ue.style.boxShadow=at,ue.style.borderRadius=gt,kt?ue.style.border="none":Le&&(ue.style.border=ct),me.style.border=ut,me.style.borderRadius=Qe,me.style.boxShadow=kt&&!bt?Ne:"",bt&&(me.style.background="transparent",le.style.background="transparent",we.style.background="transparent",we.style.borderTop="none"),Le){let St=o.features?.artifacts?.layout;Os=St?.unifiedSplitOuterRadius?.trim()||St?.paneBorderRadius?.trim()||dt}else Os=null;if(i&&!be&&!ke&&!kt&&!Le&&E?.border===void 0&&(me.style.border="none",hn(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),i&&!be&&Le&&E?.border===void 0&&(hn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),Be.style.display="flex",Be.style.flexDirection="column",Be.style.flex="1 1 0%",Be.style.minHeight="0",Be.style.maxHeight="100%",Be.style.height="100%",b&&(Be.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%",kt||(ue.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",we.style.flexShrink="0"),b&&(ke||kt||bt)&&!i&&(bt||(Be.style.padding="var(--persona-panel-inset)"),Be.style.background="var(--persona-panel-canvas-bg)"),Be.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"),!f&&!b&&!i&&(Sn[lt]??Sn["bottom-right"]).split(" ").forEach(en=>Be.classList.add(en)),f){let St=o.launcher?.sidebarWidth??"420px";S?Be.style.cssText=`
|
|
83
83
|
position: fixed !important;
|
|
84
84
|
top: var(--persona-panel-inset) !important;
|
|
85
85
|
bottom: var(--persona-panel-inset) !important;
|
|
@@ -90,9 +90,9 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
90
90
|
padding: 0 !important;
|
|
91
91
|
display: flex !important;
|
|
92
92
|
flex-direction: column !important;
|
|
93
|
-
z-index: ${
|
|
94
|
-
${
|
|
95
|
-
`:
|
|
93
|
+
z-index: ${rn} !important;
|
|
94
|
+
${Ze?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
+
`:Be.style.cssText=`
|
|
96
96
|
position: fixed !important;
|
|
97
97
|
top: 0 !important;
|
|
98
98
|
bottom: 0 !important;
|
|
@@ -103,9 +103,9 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
103
103
|
padding: 0 !important;
|
|
104
104
|
display: flex !important;
|
|
105
105
|
flex-direction: column !important;
|
|
106
|
-
z-index: ${
|
|
107
|
-
${
|
|
108
|
-
`,
|
|
106
|
+
z-index: ${rn} !important;
|
|
107
|
+
${Ze?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
|
+
`,ue.style.cssText=`
|
|
109
109
|
position: relative !important;
|
|
110
110
|
display: flex !important;
|
|
111
111
|
flex-direction: column !important;
|
|
@@ -116,10 +116,10 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
116
116
|
min-height: 0 !important;
|
|
117
117
|
margin: 0 !important;
|
|
118
118
|
padding: 0 !important;
|
|
119
|
-
box-shadow: ${
|
|
120
|
-
border-radius: ${
|
|
121
|
-
${kt?"border: none !important;":
|
|
122
|
-
`,
|
|
119
|
+
box-shadow: ${at} !important;
|
|
120
|
+
border-radius: ${gt} !important;
|
|
121
|
+
${kt?"border: none !important;":Le?`border: ${ct} !important;`:""}
|
|
122
|
+
`,ue.style.setProperty("width","100%","important"),ue.style.setProperty("max-width","100%","important"),me.style.cssText=`
|
|
123
123
|
display: flex !important;
|
|
124
124
|
flex-direction: column !important;
|
|
125
125
|
flex: 1 1 0% !important;
|
|
@@ -128,16 +128,16 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
min-height: 0 !important;
|
|
129
129
|
max-height: 100% !important;
|
|
130
130
|
overflow: hidden !important;
|
|
131
|
-
border-radius: ${
|
|
132
|
-
border: ${
|
|
133
|
-
${kt&&!
|
|
134
|
-
${
|
|
135
|
-
`,
|
|
131
|
+
border-radius: ${Qe} !important;
|
|
132
|
+
border: ${ut} !important;
|
|
133
|
+
${kt&&!bt?`box-shadow: ${Ne} !important;`:""}
|
|
134
|
+
${bt?"background: transparent !important;":""}
|
|
135
|
+
`,we.style.cssText=`
|
|
136
136
|
flex-shrink: 0 !important;
|
|
137
137
|
border-top: none !important;
|
|
138
138
|
padding: 8px 16px 12px 16px !important;
|
|
139
|
-
${
|
|
140
|
-
`}if(!b&&!i){let St="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",oa=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;He.style.cssText+=St+Yt+oa}pn()};Os(),cs(e,o),Ts(e,o),Ms(e,o),Er=()=>{Os(),cs(e,o),Ts(e,o),Ms(e,o),Rs?e.style.setProperty("--persona-artifact-welded-outer-radius",Rs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let ze=[];ze.push(()=>{document.removeEventListener("keydown",fc)}),ze.push(()=>{Sr!==null&&clearTimeout(Sr)});let An=null,Sn=null;ze.push(()=>{An?.(),An=null,Sn?.(),Sn=null}),Mr&&ze.push(()=>{Mr?.disconnect(),Mr=null}),ze.push(()=>{Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&ze.push(()=>{Te!==null&&(cancelAnimationFrame(Te),Te=null),Qe?.destroy(),Qe=null,Me?.destroy(),Me=null,ve=null});let bo=null,hc=()=>{bo&&(bo(),bo=null),o.colorScheme==="auto"&&(bo=Ia(()=>{cs(e,o)}))};hc(),ze.push(()=>{bo&&(bo(),bo=null)}),ze.push(l);let _s=o.features?.streamAnimation;if(_s?.type&&_s.type!=="none"){let i=mr(_s.type,_s.plugins);i&&(qa(i,e),ze.push(()=>eu(e)))}let $s=vu(it),vo=null,O,bi=i=>{if(!O)return;let g=i??O.getMessages(),m=o.features?.suggestReplies?.enabled!==!1?zd(g):null;m?$s.render(m,O,ue,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?$s.render([],O,ue,g):$s.render(o.suggestionChips,O,ue,g,o.suggestionChipsConfig)},yn=!1,wo=Up(),Uo=new Map,xo=new Map,Gn=new Map,vi=0,hf=Fn()!==null,en=_a(),an=0,Qn=null,ln=!1,zs=!1,Xn=0,bn=null,Co=null,wi=!1,js=!1,Ir=null,Rr=!0,Us=!1,Vs=null,qs=!1,Ao=()=>{qs=!0},xi=null,yf=4,Ks=24,bf=80,Ci=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},yc=o.voiceRecognition?.autoResume??!1,In=i=>{p.emit("voice:state",{active:Ge.active,source:i,timestamp:Date.now()})},vn=()=>{R(i=>({...i,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},vf=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Vl(u.voiceState),g=!!i.active,m=Number(i.timestamp??0);Ge.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-m<rb&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("restore"),O.isVoiceActive()&&Qo()}):Ys("restore"))},1e3)},wf=()=>O?Ku(O.getMessages()).filter(i=>!i.__skipPersist):[],Gs=null,bc=(i,g)=>{typeof console<"u"&&console.error(i,g)},Ai=(i,g)=>{let m=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(N=>{bc(g,N)})}catch(Q){return bc(g,Q),null}},b=Gs,A=b?b.then(()=>m()??void 0):m();if(!A)return;let k=A.finally(()=>{Gs===k&&(Gs=null)});Gs=k};function Si(i){if(!c?.save)return;let m={messages:i?Ku(i):O?wf():[],metadata:u,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};Ai(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Vo=null,vc=()=>He.querySelector("#persona-scroll-container")||se,Wr=()=>{Vo!==null&&(cancelAnimationFrame(Vo),Vo=null),ln=!1},wc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!1,Wr()},xf=()=>yn&&Mi()&&(sn()!=="anchor-top"||ec()),Ti=()=>{let i=go()||"Jump to latest",g=xf();Tt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Xn>0?(mo.textContent=String(Xn),mo.style.display="",Tt.setAttribute("aria-label",`${i} (${Xn} new)`)):(mo.textContent="",mo.style.display="none",Tt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},xc=()=>{Xn!==0&&(Xn=0,Ti())},Mi=()=>Un()?!en.isFollowing():!uo(se,Ks),tn=()=>{if(!Ps()||Ve){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==fe&&fe.appendChild(Tt),_o();let g=En(se)>0&&Mi();g?Ti():xc(),Tt.style.display=g?"":"none"},Hr=()=>{en.pause()&&(wc(),tn())},Jn=()=>{en.resume(),xc(),tn()},Yn=(i=!1)=>{Un()&&en.isFollowing()&&(!i&&!yn||(Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!0,Qn=requestAnimationFrame(()=>{Qn=null,zs=!1,en.isFollowing()&&Cf(vc(),i?220:140)})))},Cc=(i,g,m,b=()=>!0)=>{let A=i.scrollTop,k=g(),Q=k-A;if(Wr(),Math.abs(Q)<1){ln=!0,i.scrollTop=k,an=i.scrollTop,ln=!1;return}let N=performance.now();ln=!0;let K=ge=>1-Math.pow(1-ge,3),ae=ge=>{if(!b()){Wr();return}let re=g();re!==k&&(k=re,Q=k-A);let we=ge-N,Ue=Math.min(we/m,1),pt=K(Ue),nt=A+Q*pt;i.scrollTop=nt,an=i.scrollTop,Ue<1?Vo=requestAnimationFrame(ae):(i.scrollTop=k,an=i.scrollTop,Vo=null,ln=!1)};Vo=requestAnimationFrame(ae)},Cf=(i,g=500)=>{let m=En(i)-i.scrollTop;if(Math.abs(m)<1){an=i.scrollTop;return}if(Math.abs(m)>=bf){Wr(),ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1;return}Cc(i,()=>En(i),g,()=>en.isFollowing())},Ac=()=>{let i=vc();ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1,tn()},Sc=i=>{let g=0,m=i;for(;m&&m!==se;)g+=m.offsetTop,m=m.offsetParent;return g},Af=()=>{let i=se.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??se.ownerDocument.getSelection()},Qs=()=>Qp(Af(),se),Tc=()=>{if(cf()!=="last-user-turn")return!1;let i=O?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(k=>k.role==="user");if(!g)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=se.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let A=Math.min(Math.max(0,Sc(b)-Yl()),En(se));return ln=!0,se.scrollTop=A,an=se.scrollTop,ln=!1,sn()==="follow"&&!uo(se,Ks)&&en.pause(),tn(),!0},Mc=i=>{Vn.style.height=`${Math.max(0,Math.round(i))}px`,bn&&(bn.spacerHeight=Math.max(0,i))},Br=()=>{Co!==null&&(cancelAnimationFrame(Co),Co=null),Wr(),bn=null,Vn.style.height="0px"},Ec=i=>{Co!==null&&cancelAnimationFrame(Co),Co=requestAnimationFrame(()=>{Co=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=se.querySelector(`[data-message-id="${g}"]`);if(!m)return;let b=Sc(m),A=bn?.spacerHeight??0,k=se.scrollHeight-A,{targetScrollTop:Q,spacerHeight:N}=Xp({anchorOffsetTop:b,topOffset:Yl(),viewportHeight:se.clientHeight,contentHeight:k});bn={initialSpacerHeight:N,contentHeightAtAnchor:k,spacerHeight:N},Mc(N),Cc(se,()=>Q,220)})},Sf=()=>{if(Un()){if(!en.isFollowing()||uo(se,1))return;Yn(!yn);return}if(bn&&bn.initialSpacerHeight>0){let i=se.scrollHeight-bn.spacerHeight,g=Jp({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:i});g!==bn.spacerHeight&&Mc(g)}tn()},Tf=i=>{let g=sn();g==="follow"?(Jn(),Yn(!0)):g==="anchor-top"&&(Rr=!1,Us=!0,qs=!1,Vs=i,Ec(i))},Mf=()=>{if(sn()==="anchor-top"){if(Us){Rr=!1;return}Rr=!0,Br(),Jn(),Yn(!0)}},Ef=i=>{if(sn()!=="anchor-top"||!Us||qs||Qs())return;let g=Ir===null;for(let m of i){if(!g){m.id===Ir&&(g=!0);continue}if(Gp(m)){if(m.id===Vs)return;Vs=m.id,Ec(m.id);return}}},kf=i=>{let g=new Map;i.forEach(m=>{let b=Ci.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(p.emit("assistant:message",m),!js&&(sn()!=="anchor-top"||ec())&&Mi()&&(Xn+=1,Ti(),tn(),nc(Xn===1?"1 new message below.":`${Xn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),Ci.clear(),g.forEach((m,b)=>{Ci.set(b,m)})},Xs=(i,g)=>{let m=g==="user"?"user":"assistant",b=o.layout?.messages?.[m],A=b?.width??"content",k=b?.maxWidth??(A==="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-${g}`,`persona-message-width-${A}`),i.classList.toggle("persona-justify-end",g==="user"),i.setAttribute("data-message-role",g),i.setAttribute("data-message-width",A),i.style.setProperty("--persona-message-row-max-width",k)},So=(i,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Xs(m,g),m},Lf=(i,g,m)=>{let b=document.createElement("div"),k=(()=>{let W=s.find(Ee=>Ee.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(W,Ee)=>Ee==null?!1:typeof Ee=="string"?(W.textContent=Ee,!0):(W.appendChild(Ee),!0),N=new Set,K=new Map,ae=new Set,ge=s.some(W=>W.renderAskUserQuestion),re=[],we=[],Ue=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(g.forEach(W=>{N.add(W.id),K.set(W.id,W.role);let Ee=ge&&Lo(W),Ne=pt&&W.variant==="approval"&&!!W.approval,Se=!Ee&&W.role==="assistant"&&!W.variant&&Ue&&Ul(W);!Ne&&Gn.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id)),!Se&&xo.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),xo.delete(W.id));let wt=Lo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=jp(W,vi)+wt,Bt=Ee||Ne||Se?null:Vp(wo,W.id,ut);if(Bt){b.appendChild(Bt.cloneNode(!0)),Lo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let ft=null,Jt=s.find(Oe=>!!(W.variant==="reasoning"&&Oe.renderReasoning||W.variant==="tool"&&Oe.renderToolCall||!W.variant&&Oe.renderMessage)),kt=o.layout?.messages;if(Lo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(W.id),i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(Yi(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(W)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=s.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Oe&<.current){let _t=Uo.get(W.id),$t=_t!==ut,vt=null;if($t){let{payload:Ze,complete:We}=nr(W),ht=W.id,zt=()=>lt.current?.getMessages().find(pn=>pn.id===ht);vt=Oe.renderAskUserQuestion({message:W,payload:Ze,complete:We,resolve:pn=>{let Vr=zt();Vr&<.current?.resolveAskUserQuestion(Vr,pn)},dismiss:()=>{let pn=zt();pn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(pn),lt.current?.resolveAskUserQuestion(pn,"(dismissed)"))},config:o})}let ct=_t!=null;if($t&&vt===null&&!ct){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let gt=So(W.id,W.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),re.push({messageId:W.id,fingerprint:ut,bubble:vt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}}else if(Ne){let Oe=s.find(ct=>typeof ct.renderApproval=="function")??a,$t=Gn.get(W.id)!==ut,vt=null;if($t&&Oe?.renderApproval){let ct=W.id,gt=(Ze,We)=>{let ht=lt.current?.getMessages().find(zt=>zt.id===ct);ht?.approval&&(ht.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(ht.id,Ze):lt.current?.resolveApproval(ht.approval,Ze,We))};vt=Oe.renderApproval({message:W,defaultRenderer:()=>ri(W,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if($t&&vt===null)i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id),ft=ri(W,o);else{let ct=So(W.id,W.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),b.appendChild(ct),nt.push({messageId:W.id,fingerprint:ut,bubble:vt});return}}else if(Jt)if(W.variant==="reasoning"&&W.reasoning&&Jt.renderReasoning){if(!ce)return;ft=Jt.renderReasoning({message:W,defaultRenderer:()=>El(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Jt.renderToolCall){if(!ee)return;ft=Jt.renderToolCall({message:W,defaultRenderer:()=>Ll(W,o),config:o})}else Jt.renderMessage&&(ft=Jt.renderMessage({message:W,defaultRenderer:()=>{let Oe=Ml(W,m,kt,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o});return W.role!=="user"&&Nl(Oe,W,o,O),Oe},config:o}));if(!ft&&Se){let Oe=Uu(W);if(Oe){let _t=xo.get(W.id),$t=_t!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&zn.getOptions(Oe.component)?.bubbleChrome!==!1,ct=null;if($t){let gt=zu(Oe,{config:o,message:W,transform:m});if(gt&&Oe.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),We=Ze?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,zt=We?i.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Ze&&zt&&zt!==Ze&&Np(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-${W.id}`,Ze.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),Ze.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}}if(ct||_t!=null){let gt=So(W.id,W.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),we.push({messageId:W.id,fingerprint:ut,bubble:ct});return}}}if(!ft)if(W.variant==="reasoning"&&W.reasoning){if(!ce)return;ft=El(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!ee)return;ft=Ll(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;ft=ri(W,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&W.role==="user"?ft=Oe.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Oe?.renderAssistantMessage&&W.role==="assistant"?ft=Oe.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ft=Ml(W,m,Oe,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o}),W.role!=="user"&&ft&&Nl(ft,W,o,O)}let ke=So(W.id,W.role);ke.appendChild(ft),qp(wo,W.id,ut,ke),b.appendChild(ke)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let Ne=Ee.getAttribute("data-persona-ask-sheet-for");Ne&&!ae.has(Ne)&&rr(Ie.composerOverlay,Ne)}),o.features?.toolCallDisplay?.grouped){let W=[],Ee=[],Ne=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ee){Ee.push(Se);return}Se.variant==="reasoning"&&!ce||((Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),Ee=[])}),(Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),W.forEach(Se=>{let wt=Se.map(Oe=>Array.from(b.children).find(_t=>_t instanceof HTMLElement&&_t.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(wt.length<(Ne?1:2))return;let ut=So(`tool-group-${Se[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Jt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,kt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:Jt,config:o});Q(ft,kt)||(ft.textContent=Jt);let ke=document.createElement("div");ke.className="persona-tool-group-stack persona-flex persona-flex-col",ke.id=`tool-group-stack-${Se[0].id}`,ke.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(ft),Ne||Bt.appendChild(ke),ut.appendChild(Bt),wt[0].before(ut),wt.forEach((Oe,_t)=>{if(Ne){Oe.remove();return}Oe.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),_t<wt.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),ke.appendChild($t)})})}Kp(wo,N);let nn=g.some(W=>W.role==="assistant"&&W.streaming),At=g[g.length-1],Et=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(yn&&g.some(W=>W.role==="user")&&!nn&&!Et){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:xs},Ee=s.find(Se=>Se.renderLoadingIndicator),Ne=null;if(Ee?.renderLoadingIndicator&&(Ne=Ee.renderLoadingIndicator(W)),Ne===null&&o.loadingIndicator?.render&&(Ne=o.loadingIndicator.render(W)),Ne===null&&(Ne=xs()),Ne){let Se=document.createElement("div"),wt=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Se.className=wt?Tl("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),wt&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(Ne);let Bt=So("typing-indicator","assistant");Bt.appendChild(Se),b.appendChild(Bt)}}if(!yn&&g.length>0){let W=g[g.length-1],Ee={config:o,lastMessage:W,messageCount:g.length},Ne=s.find(wt=>wt.renderIdleIndicator),Se=null;if(Ne?.renderIdleIndicator&&(Se=Ne.renderIdleIndicator(Ee)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Ee)),Se){let wt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;wt.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(" "),wt.setAttribute("data-idle-indicator","true"),wt.appendChild(Se);let Bt=So("idle-indicator","assistant");Bt.appendChild(wt),b.appendChild(Bt)}}if(Cd(b),Oa(i,b),zi(i),re.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of re){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Uo.set(W,Ee)))}if(Uo.size>0)for(let W of Uo.keys())N.has(W)||Uo.delete(W);if(we.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of we){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),xo.set(W,Ee)))}if(xo.size>0)for(let W of xo.keys())N.has(W)||xo.delete(W);if(nt.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of nt){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Gn.set(W,Ee)))}if(Gn.size>0)for(let W of Gn.keys())N.has(W)||Gn.delete(W)},Dr=(i,g,m)=>{Lf(i,g,m),dc()},Fr=null,Pf=()=>{if(Fr)return;let i=m=>{let b=m.composedPath();b.includes(He)||et&&b.includes(et)||dt(!1,"user")};Fr=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},kc=()=>{if(!Fr)return;(e.ownerDocument??document).removeEventListener("pointerdown",Fr,!0),Fr=null};ze.push(()=>kc());let Nr=null,If=()=>{if(Nr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};Nr=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Lc=()=>{if(!Nr)return;(e.ownerDocument??document).removeEventListener("keydown",Nr,!0),Nr=null};ze.push(()=>Lc());let Or=!1,Pc=new Set,Rf=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},qo=()=>{if(!F())return;let i=Ie.peekBanner,g=Ie.peekTextNode;if(!i||!g)return;if(X){i.classList.remove("persona-pill-peek--visible");return}let m=O?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Et=m[At];if(Et.role==="assistant"&&Et.content){b=Et;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let A=b.content,k=!!b.streaming,Q=Rf(),N=ja(Q),K=N.type!=="none"?mr(N.type,Q?.plugins):null,ae=K?.isAnimating?.(b)===!0,ge=K!==null&&(k||ae);ge&&K&&!Pc.has(K.name)&&(qa(K,e),Pc.add(K.name));let re=ge&&K?.containerClass?K.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==re&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),re&&we!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),ge?(g.style.setProperty("--persona-stream-step",`${N.speed}ms`),g.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ue=ge?Ua(A,N.buffer,K,b,k):A;if(ge&&N.placeholder==="skeleton"&&k&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Et=hs();Et.classList.add("persona-pill-peek__skeleton"),At.appendChild(Et),Oa(g,At)}else{let At=Math.max(0,Ue.length-100),Et=Ue.length>100?Ue.slice(-100):Ue,W=oo(Et);if(!ge||!K){let Ee=Ue.length>100?`\u2026${Et}`:Et;g.textContent!==Ee&&(g.textContent=Ee)}else{let Ee=W;(K.wrap==="char"||K.wrap==="word")&&(Ee=ms(W,K.wrap,`peek-${b.id}`,{skipTags:K.skipTags,startIndex:At}));let Ne=document.createElement("div");if(Ne.innerHTML=Ee,K.useCaret&&Et.length>0){let Se=Va(),wt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=wt[wt.length-1];ut?.parentNode?ut.parentNode.insertBefore(Se,ut.nextSibling):Ne.appendChild(Se)}Oa(g,Ne),K.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:N.speed,duration:N.duration})}}let nn=yn||Or;i.classList.toggle("persona-pill-peek--visible",nn)};if(F()){let i=Ie.peekBanner;if(i){let b=A=>{A.preventDefault(),A.stopPropagation(),dt(!0,"user")};i.addEventListener("pointerdown",b),ze.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Or||(Or=!0,qo())},m=()=>{Or&&(Or=!1,qo())};de.addEventListener("pointerenter",g),de.addEventListener("pointerleave",m),ze.push(()=>{de.removeEventListener("pointerenter",g),de.removeEventListener("pointerleave",m)}),et&&(et.addEventListener("pointerenter",g),et.addEventListener("pointerleave",m),ze.push(()=>{et.removeEventListener("pointerenter",g),et.removeEventListener("pointerleave",m)}))}let Wf=i=>{let g=o.launcher?.composerBar??{},m=g.expandedSize??"anchored",b=g.bottomOffset??"16px",A=g.collapsedMaxWidth,k=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",N=g.modalMaxWidth??"880px",K=g.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",ge="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 we=et.style;we.bottom=b,we.width=A??""}if(i&&m!=="fullscreen"){if(m==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=N,re.maxWidth=ae,re.maxHeight=K,re.height=K;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${b} + ${ge})`,re.top=Q,re.width=k,re.maxWidth=ae}},_r=()=>{if(!$())return;if(F()){let ae=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=X?"expanded":"collapsed";He.dataset.state=ge,He.dataset.expandedSize=ae,et&&(et.dataset.state=ge,et.dataset.expandedSize=ae),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Wf(X),fe.style.display=X?"flex":"none",Os(),X?(Pf(),If()):(kc(),Lc()),qo();return}let i=Dt(o),g=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=m,k=b&&A&&M,Q=gn(o).reveal;X?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Kt&&(Kt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!k?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.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"),de.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"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=i?"none":"":Kt&&(Kt.style.display=i?"none":""))},dt=(i,g="user")=>{if(!$()||X===i)return;let m=X;X=i,_r();let b=(()=>{let k=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,ae=Q.innerWidth<=K,ge=Dt(o)&&N&&ae,re=F()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||N&&ae&&M||ge||re})();if(X&&b){if(!An){let k=e.getRootNode(),Q=k instanceof ShadowRoot?k.host:e.closest(".persona-host");Q&&(An=vl(Q,o.launcher?.zIndex??Vt))}Sn||(Sn=wl(e.ownerDocument))}else X||(An?.(),An=null,Sn?.(),Sn=null);X&&(jr(),Tc()||(sn()==="follow"?Yn(!0):Ac()));let A={open:X,source:g,timestamp:Date.now()};X&&!m?p.emit("widget:opened",A):!X&&m&&p.emit("widget:closed",A),p.emit("widget:state",{open:X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()})},Ei=i=>{rt(i?"stop":"send"),V&&(V.disabled=i),$s.buttons.forEach(g=>{g.disabled=i}),J.dataset.personaComposerStreaming=i?"true":"false",J.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},ki=()=>{Ge.active||ue&&ue.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ki(),200)});let Ic=()=>{y.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",P.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ue.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=se.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(se.classList.remove("persona-gap-3"),se.classList.add("persona-gap-6")):(se.classList.remove("persona-gap-6"),se.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!O?.isStreaming()&&(Ce.textContent=o.copy?.sendButtonLabel??"Send"),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.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=>{R(g=>({...g,sessionId:i}))}});let To=null,Hf=()=>{To==null&&(To=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(To),To=null;return}let g=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=ya(g-b))})},100))},Li=(i,g)=>{if(Object.is(i,g))return!0;if(i===null||g===null||typeof i!="object"||typeof g!="object")return!1;if(Array.isArray(i)||Array.isArray(g))return!Array.isArray(i)||!Array.isArray(g)||i.length!==g.length?!1:i.every((Q,N)=>Li(Q,g[N]));let m=i,b=g,A=Object.keys(m),k=Object.keys(b);return A.length===k.length&&A.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&Li(m[Q],b[Q]))},Rc=i=>{let{content:g,rawContent:m,llmContent:b,...A}=i;return A},Pi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Ul(i),Bf=(i,g,m)=>{if(i.length!==g.length)return!1;let b=i[m.index],A=g[m.index];return!b||!A||b.id!==m.id||A.id!==m.id?!1:(!Object.is(b.content,A.content)||!Object.is(b.rawContent,A.rawContent)||!Object.is(b.llmContent,A.llmContent))&&Pi(b)&&Pi(A)&&Li(Rc(b),Rc(A))},Wc=null,Ko=null,Mo=null,Rn=null,Js=i=>{Wc=i;let g,m;Ko=null;for(let A=i.length-1;A>=0;A-=1){let k=i[A];if(!g&&k.role==="user"&&(g=k),!m&&k.role==="assistant"&&(m=k),!Ko&&Pi(k)&&(Ko={index:A,id:k.id}),g&&m&&Ko)break}Dr(Pe,i,Z),fl(Pe,mn.artifacts,{suppressTransition:yn}),Hf(),bi(i),Yn(!yn),kf(i),i.length===0&&(Br(),Rr=!0,Us=!1,Vs=null,qs=!1),!wi||js?(wi=!0,Ir=g?.id??null,xi=m?.id??null):g&&g.id!==Ir?(Ir=g.id,Tf(g.id)):m&&m.id!==xi&&Mf(),m&&(xi=m.id),Ef(i);let b=Ge.lastUserMessageId;g&&g.id!==b&&(Ge.lastUserMessageId=g.id,p.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,Si(i),qo()},Ii=()=>{Rn!==null&&(cancelAnimationFrame(Rn),Rn=null);let i=Mo;Mo=null,i&&Js(i)},Hc=()=>{Rn!==null&&cancelAnimationFrame(Rn),Rn=null,Mo=null},Df=i=>{let g=Mo??Wc;if(yn&&g&&Ko&&Bf(g,i,Ko)){Mo=i,Rn===null&&(Rn=requestAnimationFrame(()=>{Rn=null;let m=Mo;Mo=null,m&&Js(m)}));return}if(i.length===0){Hc(),Js(i);return}Ii(),Js(i)};O=new Ta(o,{onMessagesChanged(i){Df(i)},onStatusChanged(i){let g=o.statusIndicator??{};qt(D,(b=>b==="idle"?g.idleText??Lt.idle:b==="connecting"?g.connectingText??Lt.connecting:b==="connected"?g.connectedText??Lt.connected:b==="error"?g.errorText??Lt.error:b==="paused"?g.pausedText??Lt.paused:b==="resuming"?g.resumingText??Lt.resuming:Lt[b])(i),g,i)},onStreamingChanged(i){i||(O?.getMessages().length===0?Hc():Ii()),yn=i,Ei(i),O&&Dr(Pe,O.getMessages(),Z),i||Yn(!0),tn(),nc(i?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Wn(),Qo();break;case"processing":Wn(),Kf();break;case"speaking":Wn(),Gf();break;default:i==="idle"&&O.isBargeInActive()?(Wn(),Qo(),V?.setAttribute("aria-label","End voice session")):(Ge.active=!1,Wn(),In("system"),vn());break}},onArtifactsState(i){mn=i,i.artifacts.length===0&&($o=!1),fl(Pe,i.artifacts,{suppressTransition:yn}),Pn(),Si()},onReconnect(i){let{executionId:g,lastEventId:m}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:g,after:m}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:g,after:m,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:g,after:m})}}),lt.current=O,ze.push(()=>O.cancel());let Ri=null;if(O.onReadAloudChange((i,g)=>{lc=i,cc=g,dc();let m=i??Ri;i&&(Ri=i);let b=m?O.getMessages().find(A=>A.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(Ri=null)}),wi=!0,o.voiceRecognition?.provider?.type==="runtype")try{O.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&O.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Me||o.onSSEEvent)&&O.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),De?.processEvent(i,g),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let Bc=()=>{o.resume&&typeof o.reconnectStream=="function"&&O.resumeFromHandle(o.resume)};w?w.then(i=>{if(i){if(i.metadata&&(u=Vl(i.metadata),E.syncFromMetadata()),i.messages?.length){js=!0;try{O.hydrateMessages(i.messages)}finally{js=!1}}i.artifacts?.length&&O.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Bc()):Bc();let Dc=()=>{!F()||X||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},Ff=(i,g)=>i?g?{refs:[...i.refs,...g.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([i.finalize(),g.finalize()]),A=[];return m.status==="fulfilled"?A.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?A.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),pb(A)}}:i:g,Nf=()=>{let g=ue.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},$r=!1,Of=async i=>{let g=ue.value.trim(),m=Ct?.hasAttachments()??!1,b=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){ue.value="",ue.style.height="auto",zr(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,k=b?.kind==="server"?b.mentions:null,Q=Ff(A,k),N=b?.kind==="prompt"?b.sendText:g,K=!!A&&A.refs.length>0;if(!N&&!m&&!K&&!k)return;Dc();let ae;m&&(ae=[],ae.push(...Ct.getContentParts()),N&&ae.push(ar(N)));let ge=b?.kind==="prompt"?void 0:Nf();ue.value="",ue.style.height="auto",zr(),O.sendMessage(N,{contentParts:ae,mentions:Q??void 0,contentSegments:ge,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),A&&Zt?.clear()},Wi=async i=>{if(!$r){$r=!0;try{await Of(i)}finally{$r=!1}}},Fc=i=>{if(i.preventDefault(),O.isStreaming()){O.cancel(),De?.reset(),Qe?.update();return}$r||Wi()},_f=()=>o.features?.composerHistory!==!1,Hi={...hl},Bi=!1,zr=()=>{Hi={...hl}},$f=()=>O.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),zf=i=>{if(!ue)return;Bi=!0,ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),Bi=!1;let g=ue.value.length;ue.setSelectionRange(g,g)},jf=i=>{Bi||(i.isComposing||Zt?.handleInput(i.inputType??void 0),zr())},Uf=i=>{if(ue&&!(!i.isComposing&&Zt?.handleKeydown(i))){if(_f()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=ue.selectionStart===0&&ue.selectionEnd===0,m=zp({direction:i.key==="ArrowUp"?"up":"down",history:$f(),currentValue:ue.value,atStart:g,state:Hi});if(Hi=m.state,m.handled){i.preventDefault(),m.value!==void 0&&zf(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(O.isStreaming()){i.preventDefault();return}if($r){i.preventDefault();return}zr(),i.preventDefault(),Ce.click()}}},Nc=i=>{i.key!=="Escape"||i.isComposing||O.isStreaming()&&i.composedPath().includes(fe)&&(O.cancel(),De?.reset(),Qe?.update(),zr(),i.preventDefault(),i.stopImmediatePropagation())},Vf=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let g=ib(i.clipboardData);g.length!==0&&(i.preventDefault(),await Ct.handleFiles(g))},cn=null,Tn=!1,Go=null,bt=null,Oc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ys=(i="user")=>{if(Tn||O.isStreaming())return;let g=Oc();if(!g)return;cn=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let A=ue.value;cn.onresult=k=>{let Q="",N="";for(let ae=0;ae<k.results.length;ae++){let ge=k.results[ae],re=ge[0].transcript;ge.isFinal?Q+=re+" ":N=re}let K=A+Q+N;ue.value=K,Go&&clearTimeout(Go),(Q||N)&&(Go=window.setTimeout(()=>{ue.value.trim()&&cn&&Tn&&(Zn(),Wi({viaVoice:!0}))},b))},cn.onerror=k=>{k.error!=="no-speech"&&Zn()},cn.onend=()=>{if(Tn){let k=ue.value.trim();k&&k!==A.trim()&&Wi({viaVoice:!0}),Zn()}};try{if(cn.start(),Tn=!0,Ge.active=!0,i!=="system"&&(Ge.manuallyDeactivated=!1),In(i),vn(),V){let k=o.voiceRecognition??{};bt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??o.sendButton?.size??"40")||24};let Q=k.recordingBackgroundColor,N=k.recordingIconColor,K=k.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let ae=V.querySelector("svg");ae&&ae.setAttribute("stroke",N)}K&&(V.style.borderColor=K),V.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(i="user")=>{if(Tn){if(Tn=!1,Go&&(clearTimeout(Go),Go=null),cn){try{cn.stop()}catch{}cn=null}if(Ge.active=!1,In(i),vn(),V){if(V.classList.remove("persona-voice-recording"),bt){V.style.backgroundColor=bt.backgroundColor,V.style.color=bt.color,V.style.borderColor=bt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",bt.color||"currentColor"),bt=null}V.setAttribute("aria-label","Start voice recognition")}}},qf=(i,g)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",A=i?.provider?.type==="custom";if(!(m||b||A))return null;let Q=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let K=i?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",K);let ae=i?.iconName??"mic",ge=g?.size??"40px",re=i?.iconSize??ge,we=parseFloat(re)||24,Ue=i?.backgroundColor??g?.backgroundColor,pt=i?.iconColor??g?.textColor;N.style.width=re,N.style.height=re,N.style.minWidth=re,N.style.minHeight=re,N.style.fontSize="18px",N.style.lineHeight="1",pt?N.style.color=pt:N.style.color="var(--persona-text, #111827)";let nn=ie(ae,we,pt||"currentColor",1.5);nn?N.appendChild(nn):N.textContent="\u{1F3A4}",Ue?N.style.backgroundColor=Ue:N.style.backgroundColor="",i?.borderWidth&&(N.style.borderWidth=i.borderWidth,N.style.borderStyle="solid"),i?.borderColor&&(N.style.borderColor=i.borderColor),i?.paddingX&&(N.style.paddingLeft=i.paddingX,N.style.paddingRight=i.paddingX),i?.paddingY&&(N.style.paddingTop=i.paddingY,N.style.paddingBottom=i.paddingY),Q.appendChild(N);let At=i?.showTooltip??!1;return Ot({anchor:N,trigger:Q,text:()=>N.getAttribute("aria-label")??K,enabled:At}),{micButton:N,micButtonWrapper:Q}},Di=()=>{if(!V||bt)return;let i=o.voiceRecognition??{};bt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Fi=(i,g)=>{if(!V)return;let m=V.querySelector("svg");m&&m.remove();let b=bt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ie(i,b,g,1.5);A&&V.appendChild(A)},Zs=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qo=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(Zs(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let A=V.querySelector("svg");A&&A.setAttribute("stroke",m)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Kf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??bt?.color??"",A=i.processingBackgroundColor??bt?.backgroundColor??"",k=i.processingBorderColor??bt?.borderColor??"";Zs(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=k;let Q=b||"currentColor";V.style.color=Q,Fi(m,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Gf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,A=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??bt?.color??"":bt?.color??""),k=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":bt?.borderColor??"");Zs(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=k,V.style.borderColor=Q;let N=A||"currentColor";V.style.color=N,Fi(b,N);let K=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",K),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Wn=()=>{V&&(Zs(),bt&&(V.style.backgroundColor=bt.backgroundColor??"",V.style.color=bt.color??"",V.style.borderColor=bt.borderColor??"",Fi(bt.iconName,bt.color||"currentColor"),bt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},ea=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=O.getVoiceStatus(),g=O.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()});return}O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),Ge.manuallyDeactivated=!O.isVoiceActive(),vn(),In("user"),O.isVoiceActive()?Qo():Wn()});return}if(Tn){let i=ue.value.trim();Ge.manuallyDeactivated=!0,vn(),Zn("user"),i&&(ue.value="",ue.style.height="auto",O.sendMessage(i))}else Ge.manuallyDeactivated=!1,vn(),Ys("user")};rc=ea,V&&(V.addEventListener("click",ea),ze.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Wn()):Zn("system"),V&&V.removeEventListener("click",ea)}));let Qf=p.on("assistant:complete",()=>{yc&&(Ge.active||Ge.manuallyDeactivated||yc==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("auto"),O.isVoiceActive()&&Qo()}):Ys("auto"))},600))});ze.push(Qf);let Xf=p.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ze.push(Xf);let _c=()=>{dt(!X,"user")},Ft=null,Kt=null;if(M&&!F()){let{instance:i,element:g}=Cl({config:o,plugins:s,onToggle:_c});Ft=i,i||(Kt=g)}Ft?e.appendChild(Ft.element):Kt&&e.appendChild(Kt),_r(),bi(),Ic(),Ei(O.isStreaming()),Tc()||(sn()==="follow"?Yn(!0):Ac()),vf(),G&&(!M||F()?setTimeout(()=>ki(),0):X&&setTimeout(()=>ki(),200));let jr=()=>{if(F()){_o(),_r();return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=k,N=A&&Q&&M;try{if(N){Er(),kr=Ns();return}let K=!1;oe&&(oe=!1,Er(),K=!0);let ae=Ns();if(!K&&ae!==kr&&(Er(),K=!0),kr=ae,K&&hi(),!M&&!i){de.style.height="",de.style.width="";return}if(!g&&!i){let re=o?.launcher?.width??o?.launcherWidth??$n;de.style.width=re,de.style.maxWidth=re}if(Fs(),!m){let ge=b.innerHeight,re=64,we=o.launcher?.heightOffset??0,Ue=Math.max(200,ge-re),pt=Math.min(640,Ue),nt=Math.max(200,pt-we);de.style.height=`${nt}px`}}finally{if(_o(),_r(),X&&M){let ae=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,we=Dt(o)&&re&&ae,Ue=ge||re&&ae&&M||we;if(Ue&&!Sn){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!An&&(An=vl(nt,o.launcher?.zIndex??Vt)),Sn=wl(e.ownerDocument)}else Ue||(An?.(),An=null,Sn?.(),Sn=null)}}};jr();let $c=e.ownerDocument.defaultView??window;if($c.addEventListener("resize",jr),ze.push(()=>$c.removeEventListener("resize",jr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{_o()});i.observe(J),ze.push(()=>i.disconnect())}an=se.scrollTop;let zc=En(se),jc=()=>{let i=se.scrollTop,g=En(se),m=g<zc;if(zc=g,!Un()){an=i,tn();return}let{action:b,nextLastScrollTop:A}=$a({following:en.isFollowing(),currentScrollTop:i,lastScrollTop:an,nearBottom:uo(se,Ks),userScrollThreshold:yf,isAutoScrolling:ln||zs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=A,b==="resume"){Qs()||Jn();return}b==="pause"&&Hr()};if(se.addEventListener("scroll",jc,{passive:!0}),ze.push(()=>se.removeEventListener("scroll",jc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Sf(),zi(Pe)});i.observe(Pe),i.observe(se),ze.push(()=>i.disconnect())}let Uc=()=>{Un()&&en.isFollowing()&&Qs()&&Hr()},Vc=se.ownerDocument;Vc.addEventListener("selectionchange",Uc),ze.push(()=>{Vc.removeEventListener("selectionchange",Uc)});let Jf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qc=i=>{Jf.has(i.key)&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())},Kc=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())};se.addEventListener("keydown",qc),se.addEventListener("focusin",Kc),ze.push(()=>{se.removeEventListener("keydown",qc),se.removeEventListener("focusin",Kc)});let Gc=i=>{if(i.deltaY!==0&&Ao(),!Un())return;let g=za({following:en.isFollowing(),deltaY:i.deltaY,nearBottom:uo(se,Ks),resumeWhenNearBottom:!0});g==="pause"?Hr():g==="resume"&&!Qs()&&Jn()};se.addEventListener("wheel",Gc,{passive:!0}),se.addEventListener("touchmove",Ao,{passive:!0}),se.addEventListener("pointerdown",Ao,{passive:!0}),ze.push(()=>{se.removeEventListener("touchmove",Ao),se.removeEventListener("pointerdown",Ao)}),ze.push(()=>se.removeEventListener("wheel",Gc)),Tt.addEventListener("click",()=>{Br(),se.scrollTop=se.scrollHeight,an=se.scrollTop,Jn(),Yn(!0),tn()}),ze.push(()=>Tt.remove()),ze.push(()=>{wc(),Br()});let Qc=()=>{T&&(vo&&(T.removeEventListener("click",vo),vo=null),$()?(T.style.display="",vo=()=>{dt(!1,"user")},T.addEventListener("click",vo)):T.style.display="none")};Qc(),(()=>{let{clearChatButton:i}=Ie;i&&i.addEventListener("click",()=>{O.clearMessages(),wo.clear(),Jn(),rr(Ie.composerOverlay);try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()})})(),S&&S.addEventListener("submit",Fc);let Xc=[["keydown",Uf],["input",jf],["paste",Vf],["focus",uf]],Jc=i=>{if(i)for(let[g,m]of Xc)i.addEventListener(g,m)},Yc=i=>{if(i)for(let[g,m]of Xc)i.removeEventListener(g,m)};Jc(ue),Zt?.onComposerSwap((i,g)=>{Yc(g),ue=i,Jc(i)});let Zc=e.ownerDocument??document;Zc.addEventListener("keydown",Nc,!0);let ed="persona-attachment-drop-active",Ur=0,Ni=()=>{Ur=0,fe.classList.remove(ed)},Xo=()=>o.attachments?.enabled===!0&&Ct!==null,td=i=>{!li(i.dataTransfer)||!Xo()||(Ur++,Ur===1&&fe.classList.add(ed))},nd=i=>{!li(i.dataTransfer)||!Xo()||(Ur--,Ur<=0&&Ni())},od=i=>{!li(i.dataTransfer)||!Xo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},rd=i=>{if(!li(i.dataTransfer)||!Xo())return;i.preventDefault(),i.stopPropagation(),Ni();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Ct.handleFiles(g)},eo=!0;fe.addEventListener("dragenter",td,eo),fe.addEventListener("dragleave",nd,eo),e.addEventListener("dragover",od,eo),e.addEventListener("drop",rd,eo);let ta=e.ownerDocument,sd=i=>{Xo()&&i.preventDefault()},ad=i=>{Xo()&&i.preventDefault()};ta.addEventListener("dragover",sd),ta.addEventListener("drop",ad),ze.push(()=>{S&&S.removeEventListener("submit",Fc),Yc(ue),Zc.removeEventListener("keydown",Nc,!0),Zt?.destroy()}),ze.push(()=>{fe.removeEventListener("dragenter",td,eo),fe.removeEventListener("dragleave",nd,eo),e.removeEventListener("dragover",od,eo),e.removeEventListener("drop",rd,eo),ta.removeEventListener("dragover",sd),ta.removeEventListener("drop",ad),Ni()}),ze.push(()=>{O.cancel()}),Ft?ze.push(()=>{Ft?.destroy()}):Kt&&ze.push(()=>{Kt?.remove()});let Mt={update(i){let g=o.toolCall,m=o.messageActions,b=o.layout?.messages,A=o.colorScheme,k=o.loadingIndicator,Q=o.iterationDisplay,N=o.features?.showReasoning,K=o.features?.showToolCalls,ae=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Nu({...o,features:r},i),r=o.features,o=Dl(o),Os(),cs(e,o),Ts(e,o),Ms(e,o),Pn(),o.colorScheme!==A&&hc();let we=_l.getForInstance(o.plugins);s.length=0,s.push(...we),M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,Y=o.features?.scrollToBottom??{};let Ue=sn();pe=o.features?.scrollBehavior??{},Ue!==sn()&&(Br(),Jn()),oc(),tn();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(Me||(ve=new As(ye),Me=new Cs(je,ve),De=De??new Ss,ve.open().then(()=>Me?.restore()).catch(()=>{}),O.setSSEEventCallback((ne,Ke)=>{o.onSSEEvent?.(ne,Ke),De?.processEvent(ne,Ke),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!tt&&z){let ne=o.features?.eventStream?.classNames,Ke="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne?.toggleButton?" "+ne.toggleButton:"");tt=h("button",Ke),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let mt=ie("activity","18px","currentColor",1.5);mt&&tt.appendChild(mt);let ot=Ie.clearChatButtonWrapper,st=Ie.closeButtonWrapper,jt=ot||st;jt&&jt.parentNode===z?z.insertBefore(tt,jt):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}}else!le&&pt&&(Tr(),tt&&(tt.remove(),tt=null),Me?.clear(),ve?.destroy(),Me=null,ve=null,De?.reset(),De=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Ft&&!Kt){let{instance:ne,element:Ke}=Cl({config:o,plugins:s,onToggle:_c});Ft=ne,ne||(Kt=Ke),e.appendChild(Ke)}Ft&&Ft.update(o),q&&o.launcher?.title!==void 0&&(q.textContent=o.launcher.title),H&&o.launcher?.subtitle!==void 0&&(H.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==U&&z){let ne=nt?Qa(o,nt,{showClose:$(),onClose:()=>dt(!1,"user")}):Ho({config:o,showClose:$(),onClose:()=>dt(!1,"user")});xt.replaceHeader(ne),z=xt.header.element,I=xt.header.iconHolder,q=xt.header.headerTitle,H=xt.header.headerSubtitle,T=xt.header.closeButton,U=nt?.layout}else if(nt){if(I&&(I.style.display=nt.showIcon===!1?"none":""),q&&(q.style.display=nt.showTitle===!1?"none":""),H&&(H.style.display=nt.showSubtitle===!1?"none":""),T){let ne=$()&&nt.showCloseButton!==!1;T.style.display=ne?"":"none"}if(Ie.clearChatButtonWrapper){let ne=nt.showClearChat;if(ne!==void 0){Ie.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ke}=Ie;Ke&&!Ke.classList.contains("persona-absolute")&&(ne?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;z&&(z.style.display=At?"":"none");let Et=o.layout?.showFooter!==!1;J&&(J.style.display=Et?"":"none"),_o(),tn(),M!==j?M?dt(_,"auto"):(X=!0,_r()):_!==x&&dt(_,"auto"),x=_,j=M,jr(),Qc();let Ne=JSON.stringify(o.toolCall)!==JSON.stringify(g),Se=JSON.stringify(o.messageActions)!==JSON.stringify(m),wt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ut=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Bt=o.iterationDisplay!==Q,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);(Ne||Se||wt||ut||Bt||ft)&&O&&(vi++,Dr(Pe,O.getMessages(),Z));let kt=o.features?.streamAnimation?.type;if(kt!==re&&kt&&kt!=="none"){let ne=mr(kt,o.features?.streamAnimation?.plugins);ne&&qa(ne,e)}let ke=o.launcher??{},Oe=ke.headerIconHidden??!1,_t=o.layout?.header?.showIcon,$t=Oe||_t===!1,vt=ke.headerIconName,ct=ke.headerIconSize??"48px";if(I){let ne=fe.querySelector(".persona-border-b-persona-divider"),Ke=ne?.querySelector(".persona-flex-col");if($t)I.style.display="none",ne&&Ke&&!ne.contains(Ke)&&ne.insertBefore(Ke,ne.firstChild);else{if(I.style.display="",I.style.height=ct,I.style.width=ct,ne&&Ke&&(ne.contains(I)?I.nextSibling!==Ke&&(I.remove(),ne.insertBefore(I,Ke)):ne.insertBefore(I,Ke)),vt){let ot=parseFloat(ct)||24,st=ie(vt,ot*.6,"currentColor",1);st?I.replaceChildren(st):I.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let ot=I.querySelector("img");if(ot)ot.src=ke.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let st=document.createElement("img");st.src=ke.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,I.replaceChildren(st)}}else{let ot=I.querySelector("svg"),st=I.querySelector("img");(ot||st)&&I.replaceChildren(),I.textContent=ke.agentIconText??"\u{1F4AC}"}let mt=I.querySelector("img");mt&&(mt.style.height=ct,mt.style.width=ct)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(q&&(q.style.display=gt===!1?"none":""),H&&(H.style.display=Ze===!1?"none":""),T){let ne=$()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ne?"":"none";let Ke=ke.closeButtonSize??"32px",mt=ke.closeButtonPlacement??"inline";T.style.height=Ke,T.style.width=Ke;let{closeButtonWrapper:ot}=Ie,st=mt==="top-right",jt=ot?.classList.contains("persona-absolute");if(ot&&st!==jt)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(ot);else{let no=ke.clearChat?.placement??"inline",Kr=ke.clearChat?.enabled??!0;ot.className=Kr&&no==="inline"?"":"persona-ml-auto";let id=fe.querySelector(".persona-border-b-persona-divider");id&&id.appendChild(ot)}if(T.style.color=ke.closeButtonColor||Qt.actionIconColor,ke.closeButtonBackgroundColor?(T.style.backgroundColor=ke.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let no=ke.closeButtonBorderWidth||"0px",Kr=ke.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${Kr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");ke.closeButtonBorderRadius?(T.style.borderRadius=ke.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(T.style.paddingLeft=ke.closeButtonPaddingX,T.style.paddingRight=ke.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),ke.closeButtonPaddingY?(T.style.paddingTop=ke.closeButtonPaddingY,T.style.paddingBottom=ke.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let on=ke.closeButtonIconName??"x",wn=ke.closeButtonIconText??"\xD7";T.innerHTML="";let Nt=ie(on,"28px","currentColor",1);Nt?(Nt.style.display="block",T.appendChild(Nt)):T.textContent=wn;let Ut=ke.closeButtonTooltipText??"Close chat",Bn=ke.closeButtonShowTooltip??!0;T.setAttribute("aria-label",Ut),ot&&Ot({anchor:T,trigger:ot,text:()=>T?.getAttribute("aria-label")??Ut,enabled:Bn})}let{clearChatButton:We,clearChatButtonWrapper:ht}=Ie;if(We){let ne=ke.clearChat??{},Ke=ne.enabled??!0,mt=o.layout?.header?.showClearChat,ot=mt!==void 0?mt:Ke,st=ne.placement??"inline";if(ht){ht.style.display=ot?"":"none";let{closeButtonWrapper:jt}=Ie;!F()&&jt&&!jt.classList.contains("persona-absolute")&&(ot?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let on=st==="top-right",wn=ht.classList.contains("persona-absolute");if(!F()&&on!==wn&&ot){if(ht.remove(),on)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",fe.style.position="relative",fe.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let Ut=fe.querySelector(".persona-border-b-persona-divider"),Bn=Ie.closeButtonWrapper;Ut&&Bn&&Bn.parentElement===Ut?Ut.insertBefore(ht,Bn):Ut&&Ut.appendChild(ht)}let Nt=Ie.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(on?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!F()){let no=ne.size??"32px";We.style.height=no,We.style.width=no}let jt=ne.iconName??"refresh-cw",on=ne.iconColor??"";We.style.color=on||Qt.actionIconColor,We.innerHTML="";let wn=F()?"14px":"20px",Nt=ie(jt,wn,"currentColor",1);if(Nt&&(Nt.style.display="block",We.appendChild(Nt)),ne.backgroundColor?(We.style.backgroundColor=ne.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let no=ne.borderWidth||"0px",Kr=ne.borderColor||"transparent";We.style.border=`${no} solid ${Kr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");ne.borderRadius?(We.style.borderRadius=ne.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),ne.paddingX?(We.style.paddingLeft=ne.paddingX,We.style.paddingRight=ne.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),ne.paddingY?(We.style.paddingTop=ne.paddingY,We.style.paddingBottom=ne.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Ut=ne.tooltipText??"Clear chat",Bn=ne.showTooltip??!0;We.setAttribute("aria-label",Ut),ht&&Ot({anchor:We,trigger:ht,text:()=>We?.getAttribute("aria-label")??Ut,enabled:Bn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],pn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick];E=jl({parsers:zt,handlers:pn,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=Gu(o,E,Ae),O.updateConfig(o),Dr(Pe,O.getMessages(),Z),bi(),Ic(),Ei(O.isStreaming());let Vr=o.voiceRecognition?.enabled===!0,na=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),St=o.voiceRecognition?.provider?.type==="runtype";if(Vr&&(na||St))if(!V||!_e){let ne=qf(o.voiceRecognition,o.sendButton);ne&&(V=ne.micButton,_e=ne.micButtonWrapper,Re.insertBefore(_e,te),V.addEventListener("click",ea),V.disabled=O.isStreaming())}else{let ne=o.voiceRecognition??{},Ke=o.sendButton??{},mt=ne.iconName??"mic",ot=Ke.size??"40px",st=ne.iconSize??ot,jt=parseFloat(st)||24;V.style.width=st,V.style.height=st,V.style.minWidth=st,V.style.minHeight=st;let on=ne.iconColor??Ke.textColor;V.innerHTML="";let wn=ie(mt,jt,on||"currentColor",1.5);wn?V.appendChild(wn):V.textContent="\u{1F3A4}";let Nt=ne.backgroundColor??Ke.backgroundColor;Nt?V.style.backgroundColor=Nt:V.style.backgroundColor="",on?V.style.color=on:V.style.color="var(--persona-text, #111827)",ne.borderWidth?(V.style.borderWidth=ne.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ne.borderColor?V.style.borderColor=ne.borderColor:V.style.borderColor="",ne.paddingX?(V.style.paddingLeft=ne.paddingX,V.style.paddingRight=ne.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.paddingY?(V.style.paddingTop=ne.paddingY,V.style.paddingBottom=ne.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Ut=ne.tooltipText??"Start voice recognition",Bn=ne.showTooltip??!1;V.setAttribute("aria-label",Ut),_e&&Ot({anchor:V,trigger:_e,text:()=>V?.getAttribute("aria-label")??Ut,enabled:Bn}),_e.style.display="",V.disabled=O.isStreaming()}else V&&_e&&(_e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()&&O.toggleVoice():Tn&&Zn());if(o.attachments?.enabled===!0){if(!$e||!be){let ne=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Rt||(Rt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Rt.style.display="none",S.insertBefore(Rt,ue)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),S.insertBefore(Fe,ue)),$e=h("div","persona-send-button-wrapper"),be=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),be.type="button",be.setAttribute("aria-label",ne.buttonTooltipText??"Attach file");let ot=ne.buttonIconName??"paperclip",st=mt,jt=parseFloat(st)||40,on=Math.round(jt*.6);be.style.width=st,be.style.height=st,be.style.minWidth=st,be.style.minHeight=st,be.style.fontSize="18px",be.style.lineHeight="1";let wn=ie(ot,on,"currentColor",1.5);wn?be.appendChild(wn):be.textContent="\u{1F4CE}",be.addEventListener("click",Ut=>{Ut.preventDefault(),Fe?.click()}),$e.appendChild(be);let Nt=ne.buttonTooltipText??"Attach file";Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Nt}),Je?Je.append($e):S.appendChild($e),!Ct&&Fe&&Rt&&(Ct=as.fromConfig(ne),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",async()=>{Ct&&Fe?.files&&(await Ct.handleFileSelect(Fe.files),Fe.value="")}))}else{$e.style.display="";let ne=o.attachments??{};Fe&&(Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Qu(o.attachments?.dropOverlay)),be){let ne=o.attachments??{},Ke=ne.buttonTooltipText??"Attach file";be.setAttribute("aria-label",Ke),be.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,ot=ie(ne.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);ot?be.appendChild(ot):be.textContent="\u{1F4CE}",$e&&Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Ke})}}else $e&&($e.style.display="none"),Ct&&Ct.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Wt=o.sendButton??{},qr=Wt.useIcon??!1,ra=Wt.iconText??"\u2191",Jo=Wt.iconName,sa=Wt.tooltipText??"Send message",Oi=Wt.showTooltip??!1,Eo=Wt.size??"40px",Hn=Wt.backgroundColor,ko=Wt.textColor;if(qr){if(Ce.style.width=Eo,Ce.style.height=Eo,Ce.style.minWidth=Eo,Ce.style.minHeight=Eo,Ce.style.fontSize="18px",Ce.style.lineHeight="1",ko?Ce.style.color=ko:Ce.style.color="var(--persona-button-primary-fg, #ffffff)",!O.isStreaming())if(Ce.innerHTML="",Jo){let ne=parseFloat(Eo)||24,Ke=ko?.trim()||"currentColor",mt=ie(Jo,ne,Ke,2);mt?Ce.appendChild(mt):Ce.textContent=ra}else Ce.textContent=ra;Ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-primary")):(Ce.style.backgroundColor="",Ce.classList.add("persona-bg-persona-primary"))}else Ce.textContent=o.copy?.sendButtonLabel??"Send",Ce.style.width="",Ce.style.height="",Ce.style.minWidth="",Ce.style.minHeight="",Ce.style.fontSize="",Ce.style.lineHeight="",Ce.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-accent")):Ce.classList.add("persona-bg-persona-accent"),ko?Ce.style.color=ko:Ce.classList.add("persona-text-white");Wt.borderWidth?(Ce.style.borderWidth=Wt.borderWidth,Ce.style.borderStyle="solid"):(Ce.style.borderWidth="",Ce.style.borderStyle=""),Wt.borderColor?Ce.style.borderColor=Wt.borderColor:Ce.style.borderColor="",Wt.paddingX?(Ce.style.paddingLeft=Wt.paddingX,Ce.style.paddingRight=Wt.paddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),Wt.paddingY?(Ce.style.paddingTop=Wt.paddingY,Ce.style.paddingBottom=Wt.paddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),O.isStreaming()||Ce.setAttribute("aria-label",sa),te&&Ot({anchor:Ce,trigger:te,text:()=>Ce.getAttribute("aria-label")??sa,enabled:Oi});let aa=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);aa?(Pe.style.maxWidth=aa,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",S&&(S.style.maxWidth=aa,S.style.marginLeft="auto",S.style.marginRight="auto"),it&&(it.style.maxWidth=aa,it.style.marginLeft="auto",it.style.marginRight="auto")):(Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",S&&(S.style.maxWidth="",S.style.marginLeft="",S.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let to=o.statusIndicator??{},Yf=to.visible??!0;if(D.style.display=Yf?"":"none",O){let ne=O.getStatus();qt(D,(mt=>mt==="idle"?to.idleText??Lt.idle:mt==="connecting"?to.connectingText??Lt.connecting:mt==="connected"?to.connectedText??Lt.connected:mt==="error"?to.errorText??Lt.error:Lt[mt])(ne),to,ne)}D.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Zf=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";D.classList.add(Zf)},open(){$()&&dt(!0,"api")},close(){$()&&dt(!1,"api")},toggle(){$()&&dt(!X,"api")},reconnect(){O.reconnectNow()},clearChat(){Ln=!1,O.clearMessages(),wo.clear(),Jn();try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()},setMessage(i){return!ue||O.isStreaming()?!1:(!X&&$()&&dt(!0,"system"),ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(O.isStreaming())return!1;let g=i?.trim()||ue.value.trim();return g?(!X&&$()&&dt(!0,"system"),ue.value="",ue.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return O.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()||(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("user"),O.isVoiceActive()&&Qo()})),!0):Tn?!0:Oc()?(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),Ys("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()}),!0):!1:Tn?(Ge.manuallyDeactivated=!0,vn(),Zn("user"),!0):!1},injectMessage(i){return!X&&$()&&dt(!0,"system"),O.injectMessage(i)},injectAssistantMessage(i){!X&&$()&&dt(!0,"system");let g=O.injectAssistantMessage(i);return me&&(me=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(i){return!X&&$()&&dt(!0,"system"),O.injectUserMessage(i)},injectSystemMessage(i){return!X&&$()&&dt(!0,"system"),O.injectSystemMessage(i)},injectMessageBatch(i){return!X&&$()&&dt(!0,"system"),O.injectMessageBatch(i)},injectComponentDirective(i){return!X&&$()&&dt(!0,"system"),O.injectComponentDirective(i)},injectTestMessage(i){!X&&$()&&dt(!0,"system"),O.injectTestEvent(i)},async connectStream(i,g){return O.connectStream(i,g)},__pushEventStreamEvent(i){Me&&(De?.processEvent(i.type,i.payload),Me.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||!Me||ui()},hideEventStream(){Ve&&Tr()},isEventStreamVisible(){return Ve},showArtifacts(){Xt(o)&&(Ln=!1,$o=!0,Pn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Ln=!0,Pn())},upsertArtifact(i){return Xt(o)?(ro(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ln=!1,$o=!0),O.upsertArtifact(i)):null},selectArtifact(i){Xt(o)&&O.selectArtifact(i)},clearArtifacts(){Xt(o)&&O.clearArtifacts()},getArtifacts(){return O?.getArtifacts()??[]},getSelectedArtifactId(){return O?.getSelectedArtifactId()??null},focusInput(){return M&&!X&&!F()||!ue?!1:(ue.focus(),!0)},async resolveApproval(i,g,m){let A=O.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!A?.approval)throw new Error(`Approval not found: ${i}`);if(A.approval.toolType==="webmcp"){O.resolveWebMcpApproval(A.id,g);return}return O.resolveApproval(A.approval,g,m)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){R(i)},on(i,g){return p.on(i,g)},off(i,g){p.off(i,g)},isOpen(){return $()&&X},isVoiceActive(){return Ge.active},toggleReadAloud(i){O.toggleReadAloud(i)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(i){return O.getReadAloudState(i)},onReadAloudChange(i){return O.onReadAloudChange(i)},getState(){return{open:$()&&X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()}},showCSATFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=Vu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitCSATFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=qu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitNPSFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return O.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return O.submitNPSFeedback(i,g)},destroy(){Ii(),To!=null&&(clearInterval(To),To=null),ze.forEach(i=>i()),He.remove(),et?.remove(),Ft?.destroy(),Kt?.remove(),vo&&T.removeEventListener("click",vo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Mt,getMessages:Mt.getMessages,getStatus:Mt.getStatus,getMetadata:Mt.getPersistentMetadata,updateMetadata:Mt.updatePersistentMetadata,clearHistory:()=>Mt.clearChat(),setVoiceActive:m=>m?Mt.startVoiceRecognition():Mt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ze.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.focusInput()};if(window.addEventListener("persona:focusInput",g),ze.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let N=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.showEventStream()},K=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",K),ze.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",K)})}let m=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.showArtifacts()},b=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.hideArtifacts()},A=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||K?.artifact&&Mt.upsertArtifact(K.artifact)},k=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||typeof K?.id=="string"&&Mt.selectArtifact(K.id)},Q=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",Q),ze.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",Q)})}let dn=lb(o.persistState);if(dn&&$()){let i=cb(dn.storage),g=`${dn.keyPrefix}widget-open`,m=`${dn.keyPrefix}widget-voice`,b=`${dn.keyPrefix}widget-voice-mode`;if(i){let A=dn.persist?.openState&&i.getItem(g)==="true",k=dn.persist?.voiceState&&i.getItem(m)==="true",Q=dn.persist?.voiceState&&i.getItem(b)==="true";if(A&&setTimeout(()=>{Mt.open(),setTimeout(()=>{if(k||Q)Mt.startVoiceRecognition();else if(dn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),dn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(g,"true")}),p.on("widget:closed",()=>{i.setItem(g,"false")})),dn.persist?.voiceState&&(p.on("voice:state",N=>{i.setItem(m,N.active?"true":"false")}),p.on("user:message",N=>{i.setItem(b,N.viaVoice?"true":"false")})),dn.clearOnChatClear){let N=()=>{i.removeItem(g),i.removeItem(m),i.removeItem(b)},K=()=>N();window.addEventListener("persona:clear-chat",K),ze.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(f&&$()&&setTimeout(()=>{Mt.open()},0),qo(),!hf){let i=la(()=>{O&&(vi++,wo.clear(),Dr(Pe,O.getMessages(),Z))});ze.push(i)}return Mt};var Ju=(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},ub=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},fb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gb=(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 s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},Yu=(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"},Ql=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=""},Zu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ql(e)},ql=e=>{e.style.transition=""},Kl=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=""},Gl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ci=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},mb=(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))},hb=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},yb=e=>{let t=dr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(t,r)??r;return{inset:o(n?.inset,La),canvasBackground:o(n?.canvasBackground,Pa)}},ef=(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},bb=(e,t,n,o,r,s,a,l)=>{let p=gn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";mb(e,t,n,o,d),hb(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"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,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,R=f!=null?f.innerWidth<=C:!1;if(v&&R&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Kl(t),ql(o),Zu(o),Gl(n),ci(r,o),ef(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(s?.launcher?.zIndex??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Zu(o),ub(o,p.maxHeight),ef(o,c&&a,u,w),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Kl(t),ql(o),Gl(n),ci(r,o);let L=p.animate?"transform 180ms ease":"none",E=p.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":E;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=L,o.style.transform=M,o.style.pointerEvents=a?"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",ql(o),Ql(o),ci(r,o);let L=Ju(p.width,e.clientWidth),E=Math.max(0,e.clientWidth),M=p.animate?"margin-left 180ms ease":"none",_=p.side==="right"?a?-L:0:a?0:-L;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=`${E+L}px`,t.style.transition=M,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}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=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Kl(t),Ql(o),Gl(n),ci(r,o);let L=p.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?p.width:"0px",M=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",fb(o,p.maxHeight),o.style.overflow=L||_?"hidden":"visible",o.style.transition=M,L){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=c?`calc(${Ju(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},vb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Yu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Yu(n,o)},destroy(){n.remove()}}},wb=(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 s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let w=null,f=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?yb(t):null};C();let R=()=>{bb(a,l,p,d,c,t,u,v)},B=null,L=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=Ia(()=>{C(),R()}))},E=()=>{f(),gn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{R()}),w.observe(a)))},M=!1,_=()=>{R(),E(),u&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,gb(a,gn(t)))},G=a.ownerDocument.defaultView,x=()=>{_()};return G?.addEventListener("resize",x),gn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),_(),L(),{mode:"docked",host:c,shell:a,syncWidgetState(j){let U=j.launcherEnabled?j.open:!0;u!==U&&(u=U,_())},updateConfig(j){t=j,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),L()},destroy(){G?.removeEventListener("resize",x),B?.(),B=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},tf=(e,t)=>Dt(t)?wb(e,t):vb(e,t);var ks={desktop:{w:1280,h:800},mobile:{w:390,h:844}},nf=.15,of=1.5,Xl="persona-preview-shell-theme",xb={load:()=>null,save:()=>{},clear:()=>{}},Cb=["How do I get started?","Pricing & plans","Talk to support"];function Jl(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ab(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function rf(e){let t=Ab(e);return`* { box-sizing: border-box; }
|
|
139
|
+
${bt?"background: transparent !important;":""}
|
|
140
|
+
`}if(!b&&!i){let St="max-height: -moz-available !important; max-height: stretch !important;",en=f?"":"padding-top: 1.25em !important;",ca=f?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;Be.style.cssText+=St+en+ca}fn()};qs(),ys(e,o),Ws(e,o),Hs(e,o),Ir=()=>{qs(),ys(e,o),Ws(e,o),Hs(e,o),Os?e.style.setProperty("--persona-artifact-welded-outer-radius",Os):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Oe=[];Oe.push(()=>{document.removeEventListener("keydown",vc)}),Oe.push(()=>{kr!==null&&clearTimeout(kr)});let Mn=null,En=null;Oe.push(()=>{Mn?.(),Mn=null,En?.(),En=null}),Pr&&Oe.push(()=>{Pr?.disconnect(),Pr=null}),Oe.push(()=>{Hr?.(),Hr=null,Si(),ht&&(ht.remove(),ht=null),Ge?.element.style.removeProperty("width"),Ge?.element.style.removeProperty("maxWidth")}),ie&&Oe.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),qe?.destroy(),qe=null,Ae?.destroy(),Ae=null,xe=null});let xo=null,Cc=()=>{xo&&(xo(),xo=null),o.colorScheme==="auto"&&(xo=Fa(()=>{ys(e,o)}))};Cc(),Oe.push(()=>{xo&&(xo(),xo=null)}),Oe.push(l);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let i=vr(Ks.type,Ks.plugins);i&&(Ya(i,e),Oe.push(()=>bu(e)))}let Br=Za(mt),Ac=Za(Kt),Sc=Za(pt),Dr=[Br,Ac,Sc];Oe.push(()=>{Dr.forEach(i=>i.destroy())});let Co=null,N,Ao=null,Tc=!1,Mc=0,Ec=null,kc=i=>i.reduce((f,m)=>m.role==="user"?f+1:f,0),Lc=i=>{for(let f=i.length-1;f>=0;f--)if(ss(i[f]))return i[f].id??null;return null},Pc=!1,Df=()=>{Pc||o.debug!==!0||(Pc=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but copy.showWelcomeCard is false, so no starters render. Use "auto" or "composer".'))},Ic=!1,Rc=!1,Wc=(i,f)=>{Ic||o.debug!==!0||!f.enabled||f.expose||Tc||Rc&&(N.isStreaming()||i.some(ss)||(Ic=!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.")))},Fr=i=>{if(!N)return;let f=i??N.getMessages(),m=ee=>{ee.render([],N,z,f)},b=ee=>{Dr.forEach(pe=>{pe!==ee&&m(pe)})};Ao&&(kc(f)>Mc||Lc(f)!==Ec)&&(Ao=null);let S=po(o);Wc(f,S);let E=S.enabled?ip(f):null,X=Ao??E,O=Ao?"host":"agent";if(X){let ee=o.suggestions?.followUps,pe=ee?.placement??(ee?"auto":"composer"),be=(pe==="auto"?D()?"composer":"after-message":pe)==="after-message"?Sc:Br;b(be),be.render(X,N,z,f,o.suggestionChipsConfig,{source:O,surface:"followUp",variant:ee?.variant??"chip",behavior:ee?.behavior??"send",overflow:ee?.overflow??"scroll",maxItems:ee?.maxItems??4,config:o,plugins:s});return}if(f.some(ee=>ee.role==="user")){Dr.forEach(m);return}let G=o.suggestions?.starters;if(G){let ee=o.copy?.showWelcomeCard!==!1,pe=G.placement??"auto",re=pe==="auto"?ee?"welcome":"composer":pe;if(re==="welcome"&&!ee){Df(),Dr.forEach(m);return}let be=re==="welcome"?Ac:Br;b(be),be.render(G.items??o.suggestionChips,N,z,f,o.suggestionChipsConfig,{surface:"starter",variant:G.variant??"card",behavior:G.behavior??"send",overflow:G.overflow??"wrap",maxItems:G.maxItems??4,config:o,plugins:s});return}b(Br),Br.render(o.suggestionChips,N,z,f,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},Hc=()=>{Ao&&(Ao=null,Fr())},Ff=i=>{let f=Array.isArray(i)?[...i]:[];if(!f.length){Hc();return}let m=N?N.getMessages():[];Ao=f,Tc=!0,Mc=kc(m),Ec=Lc(m),Fr(m)},vn=!1,So=lu(),Go=new Map,To=new Map,Jn=new Map,Ti=0,Nf=_n()!==null,nn=qa(),cn=0,Yn=null,dn=!1,Gs=!1,Zn=0,wn=null,Mo=null,Mi=!1,Qs=!1,Nr=null,Or=!0,Xs=!1,Js=null,Ys=!1,Eo=()=>{Ys=!0},Ei=null,Of=4,Zs=24,_f=80,ki=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Bc=o.voiceRecognition?.autoResume??!1,Hn=i=>{p.emit("voice:state",{active:Ve.active,source:i,timestamp:Date.now()})},xn=()=>{P(i=>({...i,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},$f=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Jl(u.voiceState),f=!!i.active,m=Number(i.timestamp??0);Ve.manuallyDeactivated=!!i.manuallyDeactivated,f&&Date.now()-m<Ib&&setTimeout(()=>{Ve.active||(Ve.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("restore"),N.isVoiceActive()&&Zo()}):ra("restore"))},1e3)},Uf=()=>N?uf(N.getMessages()).filter(i=>!i.__skipPersist):[],ea=null,Dc=(i,f)=>{typeof console<"u"&&console.error(i,f)},Li=(i,f)=>{let m=()=>{try{let X=i();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(O=>{Dc(f,O)})}catch(X){return Dc(f,X),null}},b=ea,S=b?b.then(()=>m()??void 0):m();if(!S)return;let E=S.finally(()=>{ea===E&&(ea=null)});ea=E};function Pi(i){if(!c?.save)return;let m={messages:i?uf(i):N?Uf():[],metadata:u,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};Li(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Qo=null,Fc=()=>Be.querySelector("#persona-scroll-container")||le,_r=()=>{Qo!==null&&(cancelAnimationFrame(Qo),Qo=null),dn=!1},Nc=()=>{Yn!==null&&(cancelAnimationFrame(Yn),Yn=null),Gs=!1,_r()},zf=()=>vn&&Ri()&&(ln()!=="anchor-top"||ac()),Ii=()=>{let i=Kn()||"Jump to latest",f=zf();Tt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Zn>0?(bo.textContent=String(Zn),bo.style.display="",Tt.setAttribute("aria-label",`${i} (${Zn} new)`)):(bo.textContent="",bo.style.display="none",Tt.setAttribute("aria-label",f?`${i} (response streaming below)`:i))},Oc=()=>{Zn!==0&&(Zn=0,Ii())},Ri=()=>Gn()?!nn.isFollowing():!ho(le,Zs),on=()=>{if(!kf()||ze){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==me&&me.appendChild(Tt),jo();let f=Pn(le)>0&&Ri();f?Ii():Oc(),Tt.style.display=f?"":"none"},$r=()=>{nn.pause()&&(Nc(),on())},eo=()=>{nn.resume(),Oc(),on()},to=(i=!1)=>{Gn()&&nn.isFollowing()&&(!i&&!vn||(Yn!==null&&(cancelAnimationFrame(Yn),Yn=null),Gs=!0,Yn=requestAnimationFrame(()=>{Yn=null,Gs=!1,nn.isFollowing()&&jf(Fc(),i?220:140)})))},_c=(i,f,m,b=()=>!0)=>{let S=i.scrollTop,E=f(),X=E-S;if(_r(),Math.abs(X)<1){dn=!0,i.scrollTop=E,cn=i.scrollTop,dn=!1;return}let O=performance.now();dn=!0;let G=pe=>1-Math.pow(1-pe,3),ee=pe=>{if(!b()){_r();return}let re=f();re!==E&&(E=re,X=E-S);let be=pe-O,Ue=Math.min(be/m,1),lt=G(Ue),Ze=S+X*lt;i.scrollTop=Ze,cn=i.scrollTop,Ue<1?Qo=requestAnimationFrame(ee):(i.scrollTop=E,cn=i.scrollTop,Qo=null,dn=!1)};Qo=requestAnimationFrame(ee)},jf=(i,f=500)=>{let m=Pn(i)-i.scrollTop;if(Math.abs(m)<1){cn=i.scrollTop;return}if(Math.abs(m)>=_f){_r(),dn=!0,i.scrollTop=Pn(i),cn=i.scrollTop,dn=!1;return}_c(i,()=>Pn(i),f,()=>nn.isFollowing())},$c=()=>{let i=Fc();dn=!0,i.scrollTop=Pn(i),cn=i.scrollTop,dn=!1,on()},Uc=i=>{let f=0,m=i;for(;m&&m!==le;)f+=m.offsetTop,m=m.offsetParent;return f},Vf=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},ta=()=>fu(Vf(),le),zc=()=>{if(Lf()!=="last-user-turn")return!1;let i=N?.getMessages()??[];if(i.length<2)return!1;let f=[...i].reverse().find(E=>E.role==="user");if(!f)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=le.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let S=Math.min(Math.max(0,Uc(b)-rc()),Pn(le));return dn=!0,le.scrollTop=S,cn=le.scrollTop,dn=!1,ln()==="follow"&&!ho(le,Zs)&&nn.pause(),on(),!0},jc=i=>{Qn.style.height=`${Math.max(0,Math.round(i))}px`,wn&&(wn.spacerHeight=Math.max(0,i))},Ur=()=>{Mo!==null&&(cancelAnimationFrame(Mo),Mo=null),_r(),wn=null,Qn.style.height="0px"},Vc=i=>{Mo!==null&&cancelAnimationFrame(Mo),Mo=requestAnimationFrame(()=>{Mo=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=le.querySelector(`[data-message-id="${f}"]`);if(!m)return;let b=Uc(m),S=wn?.spacerHeight??0,E=le.scrollHeight-S,{targetScrollTop:X,spacerHeight:O}=gu({anchorOffsetTop:b,topOffset:rc(),viewportHeight:le.clientHeight,contentHeight:E});wn={initialSpacerHeight:O,contentHeightAtAnchor:E,spacerHeight:O},jc(O),_c(le,()=>X,220)})},qf=()=>{if(Gn()){if(!nn.isFollowing()||ho(le,1))return;to(!vn);return}if(wn&&wn.initialSpacerHeight>0){let i=le.scrollHeight-wn.spacerHeight,f=mu({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});f!==wn.spacerHeight&&jc(f)}on()},Kf=i=>{let f=ln();f==="follow"?(eo(),to(!0)):f==="anchor-top"&&(Or=!1,Xs=!0,Ys=!1,Js=i,Vc(i))},Gf=()=>{if(ln()==="anchor-top"){if(Xs){Or=!1;return}Or=!0,Ur(),eo(),to(!0)}},Qf=i=>{if(ln()!=="anchor-top"||!Xs||Ys||ta())return;let f=Nr===null;for(let m of i){if(!f){m.id===Nr&&(f=!0);continue}if(uu(m)){if(m.id===Js)return;Js=m.id,Vc(m.id);return}}},Xf=i=>{let f=new Map;i.forEach(m=>{let b=ki.get(m.id);f.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(p.emit("assistant:message",m),!Qs&&(ln()!=="anchor-top"||ac())&&Ri()&&(Zn+=1,Ii(),on(),lc(Zn===1?"1 new message below.":`${Zn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),ki.clear(),f.forEach((m,b)=>{ki.set(b,m)})},na=(i,f)=>{let m=f==="user"?"user":"assistant",b=o.layout?.messages?.[m],S=b?.width??"content",E=b?.maxWidth??(S==="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-${f}`,`persona-message-width-${S}`),i.classList.toggle("persona-justify-end",f==="user"),i.setAttribute("data-message-role",f),i.setAttribute("data-message-width",S),i.style.setProperty("--persona-message-row-max-width",E)},ko=(i,f)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),na(m,f),m},Jf=(i,f,m)=>{let b=document.createElement("div"),E=(()=>{let W=s.find(ke=>ke.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(W,ke)=>ke==null?!1:typeof ke=="string"?(W.textContent=ke,!0):(W.appendChild(ke),!0),O=new Set,G=new Map,ee=new Set,pe=s.some(W=>W.renderAskUserQuestion),re=[],be=[],Ue=o.enableComponentStreaming!==!1,lt=o.approval!==!1,Ze=[];if(f.forEach(W=>{O.add(W.id),G.set(W.id,W.role);let ke=pe&&Wo(W),Fe=lt&&W.variant==="approval"&&!!W.approval,Se=!ke&&W.role==="assistant"&&!W.variant&&Ue&&Xl(W);!Fe&&Jn.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id)),!Se&&To.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(W.id));let wt=Wo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ct=iu(W,Ti)+wt,Bt=ke||Fe||Se?null:cu(So,W.id,ct);if(Bt){b.appendChild(Bt.cloneNode(!0)),Wo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}let dt=null,Zt=s.find(Ne=>!!(W.variant==="reasoning"&&Ne.renderReasoning||W.variant==="tool"&&Ne.renderToolCall||!W.variant&&Ne.renderMessage)),kt=o.layout?.messages;if(Wo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Go.delete(W.id),i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(ss(W)&&po(o).enabled)return;if(Wo(W)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=s.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Ne&&st.current){let _t=Go.get(W.id),$t=_t!==ct,bt=null;if($t){let{payload:Qe,complete:He}=ar(W),gt=W.id,Ut=()=>st.current?.getMessages().find(fn=>fn.id===gt);bt=Ne.renderAskUserQuestion({message:W,payload:Qe,complete:He,resolve:fn=>{let Yr=Ut();Yr&&st.current?.resolveAskUserQuestion(Yr,fn)},dismiss:()=>{let fn=Ut();fn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(fn),st.current?.resolveAskUserQuestion(fn,"(dismissed)"))},config:o})}let at=_t!=null;if($t&&bt===null&&!at){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}let ut=ko(W.id,W.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),b.appendChild(ut),re.push({messageId:W.id,fingerprint:ct,bubble:bt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}}else if(Fe){let Ne=s.find(at=>typeof at.renderApproval=="function")??a,$t=Jn.get(W.id)!==ct,bt=null;if($t&&Ne?.renderApproval){let at=W.id,ut=(Qe,He)=>{let gt=st.current?.getMessages().find(Ut=>Ut.id===at);gt?.approval&&(gt.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(gt.id,Qe):st.current?.resolveApproval(gt.approval,Qe,He))};bt=Ne.renderApproval({message:W,defaultRenderer:()=>ui(W,o),config:o,approve:Qe=>ut("approved",Qe),deny:Qe=>ut("denied",Qe)})}if($t&&bt===null)i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id),dt=ui(W,o);else{let at=ko(W.id,W.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),b.appendChild(at),Ze.push({messageId:W.id,fingerprint:ct,bubble:bt});return}}else if(Zt)if(W.variant==="reasoning"&&W.reasoning&&Zt.renderReasoning){if(!de)return;dt=Zt.renderReasoning({message:W,defaultRenderer:()=>Wl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Zt.renderToolCall){if(!te)return;dt=Zt.renderToolCall({message:W,defaultRenderer:()=>Bl(W,o),config:o})}else Zt.renderMessage&&(dt=Zt.renderMessage({message:W,defaultRenderer:()=>{let Ne=Rl(W,m,kt,o.messageActions,Ke,{loadingIndicatorRenderer:E,widgetConfig:o});return W.role!=="user"&&jl(Ne,W,o,N),Ne},config:o}));if(!dt&&Se){let Ne=cf(W);if(Ne){let _t=To.get(W.id),$t=_t!==ct,bt=o.wrapComponentDirectiveInBubble!==!1&&Vn.getOptions(Ne.component)?.bubbleChrome!==!1,at=null;if($t){let ut=af(Ne,{config:o,message:W,transform:m});if(ut&&Ne.component==="PersonaArtifactInline"){let Qe=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),He=Qe?.getAttribute("data-artifact-inline")??"",gt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,Ut=He?i.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${gt}"]`)??null:null;Qe&&Ut&&Ut!==Qe&&nu(Ut)&&(Qe===ut?ut=Ut:Qe.replaceWith(Ut))}if(ut)if(bt){let Qe=document.createElement("div");if(Qe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Qe.id=`bubble-${W.id}`,Qe.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Qe.appendChild(He)}Qe.appendChild(ut),at=Qe}else{let Qe=document.createElement("div");if(Qe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Qe.id=`bubble-${W.id}`,Qe.setAttribute("data-message-id",W.id),Qe.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Qe.appendChild(He)}Qe.appendChild(ut),at=Qe}}if(at||_t!=null){let ut=ko(W.id,W.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),b.appendChild(ut),be.push({messageId:W.id,fingerprint:ct,bubble:at});return}}}if(!dt)if(W.variant==="reasoning"&&W.reasoning){if(!de)return;dt=Wl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!te)return;dt=Bl(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;dt=ui(W,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&W.role==="user"?dt=Ne.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Ne?.renderAssistantMessage&&W.role==="assistant"?dt=Ne.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):dt=Rl(W,m,Ne,o.messageActions,Ke,{loadingIndicatorRenderer:E,widgetConfig:o}),W.role!=="user"&&dt&&jl(dt,W,o,N)}let Le=ko(W.id,W.role);Le.appendChild(dt),du(So,W.id,ct,Le),b.appendChild(Le)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Fe=ke.getAttribute("data-persona-ask-sheet-for");Fe&&!ee.has(Fe)&&lr(We.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let W=[],ke=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&te){ke.push(Se);return}Se.variant==="reasoning"&&!de||((ke.length>1||Fe&&ke.length>0)&&W.push(ke),ke=[])}),(ke.length>1||Fe&&ke.length>0)&&W.push(ke),W.forEach(Se=>{let wt=Se.map(Ne=>Array.from(b.children).find(_t=>_t instanceof HTMLElement&&_t.getAttribute("data-wrapper-id")===Ne.id)).filter(Ne=>!!Ne);if(wt.length<(Fe?1:2))return;let ct=ko(`tool-group-${Se[0].id}`,"assistant");ct.setAttribute("data-persona-tool-group-row","true");let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let dt=document.createElement("div");dt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",dt.id=`tool-group-summary-${Se[0].id}`;let Zt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,kt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:Zt,config:o});X(dt,kt)||(dt.textContent=Zt);let Le=document.createElement("div");Le.className="persona-tool-group-stack persona-flex persona-flex-col",Le.id=`tool-group-stack-${Se[0].id}`,Le.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(dt),Fe||Bt.appendChild(Le),ct.appendChild(Bt),wt[0].before(ct),wt.forEach((Ne,_t)=>{if(Fe){Ne.remove();return}Ne.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),_t<wt.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Ne),Le.appendChild($t)})})}pu(So,O);let rn=f.some(W=>W.role==="assistant"&&W.streaming),At=f[f.length-1],Et=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(vn&&f.some(W=>W.role==="user")&&!rn&&!Et){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Ls},ke=s.find(Se=>Se.renderLoadingIndicator),Fe=null;if(ke?.renderLoadingIndicator&&(Fe=ke.renderLoadingIndicator(W)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(W)),Fe===null&&(Fe=Ls()),Fe){let Se=document.createElement("div"),wt=o.loadingIndicator?.showBubble!==!1,ct=o.layout?.messages?.layout??"bubble";Se.className=wt?Il("assistant",ct).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),wt&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",ct!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(Fe);let Bt=ko("typing-indicator","assistant");Bt.appendChild(Se),b.appendChild(Bt)}}if(!vn&&f.length>0){let W=f[f.length-1],ke={config:o,lastMessage:W,messageCount:f.length},Fe=s.find(wt=>wt.renderIdleIndicator),Se=null;if(Fe?.renderIdleIndicator&&(Se=Fe.renderIdleIndicator(ke)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(ke)),Se){let wt=document.createElement("div"),ct=o.loadingIndicator?.showBubble!==!1;wt.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(" "),wt.setAttribute("data-idle-indicator","true"),wt.appendChild(Se);let Bt=ko("idle-indicator","assistant");Bt.appendChild(wt),b.appendChild(Bt)}}if(_d(b),Va(i,b),Gi(i),re.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of re){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),Go.set(W,ke)))}if(Go.size>0)for(let W of Go.keys())O.has(W)||Go.delete(W);if(be.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of be){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),To.set(W,ke)))}if(To.size>0)for(let W of To.keys())O.has(W)||To.delete(W);if(Ze.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of Ze){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),Jn.set(W,ke)))}if(Jn.size>0)for(let W of Jn.keys())O.has(W)||Jn.delete(W)},zr=(i,f,m)=>{Jf(i,f,m),hc()},jr=null,Yf=()=>{if(jr)return;let i=m=>{let b=m.composedPath();b.includes(Be)||Xe&&b.includes(Xe)||it(!1,"user")};jr=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},qc=()=>{if(!jr)return;(e.ownerDocument??document).removeEventListener("pointerdown",jr,!0),jr=null};Oe.push(()=>qc());let Vr=null,Zf=()=>{if(Vr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||it(!1,"user"))};Vr=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Kc=()=>{if(!Vr)return;(e.ownerDocument??document).removeEventListener("keydown",Vr,!0),Vr=null};Oe.push(()=>Kc());let qr=!1,Gc=new Set,eg=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Xo=()=>{if(!D())return;let i=We.peekBanner,f=We.peekTextNode;if(!i||!f)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let m=N?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Et=m[At];if(Et.role==="assistant"&&Et.content){b=Et;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let S=b.content,E=!!b.streaming,X=eg(),O=Qa(X),G=O.type!=="none"?vr(O.type,X?.plugins):null,ee=G?.isAnimating?.(b)===!0,pe=G!==null&&(E||ee);pe&&G&&!Gc.has(G.name)&&(Ya(G,e),Gc.add(G.name));let re=pe&&G?.containerClass?G.containerClass:null,be=f.dataset.personaPeekStreamClass??null;be&&be!==re&&(f.classList.remove(be),delete f.dataset.personaPeekStreamClass),re&&be!==re&&(f.classList.add(re),f.dataset.personaPeekStreamClass=re),pe?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ue=pe?Xa(S,O.buffer,G,b,E):S;if(pe&&O.placeholder==="skeleton"&&E&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Et=Ss();Et.classList.add("persona-pill-peek__skeleton"),At.appendChild(Et),Va(f,At)}else{let At=Math.max(0,Ue.length-100),Et=Ue.length>100?Ue.slice(-100):Ue,W=ao(Et);if(!pe||!G){let ke=Ue.length>100?`\u2026${Et}`:Et;f.textContent!==ke&&(f.textContent=ke)}else{let ke=W;(G.wrap==="char"||G.wrap==="word")&&(ke=As(W,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:At}));let Fe=document.createElement("div");if(Fe.innerHTML=ke,G.useCaret&&Et.length>0){let Se=Ja(),wt=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ct=wt[wt.length-1];ct?.parentNode?ct.parentNode.insertBefore(Se,ct.nextSibling):Fe.appendChild(Se)}Va(f,Fe),G.onAfterRender?.({container:f,bubble:i,messageId:b.id,message:b,speed:O.speed,duration:O.duration})}}let rn=vn||qr;i.classList.toggle("persona-pill-peek--visible",rn)};if(D()){let i=We.peekBanner;if(i){let b=S=>{S.preventDefault(),S.stopPropagation(),it(!0,"user")};i.addEventListener("pointerdown",b),Oe.push(()=>{i.removeEventListener("pointerdown",b)})}let f=()=>{qr||(qr=!0,Xo())},m=()=>{qr&&(qr=!1,Xo())};ue.addEventListener("pointerenter",f),ue.addEventListener("pointerleave",m),Oe.push(()=>{ue.removeEventListener("pointerenter",f),ue.removeEventListener("pointerleave",m)}),Xe&&(Xe.addEventListener("pointerenter",f),Xe.addEventListener("pointerleave",m),Oe.push(()=>{Xe.removeEventListener("pointerenter",f),Xe.removeEventListener("pointerleave",m)}))}let tg=i=>{let f=o.launcher?.composerBar??{},m=f.expandedSize??"anchored",b=f.bottomOffset??"16px",S=f.collapsedMaxWidth,E=f.expandedMaxWidth??"880px",X=f.expandedTopOffset??"5vh",O=f.modalMaxWidth??"880px",G=f.modalMaxHeight??"min(90vh, 800px)",ee="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",re=Be.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Xe){let be=Xe.style;be.bottom=b,be.width=S??""}if(i&&m!=="fullscreen"){if(m==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=O,re.maxWidth=ee,re.maxHeight=G,re.height=G;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${b} + ${pe})`,re.top=X,re.width=E,re.maxWidth=ee}},Kr=()=>{if(!_())return;if(D()){let ee=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Y?"expanded":"collapsed";Be.dataset.state=pe,Be.dataset.expandedSize=ee,Xe&&(Xe.dataset.state=pe,Xe.dataset.expandedSize=ee),Be.style.removeProperty("display"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tg(Y),me.style.display=Y?"flex":"none",qs(),Y?(Yf(),Zf()):(qc(),Kc()),Xo();return}let i=Dt(o),f=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,S=f.innerWidth<=m,E=b&&S&&M,X=hn(o).reveal;Y?(Be.style.removeProperty("display"),Be.style.display=i?"flex":"",Be.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"),Ft?Ft.element.style.display="none":Qt&&(Qt.style.display="none")):(i?i&&(X==="overlay"||X==="push")&&!E?(Be.style.removeProperty("display"),Be.style.display="flex",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.setProperty("display","none","important"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.display="",Be.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")),Ft?Ft.element.style.display=i?"none":"":Qt&&(Qt.style.display=i?"none":""))},it=(i,f="user")=>{if(!_()||Y===i)return;let m=Y;Y=i,Kr();let b=(()=>{let E=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,ee=X.innerWidth<=G,pe=Dt(o)&&O&&ee,re=D()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||O&&ee&&M||pe||re})();if(Y&&b){if(!Mn){let E=e.getRootNode(),X=E instanceof ShadowRoot?E.host:e.closest(".persona-host");X&&(Mn=Sl(X,o.launcher?.zIndex??Vt))}En||(En=Tl(e.ownerDocument))}else Y||(Mn?.(),Mn=null,En?.(),En=null);Y&&(Xr(),zc()||(ln()==="follow"?to(!0):$c()));let S={open:Y,source:f,timestamp:Date.now()};Y&&!m?p.emit("widget:opened",S):!Y&&m&&p.emit("widget:closed",S),p.emit("widget:state",{open:Y,launcherEnabled:M,voiceActive:Ve.active,streaming:N.isStreaming()})},Wi=i=>{Je(i?"stop":"send"),q&&(q.disabled=i),Dr.forEach(f=>{f.elements.forEach(m=>{m.toggleAttribute("data-disabled",i),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",i?"true":"false")}),f.buttons.forEach(m=>{m.disabled=i})}),we.dataset.personaComposerStreaming=i?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=i)})},Hi=()=>{Ve.active||z&&z.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hi(),200)});let Qc=()=>{I.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",H.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",z.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=le.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!N?.isStreaming()&&(C.textContent=o.copy?.sendButtonLabel??"Send"),z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',z.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=>{P(f=>({...f,sessionId:i}))}});let Lo=null,ng=()=>{Lo==null&&(Lo=setInterval(()=>{let i=Re.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Lo),Lo=null;return}let f=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=Aa(f-b))})},100))},Bi=(i,f)=>{if(Object.is(i,f))return!0;if(i===null||f===null||typeof i!="object"||typeof f!="object")return!1;if(Array.isArray(i)||Array.isArray(f))return!Array.isArray(i)||!Array.isArray(f)||i.length!==f.length?!1:i.every((X,O)=>Bi(X,f[O]));let m=i,b=f,S=Object.keys(m),E=Object.keys(b);return S.length===E.length&&S.every(X=>Object.prototype.hasOwnProperty.call(b,X)&&Bi(m[X],b[X]))},Xc=i=>{let{content:f,rawContent:m,llmContent:b,...S}=i;return S},Di=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Xl(i),og=(i,f,m)=>{if(i.length!==f.length)return!1;let b=i[m.index],S=f[m.index];return!b||!S||b.id!==m.id||S.id!==m.id?!1:(!Object.is(b.content,S.content)||!Object.is(b.rawContent,S.rawContent)||!Object.is(b.llmContent,S.llmContent))&&Di(b)&&Di(S)&&Bi(Xc(b),Xc(S))},Jc=null,Jo=null,Po=null,Bn=null,oa=i=>{Jc=i;let f,m;Jo=null;for(let S=i.length-1;S>=0;S-=1){let E=i[S];if(!f&&E.role==="user"&&(f=E),!m&&E.role==="assistant"&&(m=E),!Jo&&Di(E)&&(Jo={index:S,id:E.id}),f&&m&&Jo)break}zr(Re,i,Z),bl(Re,yn.artifacts,{suppressTransition:vn}),ng(),Fr(i),to(!vn),Xf(i),i.length===0&&(Ur(),Or=!0,Xs=!1,Js=null,Ys=!1),!Mi||Qs?(Mi=!0,Nr=f?.id??null,Ei=m?.id??null):f&&f.id!==Nr?(Nr=f.id,Kf(f.id)):m&&m.id!==Ei&&Gf(),m&&(Ei=m.id),Qf(i);let b=Ve.lastUserMessageId;f&&f.id!==b&&(Ve.lastUserMessageId=f.id,p.emit("user:message",f)),Ve.lastUserMessageWasVoice=!!f?.viaVoice,Pi(i),Xo()},Fi=()=>{Bn!==null&&(cancelAnimationFrame(Bn),Bn=null);let i=Po;Po=null,i&&oa(i)},Yc=()=>{Bn!==null&&cancelAnimationFrame(Bn),Bn=null,Po=null},rg=i=>{let f=Po??Jc;if(vn&&f&&Jo&&og(f,i,Jo)){Po=i,Bn===null&&(Bn=requestAnimationFrame(()=>{Bn=null;let m=Po;Po=null,m&&oa(m)}));return}if(i.length===0){Yc(),oa(i);return}Fi(),oa(i)};N=new Ia(o,{onMessagesChanged(i){rg(i)},onStatusChanged(i){let f=o.statusIndicator??{};qt(L,(b=>b==="idle"?f.idleText??Lt.idle:b==="connecting"?f.connectingText??Lt.connecting:b==="connected"?f.connectedText??Lt.connected:b==="error"?f.errorText??Lt.error:b==="paused"?f.pausedText??Lt.paused:b==="resuming"?f.resumingText??Lt.resuming:Lt[b])(i),f,i)},onStreamingChanged(i){i||(N?.getMessages().length===0?Yc():Fi()),vn=i,Wi(i),N&&zr(Re,N.getMessages(),Z),i||(to(!0),Rc=!0,N&&Wc(N.getMessages(),po(o))),on(),lc(i?"Responding\u2026":"Response complete."),Xo()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Dn(),Zo();break;case"processing":Dn(),mg();break;case"speaking":Dn(),hg();break;default:i==="idle"&&N.isBargeInActive()?(Dn(),Zo(),q?.setAttribute("aria-label","End voice session")):(Ve.active=!1,Dn(),Hn("system"),xn());break}},onArtifactsState(i){yn=i,i.artifacts.length===0&&(Vo=!1),bl(Re,i.artifacts,{suppressTransition:vn}),Wn(),Pi()},onReconnect(i){let{executionId:f,lastEventId:m}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:f,after:m}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:f,after:m,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:f,after:m})}}),st.current=N,Oe.push(()=>N.cancel());let Ni=null;if(N.onReadAloudChange((i,f)=>{gc=i,mc=f,hc();let m=i??Ni;i&&(Ni=i);let b=m?N.getMessages().find(S=>S.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:b,state:f,timestamp:Date.now()}),f==="idle"&&(Ni=null)}),Mi=!0,o.voiceRecognition?.provider?.type==="runtype")try{N.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&N.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ae||o.onSSEEvent)&&N.setSSEEventCallback((i,f)=>{o.onSSEEvent?.(i,f),Te?.processEvent(i,f),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(f)})});let Zc=()=>{o.resume&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(o.resume)};w?w.then(i=>{if(i){if(i.metadata&&(u=Jl(i.metadata),T.syncFromMetadata()),i.messages?.length){Qs=!0;try{N.hydrateMessages(i.messages)}finally{Qs=!1}}i.artifacts?.length&&N.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Zc()):Zc();let ed=()=>{!D()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||it(!0,"auto")},sg=(i,f)=>i?f?{refs:[...i.refs,...f.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([i.finalize(),f.finalize()]),S=[];return m.status==="fulfilled"?S.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),Nb(S)}}:i:f,ag=()=>{let f=z.getInlineMessageFields?.();return f&&f.contentSegments.some(b=>b.kind==="mention")?f.contentSegments:void 0},Gr=!1,ig=async i=>{let f=z.value.trim(),m=Ct?.hasAttachments()??!1,b=f?await(tn?.takeInlineCommand(f)??Promise.resolve(null)):null;if(b?.kind==="action"){z.value="",z.style.height="auto",Qr(),tn?.clear();return}let S=tn?.collectForSubmit()??null,E=b?.kind==="server"?b.mentions:null,X=sg(S,E),O=b?.kind==="prompt"?b.sendText:f,G=!!S&&S.refs.length>0;if(!O&&!m&&!G&&!E)return;ed();let ee;m&&(ee=[],ee.push(...Ct.getContentParts()),O&&ee.push(dr(O)));let pe=b?.kind==="prompt"?void 0:ag();z.value="",z.style.height="auto",Qr(),N.sendMessage(O,{contentParts:ee,mentions:X??void 0,contentSegments:pe,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),S&&tn?.clear()},Oi=async i=>{if(!Gr){Gr=!0;try{await ig(i)}finally{Gr=!1}}},td=i=>{if(i.preventDefault(),N.isStreaming()){N.cancel(),Te?.reset(),qe?.update();return}Gr||Oi()},lg=()=>o.features?.composerHistory!==!1,_i={...xl},$i=!1,Qr=()=>{_i={...xl}},cg=()=>N.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),dg=i=>{if(!z)return;$i=!0,z.value=i,z.dispatchEvent(new Event("input",{bubbles:!0})),$i=!1;let f=z.value.length;z.setSelectionRange(f,f)},pg=i=>{$i||(i.isComposing||tn?.handleInput(i.inputType??void 0),Qr())},ug=i=>{if(z&&!(!i.isComposing&&tn?.handleKeydown(i))){if(lg()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let f=z.selectionStart===0&&z.selectionEnd===0,m=au({direction:i.key==="ArrowUp"?"up":"down",history:cg(),currentValue:z.value,atStart:f,state:_i});if(_i=m.state,m.handled){i.preventDefault(),m.value!==void 0&&dg(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(N.isStreaming()){i.preventDefault();return}if(Gr){i.preventDefault();return}Qr(),i.preventDefault(),C.click()}}},nd=i=>{i.key!=="Escape"||i.isComposing||N.isStreaming()&&i.composedPath().includes(me)&&(N.cancel(),Te?.reset(),qe?.update(),Qr(),i.preventDefault(),i.stopImmediatePropagation())},fg=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let f=Hb(i.clipboardData);f.length!==0&&(i.preventDefault(),await Ct.handleFiles(f))},pn=null,kn=!1,Yo=null,yt=null,od=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ra=(i="user")=>{if(kn||N.isStreaming())return;let f=od();if(!f)return;pn=new f;let b=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let S=z.value;pn.onresult=E=>{let X="",O="";for(let ee=0;ee<E.results.length;ee++){let pe=E.results[ee],re=pe[0].transcript;pe.isFinal?X+=re+" ":O=re}let G=S+X+O;z.value=G,Yo&&clearTimeout(Yo),(X||O)&&(Yo=window.setTimeout(()=>{z.value.trim()&&pn&&kn&&(no(),Oi({viaVoice:!0}))},b))},pn.onerror=E=>{E.error!=="no-speech"&&no()},pn.onend=()=>{if(kn){let E=z.value.trim();E&&E!==S.trim()&&Oi({viaVoice:!0}),no()}};try{if(pn.start(),kn=!0,Ve.active=!0,i!=="system"&&(Ve.manuallyDeactivated=!1),Hn(i),xn(),q){let E=o.voiceRecognition??{};yt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let X=E.recordingBackgroundColor,O=E.recordingIconColor,G=E.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let ee=q.querySelector("svg");ee&&ee.setAttribute("stroke",O)}G&&(q.style.borderColor=G),q.setAttribute("aria-label","Stop voice recognition")}}catch{no("system")}},no=(i="user")=>{if(kn){if(kn=!1,Yo&&(clearTimeout(Yo),Yo=null),pn){try{pn.stop()}catch{}pn=null}if(Ve.active=!1,Hn(i),xn(),q){if(q.classList.remove("persona-voice-recording"),yt){q.style.backgroundColor=yt.backgroundColor,q.style.color=yt.color,q.style.borderColor=yt.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",yt.color||"currentColor"),yt=null}q.setAttribute("aria-label","Start voice recognition")}}},gg=(i,f)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",S=i?.provider?.type==="custom";if(!(m||b||S))return null;let X=y("div","persona-send-button-wrapper"),O=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button";let G=i?.tooltipText??"Start voice recognition";O.setAttribute("aria-label",G);let ee=i?.iconName??"mic",pe=f?.size??"40px",re=i?.iconSize??pe,be=parseFloat(re)||24,Ue=i?.backgroundColor??f?.backgroundColor,lt=i?.iconColor??f?.textColor;O.style.width=re,O.style.height=re,O.style.minWidth=re,O.style.minHeight=re,O.style.fontSize="18px",O.style.lineHeight="1",lt?O.style.color=lt:O.style.color="var(--persona-text, #111827)";let rn=ae(ee,be,lt||"currentColor",1.5);rn?O.appendChild(rn):O.textContent="\u{1F3A4}",Ue?O.style.backgroundColor=Ue:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),X.appendChild(O);let At=i?.showTooltip??!1;return Ot({anchor:O,trigger:X,text:()=>O.getAttribute("aria-label")??G,enabled:At}),{micButton:O,micButtonWrapper:X}},Ui=()=>{if(!q||yt)return;let i=o.voiceRecognition??{};yt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},zi=(i,f)=>{if(!q)return;let m=q.querySelector("svg");m&&m.remove();let b=yt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=ae(i,b,f,1.5);S&&q.appendChild(S)},sa=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Zo=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(sa(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let S=q.querySelector("svg");S&&S.setAttribute("stroke",m)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},mg=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=N.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??yt?.color??"",S=i.processingBackgroundColor??yt?.backgroundColor??"",E=i.processingBorderColor??yt?.borderColor??"";sa(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=S,q.style.borderColor=E;let X=b||"currentColor";q.style.color=X,zi(m,X),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},hg=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=N.getVoiceInterruptionMode(),m=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,S=i.speakingIconColor??(f==="barge-in"?i.recordingIconColor??yt?.color??"":yt?.color??""),E=i.speakingBackgroundColor??(f==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":yt?.backgroundColor??""),X=i.speakingBorderColor??(f==="barge-in"?i.recordingBorderColor??"":yt?.borderColor??"");sa(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=E,q.style.borderColor=X;let O=S||"currentColor";q.style.color=O,zi(b,O);let G=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",G),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},Dn=()=>{q&&(sa(),yt&&(q.style.backgroundColor=yt.backgroundColor??"",q.style.color=yt.color??"",q.style.borderColor=yt.borderColor??"",zi(yt.iconName,yt.color||"currentColor"),yt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},aa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=N.getVoiceStatus(),f=N.getVoiceInterruptionMode();if(f==="none"&&(i==="processing"||i==="speaking"))return;if(f==="cancel"&&(i==="processing"||i==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,xn(),Hn("user"),Dn()});return}N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Ve.manuallyDeactivated=!N.isVoiceActive(),xn(),Hn("user"),N.isVoiceActive()?Zo():Dn()});return}if(kn){let i=z.value.trim();Ve.manuallyDeactivated=!0,xn(),no("user"),i&&(z.value="",z.style.height="auto",N.sendMessage(i))}else Ve.manuallyDeactivated=!1,xn(),ra("user")};dc=aa,q&&(q.addEventListener("click",aa),Oe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()&&N.toggleVoice(),Dn()):no("system"),q&&q.removeEventListener("click",aa)}));let yg=p.on("assistant:complete",()=>{Bc&&(Ve.active||Ve.manuallyDeactivated||Bc==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{!Ve.active&&!Ve.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("auto"),N.isVoiceActive()&&Zo()}):ra("auto"))},600))});Oe.push(yg);let bg=p.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});Oe.push(bg);let rd=()=>{it(!Y,"user")},Ft=null,Qt=null;if(M&&!D()){let{instance:i,element:f}=kl({config:o,plugins:s,onToggle:rd});Ft=i,i||(Qt=f)}Ft?e.appendChild(Ft.element):Qt&&e.appendChild(Qt),Kr(),Fr(),Qc(),Wi(N.isStreaming()),zc()||(ln()==="follow"?to(!0):$c()),$f(),j&&(!M||D()?setTimeout(()=>Hi(),0):Y&&setTimeout(()=>Hi(),200));let Xr=()=>{if(D()){jo(),Kr();return}let i=Dt(o),f=o.launcher?.sidebarMode??!1,m=i||f||(o.launcher?.fullHeight??!1),b=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640,X=b.innerWidth<=E,O=S&&X&&M;try{if(O){Ir(),Rr=Vs();return}let G=!1;ne&&(ne=!1,Ir(),G=!0);let ee=Vs();if(!G&&ee!==Rr&&(Ir(),G=!0),Rr=ee,G&&Ai(),!M&&!i){ue.style.height="",ue.style.width="";return}if(!f&&!i){let re=o?.launcher?.width??o?.launcherWidth??jn;ue.style.width=re,ue.style.maxWidth=re}if(js(),!m){let pe=b.innerHeight,re=64,be=o.launcher?.heightOffset??0,Ue=Math.max(200,pe-re),lt=Math.min(640,Ue),Ze=Math.max(200,lt-be);ue.style.height=`${Ze}px`}}finally{if(jo(),Kr(),Y&&M){let ee=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),pe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,be=Dt(o)&&re&&ee,Ue=pe||re&&ee&&M||be;if(Ue&&!En){let lt=e.getRootNode(),Ze=lt instanceof ShadowRoot?lt.host:e.closest(".persona-host");Ze&&!Mn&&(Mn=Sl(Ze,o.launcher?.zIndex??Vt)),En=Tl(e.ownerDocument)}else Ue||(Mn?.(),Mn=null,En?.(),En=null)}}};Xr();let sd=e.ownerDocument.defaultView??window;if(sd.addEventListener("resize",Xr),Oe.push(()=>sd.removeEventListener("resize",Xr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{jo()});i.observe(we),Oe.push(()=>i.disconnect())}cn=le.scrollTop;let ad=Pn(le),id=()=>{let i=le.scrollTop,f=Pn(le),m=f<ad;if(ad=f,!Gn()){cn=i,on();return}let{action:b,nextLastScrollTop:S}=Ka({following:nn.isFollowing(),currentScrollTop:i,lastScrollTop:cn,nearBottom:ho(le,Zs),userScrollThreshold:Of,isAutoScrolling:dn||Gs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=S,b==="resume"){ta()||eo();return}b==="pause"&&$r()};if(le.addEventListener("scroll",id,{passive:!0}),Oe.push(()=>le.removeEventListener("scroll",id)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{qf(),Gi(Re)});i.observe(Re),i.observe(le),Oe.push(()=>i.disconnect())}let ld=()=>{Gn()&&nn.isFollowing()&&ta()&&$r()},cd=le.ownerDocument;cd.addEventListener("selectionchange",ld),Oe.push(()=>{cd.removeEventListener("selectionchange",ld)});let vg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dd=i=>{vg.has(i.key)&&(Eo(),sc()&&Gn()&&nn.isFollowing()&&$r())},pd=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Eo(),sc()&&Gn()&&nn.isFollowing()&&$r())};le.addEventListener("keydown",dd),le.addEventListener("focusin",pd),Oe.push(()=>{le.removeEventListener("keydown",dd),le.removeEventListener("focusin",pd)});let ud=i=>{if(i.deltaY!==0&&Eo(),!Gn())return;let f=Ga({following:nn.isFollowing(),deltaY:i.deltaY,nearBottom:ho(le,Zs),resumeWhenNearBottom:!0});f==="pause"?$r():f==="resume"&&!ta()&&eo()};le.addEventListener("wheel",ud,{passive:!0}),le.addEventListener("touchmove",Eo,{passive:!0}),le.addEventListener("pointerdown",Eo,{passive:!0}),Oe.push(()=>{le.removeEventListener("touchmove",Eo),le.removeEventListener("pointerdown",Eo)}),Oe.push(()=>le.removeEventListener("wheel",ud)),Tt.addEventListener("click",()=>{Ur(),le.scrollTop=le.scrollHeight,cn=le.scrollTop,eo(),to(!0),on()}),Oe.push(()=>Tt.remove()),Oe.push(()=>{Nc(),Ur()});let fd=()=>{B&&(Co&&(B.removeEventListener("click",Co),Co=null),_()?(B.style.display="",Co=()=>{it(!1,"user")},B.addEventListener("click",Co)):B.style.display="none")};fd(),(()=>{let{clearChatButton:i}=We;i&&i.addEventListener("click",()=>{N.clearMessages(),So.clear(),eo(),lr(We.composerOverlay);try{localStorage.removeItem(Tr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Tr)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 f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),c?.clear&&Li(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ae?.clear(),Te?.reset(),qe?.update()})})(),h&&h.addEventListener("submit",td);let gd=[["keydown",ug],["input",pg],["paste",fg],["focus",Rf]],md=i=>{if(i)for(let[f,m]of gd)i.addEventListener(f,m)},hd=i=>{if(i)for(let[f,m]of gd)i.removeEventListener(f,m)};md(z),tn?.onComposerSwap((i,f)=>{hd(f),z=i,md(i)});let yd=e.ownerDocument??document;yd.addEventListener("keydown",nd,!0);let bd="persona-attachment-drop-active",Jr=0,ji=()=>{Jr=0,me.classList.remove(bd)},er=()=>o.attachments?.enabled===!0&&Ct!==null,vd=i=>{!hi(i.dataTransfer)||!er()||(Jr++,Jr===1&&me.classList.add(bd))},wd=i=>{!hi(i.dataTransfer)||!er()||(Jr--,Jr<=0&&ji())},xd=i=>{!hi(i.dataTransfer)||!er()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Cd=i=>{if(!hi(i.dataTransfer)||!er())return;i.preventDefault(),i.stopPropagation(),ji();let f=Array.from(i.dataTransfer.files??[]);f.length!==0&&Ct.handleFiles(f)},oo=!0;me.addEventListener("dragenter",vd,oo),me.addEventListener("dragleave",wd,oo),e.addEventListener("dragover",xd,oo),e.addEventListener("drop",Cd,oo);let ia=e.ownerDocument,Ad=i=>{er()&&i.preventDefault()},Sd=i=>{er()&&i.preventDefault()};ia.addEventListener("dragover",Ad),ia.addEventListener("drop",Sd),Oe.push(()=>{h&&h.removeEventListener("submit",td),hd(z),yd.removeEventListener("keydown",nd,!0),tn?.destroy()}),Oe.push(()=>{me.removeEventListener("dragenter",vd,oo),me.removeEventListener("dragleave",wd,oo),e.removeEventListener("dragover",xd,oo),e.removeEventListener("drop",Cd,oo),ia.removeEventListener("dragover",Ad),ia.removeEventListener("drop",Sd),ji()}),Oe.push(()=>{N.cancel()}),Ft?Oe.push(()=>{Ft?.destroy()}):Qt&&Oe.push(()=>{Qt?.remove()});let Mt={update(i){let f=o.toolCall,m=o.messageActions,b=o.layout?.messages,S=o.colorScheme,E=o.loadingIndicator,X=o.iterationDisplay,O=o.features?.showReasoning,G=o.features?.showToolCalls,ee=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=nf({...o,features:r},i),r=o.features,o=Ul(o),qs(),ys(e,o),Ws(e,o),Hs(e,o),Wn(),o.colorScheme!==S&&Cc();let be=ql.getForInstance(o.plugins);s.length=0,s.push(...be),M=o.launcher?.enabled??!0,U=o.launcher?.autoExpand??!1,de=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,J=o.features?.scrollToBottom??{};let Ue=ln();fe=o.features?.scrollBehavior??{},Ue!==ln()&&(Ur(),eo()),cc(),on();let lt=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!lt){if(Ae||(xe=new Is(ye),Ae=new Ps(ve,xe),Te=Te??new Rs,xe.open().then(()=>Ae?.restore()).catch(()=>{}),N.setSSEEventCallback((oe,je)=>{o.onSSEEvent?.(oe,je),Te?.processEvent(oe,je),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(je)})})),!Ye&&Ee){let oe=o.features?.eventStream?.classNames,je="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(oe?.toggleButton?" "+oe.toggleButton:"");Ye=y("button",je),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Jt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let ft=ae("activity","18px","currentColor",1.5);ft&&Ye.appendChild(ft);let et=We.clearChatButtonWrapper,ot=We.closeButtonWrapper,zt=et||ot;zt&&zt.parentNode===Ee?Ee.insertBefore(Ye,zt):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{ze?Lr():vi()})}}else!ie&<&&(Lr(),Ye&&(Ye.remove(),Ye=null),Ae?.clear(),xe?.destroy(),Ae=null,xe=null,Te?.reset(),Te=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Qt&&(Qt.remove(),Qt=null),o.launcher?.enabled!==!1&&!Ft&&!Qt){let{instance:oe,element:je}=kl({config:o,plugins:s,onToggle:rd});Ft=oe,oe||(Qt=je),e.appendChild(je)}Ft&&Ft.update(o),Q&&o.launcher?.title!==void 0&&(Q.textContent=o.launcher.title),se&&o.launcher?.subtitle!==void 0&&(se.textContent=o.launcher.subtitle);let Ze=o.layout?.header;if(Ze?.layout!==K&&Ee){let oe=Ze?ni(o,Ze,{showClose:_(),onClose:()=>it(!1,"user")}):No({config:o,showClose:_(),onClose:()=>it(!1,"user")});xt.replaceHeader(oe),Ee=xt.header.element,R=xt.header.iconHolder,Q=xt.header.headerTitle,se=xt.header.headerSubtitle,B=xt.header.closeButton,K=Ze?.layout}else if(Ze){if(R&&(R.style.display=Ze.showIcon===!1?"none":""),Q&&(Q.style.display=Ze.showTitle===!1?"none":""),se&&(se.style.display=Ze.showSubtitle===!1?"none":""),B){let oe=_()&&Ze.showCloseButton!==!1;B.style.display=oe?"":"none"}if(We.clearChatButtonWrapper){let oe=Ze.showClearChat;if(oe!==void 0){We.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:je}=We;je&&!je.classList.contains("persona-absolute")&&(oe?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=At?"":"none");let Et=o.layout?.showFooter!==!1;we&&(we.style.display=Et?"":"none"),jo(),on(),M!==V?M?it(U,"auto"):(Y=!0,Kr()):U!==A&&it(U,"auto"),A=U,V=M,Xr(),fd();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(f),Se=JSON.stringify(o.messageActions)!==JSON.stringify(m),wt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ct=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,Bt=o.iterationDisplay!==X,dt=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ee)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Fe||Se||wt||ct||Bt||dt)&&N&&(Ti++,zr(Re,N.getMessages(),Z));let kt=o.features?.streamAnimation?.type;if(kt!==re&&kt&&kt!=="none"){let oe=vr(kt,o.features?.streamAnimation?.plugins);oe&&Ya(oe,e)}let Le=o.launcher??{},Ne=Le.headerIconHidden??!1,_t=o.layout?.header?.showIcon,$t=Ne||_t===!1,bt=Le.headerIconName,at=Le.headerIconSize??"48px";if(R){let oe=me.querySelector(".persona-border-b-persona-divider"),je=oe?.querySelector(".persona-flex-col");if($t)R.style.display="none",oe&&je&&!oe.contains(je)&&oe.insertBefore(je,oe.firstChild);else{if(R.style.display="",R.style.height=at,R.style.width=at,oe&&je&&(oe.contains(R)?R.nextSibling!==je&&(R.remove(),oe.insertBefore(R,je)):oe.insertBefore(R,je)),bt){let et=parseFloat(at)||24,ot=ae(bt,et*.6,"currentColor",1);ot?R.replaceChildren(ot):R.textContent=Le.agentIconText??"\u{1F4AC}"}else if(Le.iconUrl){let et=R.querySelector("img");if(et)et.src=Le.iconUrl,et.style.height=at,et.style.width=at;else{let ot=document.createElement("img");ot.src=Le.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=at,ot.style.width=at,R.replaceChildren(ot)}}else{let et=R.querySelector("svg"),ot=R.querySelector("img");(et||ot)&&R.replaceChildren(),R.textContent=Le.agentIconText??"\u{1F4AC}"}let ft=R.querySelector("img");ft&&(ft.style.height=at,ft.style.width=at)}}let ut=o.layout?.header?.showTitle,Qe=o.layout?.header?.showSubtitle;if(Q&&(Q.style.display=ut===!1?"none":""),se&&(se.style.display=Qe===!1?"none":""),B){let oe=_()&&o.layout?.header?.showCloseButton!==!1;B.style.display=oe?"":"none";let je=Le.closeButtonSize??"32px",ft=Le.closeButtonPlacement??"inline";B.style.height=je,B.style.width=je;let{closeButtonWrapper:et}=We,ot=ft==="top-right",zt=et?.classList.contains("persona-absolute");if(et&&ot!==zt)if(et.remove(),ot)et.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(et);else{let so=Le.clearChat?.placement??"inline",es=Le.clearChat?.enabled??!0;et.className=es&&so==="inline"?"":"persona-ml-auto";let Td=me.querySelector(".persona-border-b-persona-divider");Td&&Td.appendChild(et)}if(B.style.color=Le.closeButtonColor||Jt.actionIconColor,Le.closeButtonBackgroundColor?(B.style.backgroundColor=Le.closeButtonBackgroundColor,B.classList.remove("hover:persona-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:persona-bg-gray-100")),Le.closeButtonBorderWidth||Le.closeButtonBorderColor){let so=Le.closeButtonBorderWidth||"0px",es=Le.closeButtonBorderColor||"transparent";B.style.border=`${so} solid ${es}`,B.classList.remove("persona-border-none")}else B.style.border="",B.classList.add("persona-border-none");Le.closeButtonBorderRadius?(B.style.borderRadius=Le.closeButtonBorderRadius,B.classList.remove("persona-rounded-full")):(B.style.borderRadius="",B.classList.add("persona-rounded-full")),Le.closeButtonPaddingX?(B.style.paddingLeft=Le.closeButtonPaddingX,B.style.paddingRight=Le.closeButtonPaddingX):(B.style.paddingLeft="",B.style.paddingRight=""),Le.closeButtonPaddingY?(B.style.paddingTop=Le.closeButtonPaddingY,B.style.paddingBottom=Le.closeButtonPaddingY):(B.style.paddingTop="",B.style.paddingBottom="");let sn=Le.closeButtonIconName??"x",Cn=Le.closeButtonIconText??"\xD7";B.innerHTML="";let Nt=ae(sn,"28px","currentColor",1);Nt?(Nt.style.display="block",B.appendChild(Nt)):B.textContent=Cn;let jt=Le.closeButtonTooltipText??"Close chat",Nn=Le.closeButtonShowTooltip??!0;B.setAttribute("aria-label",jt),et&&Ot({anchor:B,trigger:et,text:()=>B?.getAttribute("aria-label")??jt,enabled:Nn})}let{clearChatButton:He,clearChatButtonWrapper:gt}=We;if(He){let oe=Le.clearChat??{},je=oe.enabled??!0,ft=o.layout?.header?.showClearChat,et=ft!==void 0?ft:je,ot=oe.placement??"inline";if(gt){gt.style.display=et?"":"none";let{closeButtonWrapper:zt}=We;!D()&&zt&&!zt.classList.contains("persona-absolute")&&(et?zt.classList.remove("persona-ml-auto"):zt.classList.add("persona-ml-auto"));let sn=ot==="top-right",Cn=gt.classList.contains("persona-absolute");if(!D()&&sn!==Cn&&et){if(gt.remove(),sn)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",me.style.position="relative",me.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let jt=me.querySelector(".persona-border-b-persona-divider"),Nn=We.closeButtonWrapper;jt&&Nn&&Nn.parentElement===jt?jt.insertBefore(gt,Nn):jt&&jt.appendChild(gt)}let Nt=We.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(sn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(et){if(!D()){let so=oe.size??"32px";He.style.height=so,He.style.width=so}let zt=oe.iconName??"refresh-cw",sn=oe.iconColor??"";He.style.color=sn||Jt.actionIconColor,He.innerHTML="";let Cn=D()?"14px":"20px",Nt=ae(zt,Cn,"currentColor",1);if(Nt&&(Nt.style.display="block",He.appendChild(Nt)),oe.backgroundColor?(He.style.backgroundColor=oe.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let so=oe.borderWidth||"0px",es=oe.borderColor||"transparent";He.style.border=`${so} solid ${es}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");oe.borderRadius?(He.style.borderRadius=oe.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),oe.paddingX?(He.style.paddingLeft=oe.paddingX,He.style.paddingRight=oe.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),oe.paddingY?(He.style.paddingTop=oe.paddingY,He.style.paddingBottom=oe.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let jt=oe.tooltipText??"Clear chat",Nn=oe.showTooltip??!0;He.setAttribute("aria-label",jt),gt&&Ot({anchor:He,trigger:gt,text:()=>He?.getAttribute("aria-label")??jt,enabled:Nn})}}let Ut=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gl],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick];T=Ql({parsers:Ut,handlers:fn,getSessionMetadata:x,updateSessionMetadata:P,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=ff(o,T,ce),N.updateConfig(o),zr(Re,N.getMessages(),Z),Fr(),Qc(),Wi(N.isStreaming());let Yr=o.voiceRecognition?.enabled===!0,la=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),St=o.voiceRecognition?.provider?.type==="runtype";if(Yr&&(la||St))if(!q||!$e){let oe=gg(o.voiceRecognition,o.sendButton);oe&&(q=oe.micButton,$e=oe.micButtonWrapper,tt.insertBefore($e,$),q.addEventListener("click",aa),q.disabled=N.isStreaming())}else{let oe=o.voiceRecognition??{},je=o.sendButton??{},ft=oe.iconName??"mic",et=je.size??"40px",ot=oe.iconSize??et,zt=parseFloat(ot)||24;q.style.width=ot,q.style.height=ot,q.style.minWidth=ot,q.style.minHeight=ot;let sn=oe.iconColor??je.textColor;q.innerHTML="";let Cn=ae(ft,zt,sn||"currentColor",1.5);Cn?q.appendChild(Cn):q.textContent="\u{1F3A4}";let Nt=oe.backgroundColor??je.backgroundColor;Nt?q.style.backgroundColor=Nt:q.style.backgroundColor="",sn?q.style.color=sn:q.style.color="var(--persona-text, #111827)",oe.borderWidth?(q.style.borderWidth=oe.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),oe.borderColor?q.style.borderColor=oe.borderColor:q.style.borderColor="",oe.paddingX?(q.style.paddingLeft=oe.paddingX,q.style.paddingRight=oe.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),oe.paddingY?(q.style.paddingTop=oe.paddingY,q.style.paddingBottom=oe.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let jt=oe.tooltipText??"Start voice recognition",Nn=oe.showTooltip??!1;q.setAttribute("aria-label",jt),$e&&Ot({anchor:q,trigger:$e,text:()=>q?.getAttribute("aria-label")??jt,enabled:Nn}),$e.style.display="",q.disabled=N.isStreaming()}else q&&$e&&($e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()&&N.toggleVoice():kn&&no());if(o.attachments?.enabled===!0){if(!Ht||!De){let oe=o.attachments??{},ft=(o.sendButton??{}).size??"40px";Gt||(Gt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Gt.style.display="none",h.insertBefore(Gt,z)),vt||(vt=document.createElement("input"),vt.type="file",vt.accept=(oe.allowedTypes??zn).join(","),vt.multiple=(oe.maxFiles??4)>1,vt.style.display="none",vt.setAttribute("aria-label","Attach files"),h.insertBefore(vt,z)),Ht=y("div","persona-send-button-wrapper"),De=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),De.type="button",De.setAttribute("aria-label",oe.buttonTooltipText??"Attach file");let et=oe.buttonIconName??"paperclip",ot=ft,zt=parseFloat(ot)||40,sn=Math.round(zt*.6);De.style.width=ot,De.style.height=ot,De.style.minWidth=ot,De.style.minHeight=ot,De.style.fontSize="18px",De.style.lineHeight="1";let Cn=ae(et,sn,"currentColor",1.5);Cn?De.appendChild(Cn):De.textContent="\u{1F4CE}",De.addEventListener("click",jt=>{jt.preventDefault(),vt?.click()}),Ht.appendChild(De);let Nt=oe.buttonTooltipText??"Attach file";Ot({anchor:De,trigger:Ht,text:()=>De?.getAttribute("aria-label")??Nt}),_e?_e.append(Ht):h.appendChild(Ht),!Ct&&vt&&Gt&&(Ct=gs.fromConfig(oe),Ct.setPreviewsContainer(Gt),vt.addEventListener("change",async()=>{Ct&&vt?.files&&(await Ct.handleFileSelect(vt.files),vt.value="")}))}else{Ht.style.display="";let oe=o.attachments??{};vt&&(vt.accept=(oe.allowedTypes??zn).join(","),vt.multiple=(oe.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}if(me.querySelector(".persona-attachment-drop-overlay")?.remove(),me.appendChild(gf(o.attachments?.dropOverlay)),De){let oe=o.attachments??{},je=oe.buttonTooltipText??"Attach file";De.setAttribute("aria-label",je),De.textContent="";let ft=parseFloat(o.sendButton?.size??"40px")||40,et=ae(oe.buttonIconName??"paperclip",Math.round(ft*.6),"currentColor",1.5);et?De.appendChild(et):De.textContent="\u{1F4CE}",Ht&&Ot({anchor:De,trigger:Ht,text:()=>De?.getAttribute("aria-label")??je})}}else Ht&&(Ht.style.display="none"),Ct&&Ct.clearAttachments(),me.querySelector(".persona-attachment-drop-overlay")?.remove();let Rt=o.sendButton??{},Zr=Rt.useIcon??!1,da=Rt.iconText??"\u2191",tr=Rt.iconName,pa=Rt.tooltipText??"Send message",Vi=Rt.showTooltip??!1,Io=Rt.size??"40px",Fn=Rt.backgroundColor,Ro=Rt.textColor;if(Zr){if(C.style.width=Io,C.style.height=Io,C.style.minWidth=Io,C.style.minHeight=Io,C.style.fontSize="18px",C.style.lineHeight="1",Ro?C.style.color=Ro:C.style.color="var(--persona-button-primary-fg, #ffffff)",!N.isStreaming())if(C.innerHTML="",tr){let oe=parseFloat(Io)||24,je=Ro?.trim()||"currentColor",ft=ae(tr,oe,je,2);ft?C.appendChild(ft):C.textContent=da}else C.textContent=da;C.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(C.style.backgroundColor=Fn,C.classList.remove("persona-bg-persona-primary")):(C.style.backgroundColor="",C.classList.add("persona-bg-persona-primary"))}else C.textContent=o.copy?.sendButtonLabel??"Send",C.style.width="",C.style.height="",C.style.minWidth="",C.style.minHeight="",C.style.fontSize="",C.style.lineHeight="",C.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",Fn?(C.style.backgroundColor=Fn,C.classList.remove("persona-bg-persona-accent")):C.classList.add("persona-bg-persona-accent"),Ro?C.style.color=Ro:C.classList.add("persona-text-white");Rt.borderWidth?(C.style.borderWidth=Rt.borderWidth,C.style.borderStyle="solid"):(C.style.borderWidth="",C.style.borderStyle=""),Rt.borderColor?C.style.borderColor=Rt.borderColor:C.style.borderColor="",Rt.paddingX?(C.style.paddingLeft=Rt.paddingX,C.style.paddingRight=Rt.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),Rt.paddingY?(C.style.paddingTop=Rt.paddingY,C.style.paddingBottom=Rt.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),N.isStreaming()||C.setAttribute("aria-label",pa),$&&Ot({anchor:C,trigger:$,text:()=>C.getAttribute("aria-label")??pa,enabled:Vi});let ua=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ua?(Re.style.maxWidth=ua,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",h&&(h.style.maxWidth=ua,h.style.marginLeft="auto",h.style.marginRight="auto"),mt&&(mt.style.maxWidth=ua,mt.style.marginLeft="auto",mt.style.marginRight="auto")):(Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",h&&(h.style.maxWidth="",h.style.marginLeft="",h.style.marginRight=""),mt&&(mt.style.maxWidth="",mt.style.marginLeft="",mt.style.marginRight=""));let ro=o.statusIndicator??{},wg=ro.visible??!0;if(L.style.display=wg?"":"none",N){let oe=N.getStatus();qt(L,(ft=>ft==="idle"?ro.idleText??Lt.idle:ft==="connecting"?ro.connectingText??Lt.connecting:ft==="connected"?ro.connectedText??Lt.connected:ft==="error"?ro.errorText??Lt.error:Lt[ft])(oe),ro,oe)}L.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xg=ro.align==="left"?"persona-text-left":ro.align==="center"?"persona-text-center":"persona-text-right";L.classList.add(xg)},open(){_()&&it(!0,"api")},close(){_()&&it(!1,"api")},toggle(){_()&&it(!Y,"api")},reconnect(){N.reconnectNow()},clearChat(){Rn=!1,N.clearMessages(),So.clear(),eo();try{localStorage.removeItem(Tr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Tr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c?.clear&&Li(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ae?.clear(),Te?.reset(),qe?.update()},setMessage(i){return!z||N.isStreaming()?!1:(!Y&&_()&&it(!0,"system"),z.value=i,z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(N.isStreaming())return!1;let f=i?.trim()||z.value.trim();return f?(!Y&&_()&&it(!0,"system"),z.value="",z.style.height="auto",N.sendMessage(f),!0):!1},startVoiceRecognition(){return N.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()||(!Y&&_()&&it(!0,"system"),Ve.manuallyDeactivated=!1,xn(),N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("user"),N.isVoiceActive()&&Zo()})),!0):kn?!0:od()?(!Y&&_()&&it(!0,"system"),Ve.manuallyDeactivated=!1,xn(),ra("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()?(N.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,xn(),Hn("user"),Dn()}),!0):!1:kn?(Ve.manuallyDeactivated=!0,xn(),no("user"),!0):!1},injectMessage(i){return!Y&&_()&&it(!0,"system"),N.injectMessage(i)},injectAssistantMessage(i){!Y&&_()&&it(!0,"system");let f=N.injectAssistantMessage(i);return ge&&(ge=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),f},injectUserMessage(i){return!Y&&_()&&it(!0,"system"),N.injectUserMessage(i)},injectSystemMessage(i){return!Y&&_()&&it(!0,"system"),N.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&_()&&it(!0,"system"),N.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&_()&&it(!0,"system"),N.injectComponentDirective(i)},injectTestMessage(i){!Y&&_()&&it(!0,"system"),N.injectTestEvent(i)},async connectStream(i,f){return N.connectStream(i,f)},__pushEventStreamEvent(i){Ae&&(Te?.processEvent(i.type,i.payload),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ie||!Ae||vi()},hideEventStream(){ze&&Lr()},isEventStreamVisible(){return ze},showArtifacts(){Yt(o)&&(Rn=!1,Vo=!0,Wn(),Ge?.setMobileOpen(!0))},hideArtifacts(){Yt(o)&&(Rn=!0,Wn())},upsertArtifact(i){return Yt(o)?(io(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Rn=!1,Vo=!0),N.upsertArtifact(i)):null},selectArtifact(i){Yt(o)&&N.selectArtifact(i)},clearArtifacts(){Yt(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return M&&!Y&&!D()||!z?!1:(z.focus(),!0)},async resolveApproval(i,f,m){let S=N.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===i);if(!S?.approval)throw new Error(`Approval not found: ${i}`);if(S.approval.toolType==="webmcp"){N.resolveWebMcpApproval(S.id,f);return}return N.resolveApproval(S.approval,f,m)},setFollowUpSuggestions(i){Ff(i)},clearFollowUpSuggestions(){Hc()},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){P(i)},on(i,f){return p.on(i,f)},off(i,f){p.off(i,f)},isOpen(){return _()&&Y},isVoiceActive(){return Ve.active},toggleReadAloud(i){N.toggleReadAloud(i)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(i){return N.getReadAloudState(i)},onReadAloudChange(i){return N.onReadAloudChange(i)},getState(){return{open:_()&&Y,launcherEnabled:M,voiceActive:Ve.active,streaming:N.isStreaming()}},showCSATFeedback(i){!Y&&_()&&it(!0,"system");let f=Re.querySelector(".persona-feedback-container");f&&f.remove();let m=df({onSubmit:async(b,S)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});Re.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&_()&&it(!0,"system");let f=Re.querySelector(".persona-feedback-container");f&&f.remove();let m=pf({onSubmit:async(b,S)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});Re.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,f){return N.submitCSATFeedback(i,f)},async submitNPSFeedback(i,f){return N.submitNPSFeedback(i,f)},destroy(){Fi(),Lo!=null&&(clearInterval(Lo),Lo=null),Oe.forEach(i=>i()),Be.remove(),Xe?.remove(),Ft?.destroy(),Qt?.remove(),Co&&B.removeEventListener("click",Co)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,f={controller:Mt,getMessages:Mt.getMessages,getStatus:Mt.getStatus,getMetadata:Mt.getPersistentMetadata,updateMetadata:Mt.updatePersistentMetadata,clearHistory:()=>Mt.clearChat(),setVoiceActive:m=>m?Mt.startVoiceRecognition():Mt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,Oe.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.focusInput()};if(window.addEventListener("persona:focusInput",f),Oe.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let O=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===i)&&Mt.showEventStream()},G=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===i)&&Mt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",G),Oe.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",G)})}let m=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.showArtifacts()},b=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.hideArtifacts()},S=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&Mt.upsertArtifact(G.artifact)},E=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&Mt.selectArtifact(G.id)},X=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",X),Oe.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",X)})}let un=Bb(o.persistState);if(un&&_()){let i=Db(un.storage),f=`${un.keyPrefix}widget-open`,m=`${un.keyPrefix}widget-voice`,b=`${un.keyPrefix}widget-voice-mode`;if(i){let S=un.persist?.openState&&i.getItem(f)==="true",E=un.persist?.voiceState&&i.getItem(m)==="true",X=un.persist?.voiceState&&i.getItem(b)==="true";if(S&&setTimeout(()=>{Mt.open(),setTimeout(()=>{if(E||X)Mt.startVoiceRecognition();else if(un.persist?.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),un.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(f,"true")}),p.on("widget:closed",()=>{i.setItem(f,"false")})),un.persist?.voiceState&&(p.on("voice:state",O=>{i.setItem(m,O.active?"true":"false")}),p.on("user:message",O=>{i.setItem(b,O.viaVoice?"true":"false")})),un.clearOnChatClear){let O=()=>{i.removeItem(f),i.removeItem(m),i.removeItem(b)},G=()=>O();window.addEventListener("persona:clear-chat",G),Oe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(g&&_()&&setTimeout(()=>{Mt.open()},0),Xo(),!Nf){let i=ga(()=>{N&&(Ti++,So.clear(),zr(Re,N.getMessages(),Z))});Oe.push(i)}return Mt};var hf=(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},Ob=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},_b=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},$b=(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 s=o.offsetHeight>0;o.remove(),!(!r||s)&&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.")},yf=(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"},tc=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=""},bf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",tc(e)},Yl=e=>{e.style.transition=""},Zl=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=""},ec=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},yi=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ub=(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))},zb=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},jb=e=>{let t=gr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Xt(t,r)??r;return{inset:o(n?.inset,Ba),canvasBackground:o(n?.canvasBackground,Da)}},vf=(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},Vb=(e,t,n,o,r,s,a,l)=>{let p=hn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";Ub(e,t,n,o,d),zb(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"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 g=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,P=g!=null?g.innerWidth<=x:!1;if(v&&P&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Zl(t),Yl(o),bf(o),ec(n),yi(r,o),vf(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(s?.launcher?.zIndex??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),bf(o),Ob(o,p.maxHeight),vf(o,c&&a,u,w),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Zl(t),Yl(o),ec(n),yi(r,o);let k=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":T;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=k,o.style.transform=M,o.style.pointerEvents=a?"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",Yl(o),tc(o),yi(r,o);let k=hf(p.width,e.clientWidth),T=Math.max(0,e.clientWidth),M=p.animate?"margin-left 180ms ease":"none",U=p.side==="right"?a?-k:0:a?0:-k;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=`${T+k}px`,t.style.transition=M,t.style.marginLeft=`${U}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}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=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Zl(t),tc(o),ec(n),yi(r,o);let k=p.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=a?p.width:"0px",M=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",U=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",_b(o,p.maxHeight),o.style.overflow=k||U?"hidden":"visible",o.style.transition=M,k){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let j=c?`calc(${hf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=j,r.style.minWidth=j,r.style.maxWidth=j,r.style.boxSizing="border-box"}}},qb=(e,t)=>{let n=e.ownerDocument.createElement("div");return yf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){yf(n,o)},destroy(){n.remove()}}},Kb=(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 s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let w=null,g=()=>{w?.disconnect(),w=null},v=null,x=()=>{v=t?.launcher?.detachedPanel===!0?jb(t):null};x();let P=()=>{Vb(a,l,p,d,c,t,u,v)},F=null,k=()=>{F?.(),F=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(F=Fa(()=>{x(),P()}))},T=()=>{g(),hn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},M=!1,U=()=>{P(),T(),u&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,$b(a,hn(t)))},j=a.ownerDocument.defaultView,A=()=>{U()};return j?.addEventListener("resize",A),hn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),U(),k(),{mode:"docked",host:c,shell:a,syncWidgetState(V){let K=V.launcherEnabled?V.open:!0;u!==K&&(u=K,U())},updateConfig(V){t=V,(t?.launcher?.enabled??!0)===!1&&(u=!0),x(),U(),k()},destroy(){j?.removeEventListener("resize",A),F?.(),F=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},wf=(e,t)=>Dt(t)?Kb(e,t):qb(e,t);var Ds={desktop:{w:1280,h:800},mobile:{w:390,h:844}},xf=.15,Cf=1.5,nc="persona-preview-shell-theme",Gb={load:()=>null,save:()=>{},clear:()=>{}},Qb=["How do I get started?","Pricing & plans","Talk to support"];function oc(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Xb(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Af(e){let t=Xb(e);return`* { box-sizing: border-box; }
|
|
141
141
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
142
142
|
html { color-scheme: ${e}; }
|
|
143
143
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -161,7 +161,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
161
161
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
162
162
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
163
163
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
164
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
164
|
+
.preview-workspace-card.short { height: 96px; }`}function Sf(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(nc);o||(o=n.createElement("style"),o.id=nc,n.head.appendChild(o)),o.textContent=Af(t)}var Jb=`
|
|
165
165
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
166
166
|
<div class="preview-iframe-chrome">
|
|
167
167
|
<span class="preview-iframe-dot"></span>
|
|
@@ -180,7 +180,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
180
180
|
<div class="preview-iframe-line body"></div>
|
|
181
181
|
<div class="preview-iframe-line body"></div>
|
|
182
182
|
</div>
|
|
183
|
-
</div>`,
|
|
183
|
+
</div>`,Yb=`
|
|
184
184
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
185
185
|
<div class="preview-iframe-line hero"></div>
|
|
186
186
|
<div class="preview-iframe-line body"></div>
|
|
@@ -193,8 +193,8 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
193
193
|
<div class="preview-workspace-card short"></div>
|
|
194
194
|
<div class="preview-workspace-card short"></div>
|
|
195
195
|
</div>
|
|
196
|
-
</div>`;function
|
|
197
|
-
${
|
|
196
|
+
</div>`;function Tf(e,t,n,o){let r=`
|
|
197
|
+
${Jb}
|
|
198
198
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
|
|
199
199
|
<div class="preview-workspace-shell">
|
|
200
200
|
<div class="preview-workspace-topbar">
|
|
@@ -206,7 +206,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
206
206
|
</div>
|
|
207
207
|
<div class="preview-workspace-body">
|
|
208
208
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
209
|
-
${
|
|
209
|
+
${Yb}
|
|
210
210
|
</div>
|
|
211
211
|
</div>
|
|
212
212
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
214
214
|
<head>
|
|
215
215
|
<meta charset="UTF-8">
|
|
216
216
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
217
|
-
<link rel="stylesheet" href="${
|
|
218
|
-
<style id="${
|
|
217
|
+
<link rel="stylesheet" href="${oc(o)}">
|
|
218
|
+
<style id="${nc}">${Af(t)}</style>
|
|
219
219
|
</head>
|
|
220
220
|
<body>
|
|
221
221
|
${n?s:r}
|
|
222
222
|
</body>
|
|
223
|
-
</html>`}var
|
|
224
|
-
${
|
|
225
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
226
|
-
</div>`,
|
|
223
|
+
</html>`}var Zb=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],ev=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function tv(e,t,n=[]){if(e==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return e==="home"?[]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&ev(t)?[...Zb(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function nv(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:Qb:e.suggestionChips,initialMessages:tv(t,e,n),storageAdapter:Gb};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function ov(e,t){let n=e.theme?fr(e.theme,{validate:!1}):fr();return{...rt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Mr(e,t){let n=e.scene??"conversation";return nv(ov(e,t),n,e.appendedMessages??[])}function Mf(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Mr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Mr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Mr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Mr(e,n),shellMode:n}]}function rv(e,t){let n={...t},o=[],r=[],s=null,a=!1,l=1,p=1,d=0;function c(){return n.device??"desktop"}function u(){return n.zoom??l}function w(){let k=getComputedStyle(e),T=parseFloat(k.paddingLeft)+parseFloat(k.paddingRight),M=parseFloat(k.paddingTop)+parseFloat(k.paddingBottom),U=40,j=(n.compareMode??"off")!=="off",A=(e.clientWidth-T-U)/(j?2:1),V=e.clientHeight-M-U;if(A<=0||V<=0)return 1;let K=Ds[c()]??Ds.desktop;return Math.min(A/K.w,V/K.h,1)}function g(){l=w();let k=Math.max(xf,Math.min(Cf,u()));p=k;let T=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let M of T){let U=M.dataset.device??"desktop",j=Ds[U]??Ds.desktop;M.style.width=`${j.w*k}px`,M.style.height=`${j.h*k}px`,U==="mobile"&&(M.style.borderRadius=`${32*k}px`);let A=M.querySelector("iframe");A&&(A.style.width=`${j.w}px`,A.style.height=`${j.h}px`,A.style.transformOrigin="top left",A.style.transition="none",A.style.transform=`scale(${k})`)}n.onScaleChange?.(k)}function v(){n.onBeforeDestroy?.();for(let k of o)k.destroy();for(let k of r)k();o=[],r=[]}function x(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function P(){if(a)return;v();let k=++d,T=Mf(n),M=c(),U=(n.compareMode??"off")!=="off",j=(n.scene??"conversation")==="minimized",A=n.widgetCssPath??"/widget-dist/widget.css",V=n.buildSrcdoc??Tf,K=M==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",ne=ce=>`<div class="${K}" data-mount-id="${ce.mountId}" data-device="${M}" data-shell-mode="${ce.shellMode}">
|
|
224
|
+
${U?`<div class="preview-frame-meta"><span class="preview-frame-label">${oc(ce.label)}</span></div>`:""}
|
|
225
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ce.mountId}"></iframe>
|
|
226
|
+
</div>`,D=U?`<div class="preview-compare-grid">${T.map(ce=>`<div class="preview-compare-cell">${ne(ce)}</div>`).join("")}</div>`:`<div class="preview-single">${ne(T[0])}</div>`;n.morphContainer?n.morphContainer(e,D):e.innerHTML=D,g();let _=x(),Y=0,ge=_.length,he=()=>{if(a||k!==d)return;for(let Z of _){let de=Z.dataset.mountId;if(!de||!Z.contentDocument)continue;let te=T.find(ye=>ye.mountId===de);if(!te)continue;let ie=()=>{},J=Dt(te.config),fe=J?(()=>{let ye=Z.contentDocument?.getElementById(`preview-content-${de}`);if(!ye)return null;let xe=wf(ye,te.config),ve=Z.contentDocument.createElement("div");ve.id=de,ve.style.height="100%",ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1",ve.style.minHeight="0",xe.host.appendChild(ve);let Ae=()=>xe.syncWidgetState(Ce.getState()),Te=ie;return ie=()=>{xe.destroy(),Te()},ve.__syncDock=Ae,ve.__hostLayout=xe,ve})():Z.contentDocument.getElementById(de);if(!fe)continue;let Ce=mf(fe,te.config);if(o.push(Ce),J&&fe.__syncDock){let ye=fe.__syncDock,xe=Ce.on("widget:opened",ye),ve=Ce.on("widget:closed",ye),Ae=ie;ie=()=>{xe(),ve(),Ae()},ye()}r.push(ie),j&&Ce.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let Z of o)Z.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
227
227
|
|
|
228
228
|
This is a preview of the artifact sidebar.
|
|
229
229
|
|
|
@@ -231,4 +231,4 @@ This is a preview of the artifact sidebar.
|
|
|
231
231
|
|
|
232
232
|
- Markdown rendering
|
|
233
233
|
- Document toolbar
|
|
234
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes
|
|
234
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:_,controllers:[...o]})};for(let ce of _){let Z=ce.dataset.mountId;if(!Z)continue;let de=T.find(te=>te.mountId===Z);de&&(ce.addEventListener("load",()=>{Y++,Y>=ge&&he()},{once:!0}),ce.srcdoc=V(Z,de.shellMode,Dt(de.config),A))}ge===0&&he()}function F(){if(a)return;let k=Mf(n);if(o.length!==k.length){P();return}if(k.some(M=>{let U=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${M.mountId}"]`);return!U||U.dataset.shellMode!==M.shellMode})){P();return}o.forEach((M,U)=>{M.update(k[U].config),(n.scene??"conversation")==="minimized"&&M.close()});for(let M of k){let U=e.querySelector(`iframe[data-mount-id="${M.mountId}"]`);U&&Sf(U,M.shellMode)}n.onAfterUpdate?.({iframes:x(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(e)),P(),{update(k){if(a)return;let T=k.device!==void 0&&k.device!==n.device||k.scene!==void 0&&k.scene!==n.scene||k.compareMode!==void 0&&k.compareMode!==n.compareMode||k.widgetCssPath!==void 0&&k.widgetCssPath!==n.widgetCssPath;n={...n,...k},T?P():F()},destroy(){a||(a=!0,v(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return x()},getScale(){return p},setZoom(k){a||(n={...n,zoom:k},g())}}}export{rv as createThemePreview};
|