@runtypelabs/persona 4.6.1 → 4.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.cjs +2 -2
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/glyph-cycle.js +2 -2
- package/dist/animations/{types-CSmiKRVa.d.cts → types-BsZtXPKK.d.cts} +43 -3
- package/dist/animations/{types-CSmiKRVa.d.ts → types-BsZtXPKK.d.ts} +43 -3
- package/dist/animations/wipe.cjs +2 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-5EIIHQLQ.js +1 -0
- package/dist/codegen.cjs +12 -12
- package/dist/codegen.js +14 -14
- package/dist/index.cjs +91 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +918 -174
- package/dist/index.d.ts +918 -174
- package/dist/index.global.js +81 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +89 -66
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +24 -24
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.js +1 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-reconnect-JKIJBHS5.js +1 -0
- package/dist/smart-dom-reader.cjs +17 -17
- package/dist/smart-dom-reader.d.cts +753 -15
- package/dist/smart-dom-reader.d.ts +753 -15
- package/dist/smart-dom-reader.js +17 -17
- package/dist/testing.cjs +3 -3
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +81 -58
- package/dist/theme-editor-preview.d.cts +761 -15
- package/dist/theme-editor-preview.d.ts +761 -15
- package/dist/theme-editor-preview.js +81 -58
- package/dist/theme-editor.cjs +6 -6
- package/dist/theme-editor.d.cts +753 -15
- package/dist/theme-editor.d.ts +753 -15
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +74 -0
- package/dist/theme-reference.d.ts +74 -0
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +2 -2
- package/dist/voice-worklet-player.js +2 -2
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +2 -3
- package/src/artifacts-session.test.ts +178 -0
- package/src/client.test.ts +500 -1
- package/src/client.ts +285 -93
- package/src/components/artifact-card.test.ts +333 -0
- package/src/components/artifact-card.ts +75 -28
- package/src/components/artifact-inline.test.ts +1328 -0
- package/src/components/artifact-inline.ts +920 -0
- package/src/components/artifact-pane.test.ts +1042 -0
- package/src/components/artifact-pane.ts +440 -131
- package/src/components/artifact-preview.test.ts +1155 -0
- package/src/components/artifact-preview.ts +994 -0
- package/src/components/pill-composer-builder.test.ts +6 -2
- package/src/components/pill-composer-builder.ts +6 -6
- package/src/components/reasoning-bubble.ts +1 -13
- package/src/components/registry.ts +38 -3
- package/src/components/tool-bubble.ts +1 -13
- package/src/defaults.ts +1 -0
- package/src/generated/runtype-openapi-contract.ts +55 -3
- package/src/index-core.ts +20 -1
- package/src/index.ts +8 -0
- package/src/markdown-parsers-loader.test.ts +158 -0
- package/src/markdown-parsers-loader.ts +74 -9
- package/src/runtime/host-layout.test.ts +163 -0
- package/src/runtime/host-layout.ts +110 -7
- package/src/runtime/init.ts +18 -61
- package/src/runtime/persist-state.test.ts +118 -0
- package/src/session.ts +76 -22
- package/src/styles/widget.css +773 -26
- package/src/theme-editor/preview.ts +2 -0
- package/src/theme-editor/sections.test.ts +26 -1
- package/src/theme-editor/sections.ts +10 -2
- package/src/theme-reference.ts +2 -2
- package/src/tool-call-display-defaults.test.ts +1 -0
- package/src/types/theme.ts +77 -0
- package/src/types.ts +516 -17
- package/src/ui.artifact-pane-gating.test.ts +636 -0
- package/src/ui.component-directive.test.ts +104 -0
- package/src/ui.composer-bar.test.ts +60 -2
- package/src/ui.detached-panel.test.ts +1049 -0
- package/src/ui.scroll-additive.test.ts +1 -1
- package/src/ui.streaming-coalescing.test.ts +312 -0
- package/src/ui.tool-display.test.ts +51 -0
- package/src/ui.ts +933 -214
- package/src/utils/artifact-custom-actions.ts +128 -0
- package/src/utils/artifact-display.test.ts +42 -0
- package/src/utils/artifact-display.ts +84 -0
- package/src/utils/artifact-file.test.ts +116 -0
- package/src/utils/artifact-file.ts +117 -0
- package/src/utils/artifact-gate.test.ts +112 -5
- package/src/utils/artifact-gate.ts +39 -14
- package/src/utils/artifact-loading-status.ts +55 -0
- package/src/utils/artifact-status-label.ts +190 -0
- package/src/utils/buttons.ts +7 -1
- package/src/utils/code-highlight.test.ts +186 -0
- package/src/utils/code-highlight.ts +400 -0
- package/src/utils/icons.ts +2 -0
- package/src/utils/roving-tablist.test.ts +152 -0
- package/src/utils/roving-tablist.ts +111 -0
- package/src/utils/spinner.ts +45 -0
- package/src/utils/theme.test.ts +48 -0
- package/src/utils/theme.ts +7 -0
- package/src/utils/tokens.ts +91 -0
- package/src/utils/tool-loading-animation.test.ts +32 -0
- package/src/utils/tool-loading-animation.ts +24 -0
- package/dist/chunk-DFBSCFYN.js +0 -1
- package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
- package/dist/session-reconnect-U77QFUR7.js +0 -1
|
@@ -1,22 +1,28 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),
|
|
3
|
-
`):
|
|
1
|
+
import{a as Nc}from"./chunk-5EIIHQLQ.js";var Fc=null,_r=null,Mo=null,Vs=new Set,Oc=t=>{_r=t;let e=[...Vs];Vs.clear();for(let n of e)try{n()}catch{}return t};var Ks=t=>_r?()=>{}:(Vs.add(t),nf().catch(()=>{}),()=>{Vs.delete(t)});var _c=t=>{throw Mo=null,t},nf=()=>_r?Promise.resolve(_r):Mo||(Fc?(Mo=Fc().then(Oc,_c),Mo):(Mo=import("./markdown-parsers-entry-NVFT3TE6.js").then(Oc,_c),Mo)),Wn=()=>_r;var of=t=>{if(t)return t},Ti=t=>{let e=null;return n=>{let o=Wn();if(!o)return Jn(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=of(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Gs=t=>t?Ti({markedOptions:t.options,renderer:t.renderer}):Ti(),Av=Ti();var Jn=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var rf={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"]},sf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,af=()=>{let t=null;return e=>{let n=Wn();if(!n)return Jn(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!sf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,rf)}},Xs=t=>t===!1?null:typeof t=="function"?t:af();var $c=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Uc=t=>t.includes("|"),zc=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},lf=t=>`| ${t.join(" | ")} |`,cf=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,df=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),jc=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Uc(r)||$c.test(r)||!$c.test(s))continue;let a=zc(r).length;if(a<1)continue;let l=cf(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let d=e[p];if(d.trim()===""||!Uc(d))break;let c=lf(df(zc(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
|
|
3
|
+
`):t};var Bn="webmcp:",Mi=new Map,qc=t=>{Mi.clear();for(let e of t){let n=e.title?.trim();n&&Mi.set(e.name,n)}},$r=t=>Mi.get(Xc(t)),Qs={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Vc=null;function Gc(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${pf(e.join(""))}`}function Kc(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.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 pf(t){let e=Kc(t,0).toString(36),n=Kc(t,2654435761).toString(36);return`${e}.${n}`}var Js=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Qs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}qc(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=ff(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return vn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return vn(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=Xc(e),a;try{a=await r.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return vn(`Failed to read WebMCP registry: ${x}`)}qc(a);let l=a.find(v=>v.name===s);if(!l)return vn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return vn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return vn("Aborted by cancel()");let p=$r(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return vn("User declined the tool call.");if(o?.aborted)return vn("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let v=await r.executeTool(l,yf(n),{signal:c.signal});return gf(v)}catch(v){if(u)return vn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return vn("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return vn(x)}finally{clearTimeout(w),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Vc?await Vc():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Qs.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Qs.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):e}async requestConfirm(e){let n=this.confirmHandler??mf;try{return await n(e)}catch(o){return Qs.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>uf(e,o))}},Xc=t=>t.startsWith(Bn)?t.slice(Bn.length):t,Jo=t=>t.startsWith(Bn),uf=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},ff=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},gf=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:bf(e)}]}},vn=t=>({isError:!0,content:[{type:"text",text:t}]}),mf=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=hf(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
|
-
${e}`:"")+(
|
|
6
|
+
${e}`:"")+(t.description?`
|
|
7
7
|
|
|
8
|
-
${n.description}`:"");return window.confirm(t)},Xg=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Jg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Yg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var Zg="agent_",ef="flow_";function pu(n){return n.startsWith(Zg)?{kind:"agentId",agentId:n}:n.startsWith(ef)?{kind:"flowId",flowId:n}:null}function uu(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),i=t.slice(r+1);if(a==="runtype"){let c=pu(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)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:d(i).payload}}let o=pu(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as tf,ARR as nf,OBJ as rf,STR as of}from"partial-json";var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Pr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Os=(...n)=>n.filter(Boolean).join(" ");var wi="ask_user_question",_s=8,is="data-persona-ask-sheet-for",sf="Other",af="Other\u2026",gu="Type your own answer here",fu="Send",lf="Next",cf="Back",df="Submit all",pf="Skip",uf=3,xi="data-ask-current-index",Ci="data-ask-question-count",hu="data-ask-answers",Ai="data-ask-grouped",yu="data-ask-layout",mf=n=>n.layout==="pills"?"pills":"rows",gf=n=>n.getAttribute(yu)==="pills"?"pills":"rows",mu=!1,bu=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===wi,Si=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ls=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=tf(o,of|rf|nf);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},$s=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>_s&&!mu&&(mu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${_s}.`)),e.slice(0,_s)},ff=n=>{var e;return(e=$s(n)[0])!=null?e:null},hf=(n,e)=>{var t;return(t=$s(n)[e])!=null?t:null},yf=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},vu=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},bf=(n,e,t,r)=>{let s=b("button",t==="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",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=vu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},vf=n=>{let t=b("span",n==="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 t.setAttribute("aria-hidden","true"),t},wf=(n,e,t,r)=>{var u,g,h;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<uf;m++)s.appendChild(vf(r));return s}if(d.forEach((m,v)=>{s.appendChild(bf(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?sf:af;if(r==="rows"){let v=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=e.freeTextPlaceholder)!=null?u:gu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(T),v.appendChild(w);let B=vu(r,a,d.length);B&&v.appendChild(B),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(h=e.freeTextLabel)!=null?h:m,s.appendChild(v)}}return s},wu=(n,e)=>{var s,a;let r=b("div",e==="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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:gu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:fu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xf=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:fu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Cf=(n,e,t)=>{var c,u,g,h;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:cf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:pf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(g=t.submitAllLabel)!=null?g:df:(h=t.nextLabel)!=null?h:lf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Oo=n=>{let e=n.getAttribute(hu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},xu=(n,e)=>{n.setAttribute(hu,JSON.stringify(e))},er=n=>{var t;let e=Number((t=n.getAttribute(xi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Af=(n,e)=>{n.setAttribute(xi,String(Math.max(0,Math.floor(e))))},cs=n=>{var t;let e=Number((t=n.getAttribute(Ci))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},go=n=>n.getAttribute(Ai)==="true",Sf=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Tf=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},xa=(n,e)=>{let{payload:t}=ls(e),r=$s(t),o=Oo(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Cu=n=>{let e=Oo(n),t=er(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Au=n=>{if(!go(n))return;let e=Oo(n),t=er(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ti=(n,e,t)=>{let r=Si(t),o=gf(n),{payload:s,complete:a}=ls(e),i=go(n),d=er(n),c=cs(n),u=i?hf(s,d):ff(s),g=!!(u!=null&&u.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let S=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let S=wf(u,r,a,o);w.replaceWith(S)}if(o!=="rows"){let S=n.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(wu(r,o))}let T=n.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?n.appendChild(xf(r)):(!g||i)&&T&&T.remove(),n.setAttribute("data-multi-select",g?"true":"false");let B=n.querySelector('[data-ask-nav-row="true"]');if(i){let S=Cf(d,c,r);B?B.replaceWith(S):n.appendChild(S)}else B&&B.remove();Cu(n),Au(n)},Mf=(n,e,t)=>{let r=Si(e),o=mf(r),s=n.toolCall.id,a=$s(t),i=Math.max(1,a.length),d=i>1,c=Sf(n,a),u=d?Tf(n,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(is,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(Ci,String(i)),g.setAttribute(xi,String(u)),g.setAttribute(Ai,d?"true":"false"),g.setAttribute(yu,o),xu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),yf(g,r);let h=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",h.appendChild(v),g.appendChild(h);let T=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),o!=="rows"&&g.appendChild(wu(r,o)),Ti(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ef=(n,e,t)=>{let{payload:r}=ls(e),o=Math.max(1,$s(r).length);o>cs(n)&&(n.setAttribute(Ci,String(o)),o>1&&!go(n)&&n.setAttribute(Ai,"true")),Ti(n,e,t)};var Ca=(n,e,t)=>{if(!t||!Fo(n)||Si(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${is}]`).forEach(c=>{c.getAttribute(is)!==o&&c.remove()});let a=t.querySelector(`[${is}="${bu(o)}"]`);if(a){Ef(a,n,e);return}let{payload:i}=ls(n),d=Mf(n,e,i);t.appendChild(d)},ds=(n,e)=>{if(!n)return;let t=e?`[${is}="${bu(e)}"]`:`[${is}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Mi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),fo=(n,e)=>{let t=Oo(n),r=er(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,xu(n,t),Cu(n),Au(n)},Aa=(n,e,t,r)=>{let o=cs(n),s=Math.max(0,Math.min(o-1,r));Af(n,s),Ti(n,e,t)};var zr="suggest_replies";var kf={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},Su={name:zr,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:kf,origin:"sdk",annotations:{readOnlyHint:!0}},Ei=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ki=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===zr},Lf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Tu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!ki(r))continue;let o=Lf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},Mu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var Pf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:_s,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},If={name:wi,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:Pf,origin:"sdk",annotations:{readOnlyHint:!0}},Li=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(If),Mu(n)&&e.push(Su),e};import{parse as Wf,STR as Rf,OBJ as Hf}from"partial-json";var Eu=n=>n.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Pu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Iu=()=>{var e;let n=Nf();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Wu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=Wf(t,Rf|Hf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Eu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Eu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Ru=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Hu="4.6.1";var js=Hu;var Of="https://api.runtype.com/v1/dispatch",Ea="https://api.runtype.com";function _f(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ii=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function $f(n){switch(n){case"json":return Wu;case"regex-json":return Iu;case"xml":return Ru;default:return Pu}}var Bu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Uf(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Bu(t);if(!Bu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=qs(n);return qs(e)!==null&&a===null?e:n}var Vs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:Of,this.headers={"Content-Type":"application/json","X-Persona-Version":js,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:$f(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new wa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=uu(r,o);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(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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 r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.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}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/feedback`}async sendFeedback(e){var a,i;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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(Ii).map(M=>{var k,C,P;return{id:M.id,role:M.role,content:(P=(C=(k=M.contentParts)!=null?k:M.llmContent)!=null?C:M.rawContent)!=null?P:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},h=c.clientTools,m=!!(h&&h.length>0),v=m?cu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&w&&this.lastSentClientToolsFingerprint===v,B=!1,S=null,L;for(let M=0;;M++){let C={...g,...m&&(B||!T)&&h?{clientTools:h}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(C),signal:r.signal}),L.status===409&&M===0&&m){let P=await L.json().catch(()=>null);if((P==null?void 0:P.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}S=P!=null?P:{error:"Chat request failed"}}break}if(!L.ok){let M=S!=null?S:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(L.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let k=new Error(M.error||"Failed to send message");throw t({type:"error",error:k}),k}if(!L.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ea}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Ii).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let g=new Date(c.createdAt).getTime(),h=new Date(u.createdAt).getTime();return g-h}).map(c=>{var u,g,h;return{role:c.role,content:(h=(g=(u=c.contentParts)!=null?u:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Li(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async u=>{try{let g=await u({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(Ii).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return u-g}).map(d=>{var c,u,g;return{role:d.role,content:(g=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Li(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=g,o(g),g},c=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var gn,fr,hr,Ue;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,u=()=>d+c++,g=E=>{let me=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,Me=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,ke=E.tools?E.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...E,reasoning:me,toolCall:Me,tools:ke}},h=E=>{if(E.role!=="assistant"||E.variant)return!0;let me=Array.isArray(E.contentParts)&&E.contentParts.length>0,Me=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||me||Me||!!E.stopReason},m=E=>{h(E)&&t({type:"message",message:g(E)})},v=null,w=null,T={current:null},B={current:null},S=null,L="",M=new Map,k=new Map,C=new Map,P=new Map,U=new Map,_={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},$=E=>{if(E==null)return null;try{return String(E)}catch{return null}},N=E=>{var me,Me,ke,Re,tt;return $((tt=(Re=(ke=(Me=(me=E.stepId)!=null?me:E.step_id)!=null?Me:E.step)!=null?ke:E.parentId)!=null?Re:E.flowStepId)!=null?tt:E.flow_step_id)},te=E=>{var me,Me,ke,Re,tt,Qe,ht;return $((ht=(Qe=(tt=(Re=(ke=(Me=(me=E.callId)!=null?me:E.call_id)!=null?Me:E.requestId)!=null?ke:E.request_id)!=null?Re:E.toolCallId)!=null?tt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ht:E.step_id)},Ee=r,de=!1,Y=()=>{if(v)return v;let E,me="",Me=S;return!de&&Ee?(E=Ee,de=!0,me=o!=null?o:""):Ee&&Me?E=`${Ee}_${Me}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:E,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(v),v},Le=(E,me)=>{_.lastId=me,E&&_.byStep.set(E,me)},Pe=(E,me)=>{var tt;let Me=(tt=E.reasoningId)!=null?tt:E.id,ke=N(E);if(Me){let Qe=String(Me);return Le(ke,Qe),Qe}if(ke){let Qe=_.byStep.get(ke);if(Qe)return _.lastId=Qe,Qe}if(_.lastId&&!me)return _.lastId;if(!me)return null;let Re=`reason-${u()}`;return Le(ke,Re),Re},ae=E=>{let me=P.get(E);if(me)return me;let Me={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:E,status:"streaming",chunks:[]}};return P.set(E,Me),m(Me),Me},fe=(E,me)=>{I.lastId=me,E&&I.byCall.set(E,me)},ne=new Set,re=new Map,ce=new Set,Ce=new Map,_e=E=>{if(!E)return!1;let me=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},V=(E,me)=>{var tt;let Me=(tt=E.toolId)!=null?tt:E.id,ke=te(E);if(Me){let Qe=String(Me);return fe(ke,Qe),Qe}if(ke){let Qe=I.byCall.get(ke);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!me)return I.lastId;if(!me)return null;let Re=`tool-${u()}`;return fe(ke,Re),Re},X=E=>{let me=U.get(E);if(me)return me;let Me={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:E,status:"pending"}};return U.set(E,Me),m(Me),Me},Ae=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let me=Number(E);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Me=Date.parse(E);if(!Number.isNaN(Me))return Me}return Date.now()},J=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},ie=new Map,Se=new Map,Je=new Map,et=(E,me,Me)=>{var ht;let ke=Je.get(E);ke||(ke=[],Je.set(E,ke));let Re=0,tt=ke.length;for(;Re<tt;){let ge=Re+tt>>>1;ke[ge].seq<me?Re=ge+1:tt=ge}((ht=ke[Re])==null?void 0:ht.seq)===me?ke[Re]={seq:me,text:Me}:ke.splice(Re,0,{seq:me,text:Me});let Qe="";for(let ge=0;ge<ke.length;ge++)Qe+=ke[ge].text;return Qe},Wt=(E,me)=>{let Me=J(me),ke=Se.get(E.id),Re=Uf(ke,Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=le=>{var Ke;let gt=(Ke=E.content)!=null?Ke:"";le.trim()!==""&&(gt.trim().length===0||le.startsWith(gt)||le.trimStart().startsWith(gt.trim()))&&(E.content=le)},ht=()=>{var le;if(tt){let gt=(le=tt.close)==null?void 0:le.call(tt);gt instanceof Promise&>.catch(()=>{})}ie.delete(E.id),Se.delete(E.id),E.streaming=!1,m(E)};if(!tt){Qe(Me),ht();return}let ge=qs(Re);if(ge!==null&&ge.trim()!==""){Qe(ge),ht();return}let H=le=>{var Lt;let gt=typeof le=="string"?le:(Lt=le==null?void 0:le.text)!=null?Lt:null;if(gt!==null&>.trim()!=="")return gt;let Ke=tt.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Me},be;try{be=tt.processChunk(Re)}catch{Qe(Me),ht();return}if(be instanceof Promise){be.then(le=>{Qe(H(le)),ht()}).catch(()=>{Qe(Me),ht()});return}Qe(H(be)),ht()},ft=null,rt=(E,me,Me,ke)=>{var ge;E.rawContent=me,ie.has(E.id)||ie.set(E.id,this.createStreamParser());let Re=ie.get(E.id),tt=me.trim().startsWith("{")||me.trim().startsWith("[");if(tt&&Se.set(E.id,me),Re.__isPlainTextParser===!0){E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E);return}let ht=Re.processChunk(me);if(ht instanceof Promise)ht.then(H=>{var le;let be=typeof H=="string"?H:(le=H==null?void 0:H.text)!=null?le:null;be!==null&&be.trim()!==""?(E.content=be,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}).catch(()=>{E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E)});else{let H=typeof ht=="string"?ht:(ge=ht==null?void 0:ht.text)!=null?ge:null;H!==null&&H.trim()!==""?(E.content=H,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}},ue=(E,me)=>{var ge,H;let Me=me!=null?me:E.content;if(Me==null||Me===""){E.streaming=!1,m(E);return}let ke=Se.get(E.id),Re=ke!=null?ke:J(Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=null,ht=!1;if(tt&&(Qe=tt.getExtractedText(),Qe===null&&(Qe=qs(Re)),Qe===null)){let be=tt.processChunk(Re);be instanceof Promise?(ht=!0,be.then(le=>{var Ke;let gt=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;gt!==null&&(E.content=gt,E.streaming=!1,ie.delete(E.id),Se.delete(E.id),m(E))}).catch(()=>{})):Qe=typeof be=="string"?be:(ge=be==null?void 0:be.text)!=null?ge:null}if(!ht){Qe!==null&&Qe.trim()!==""?E.content=Qe:Se.has(E.id)||(E.content=J(Me));let be=ie.get(E.id);if(be){let le=(H=be.close)==null?void 0:H.call(be);le instanceof Promise&&le.catch(()=>{}),ie.delete(E.id)}Se.delete(E.id),E.streaming=!1,m(E)}},Q=(E,me,Me)=>{let ke=k.get(E);if(ke)return ke;let Re={id:`nested-${me}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return k.set(E,Re),m(Re),Re},it=[],je,Te=new Map,we=0,Ye="agent",qt=!1,ye=null,pe=null,wn=new Map,Ct=(gn=this.config.iterationDisplay)!=null?gn:"separate";for(je=()=>{var E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr,xe,Dr,Gn,Ot,Qn,Nr,As,Go,Ss,So,Cr,eo,lt,nn,rn,Ar,Ts,Fr,To,Sr,F,Qo,ir,Tr,Or,Mr,lr,Xo,pa,fn,Cn,cr,An,Mo,dr,hn,Er,Jo,Eo,Yo,to;for(let no=0;no<it.length;no++){let ot=it[no].payloadType,x=it[no].payload;if(!qt&&Ye!=="flow"&&typeof x.stepType=="string"&&(Ye="flow"),ot==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q),Q(j,q,"reasoning");continue}let G=(E=Pe(x,!0))!=null?E:`reason-${u()}`,K=ae(G);K.reasoning=(me=K.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Ae((Me=x.startedAt)!=null?Me:x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(ot==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let De=k.get(j),nt=(Qe=(tt=(Re=x.reasoningText)!=null?Re:x.text)!=null?tt:x.delta)!=null?Qe:"";nt&&x.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(nt)),m(De));continue}let q=(ge=(ht=Pe(x,!1))!=null?ht:Pe(x,!0))!=null?ge:`reason-${u()}`,G=ae(q);G.reasoning=(H=G.reasoning)!=null?H:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(le=G.reasoning.startedAt)!=null?le:Ae((be=x.startedAt)!=null?be:x.timestamp);let K=(Lt=(Ke=(gt=x.reasoningText)!=null?gt:x.text)!=null?Ke:x.delta)!=null?Lt:"";if(K&&x.hidden!==!0){let De=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(De!==void 0){let nt=et(q,De,String(K));G.reasoning.chunks=[nt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=x.done?"complete":"streaming",x.done){G.reasoning.completedAt=Ae((Et=x.completedAt)!=null?Et:x.timestamp);let De=(vt=G.reasoning.startedAt)!=null?vt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-De)}G.streaming=G.reasoning.status!=="complete",m(G)}else if(ot==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let nt=k.get(j);if(nt.reasoning){let ct=typeof x.text=="string"?x.text:"";ct&&nt.reasoning.chunks.length===0&&nt.reasoning.chunks.push(ct),nt.reasoning.status="complete",nt.streaming=!1,m(nt)}M.delete(j),k.delete(j);continue}let q=(Ft=(Qt=Pe(x,!1))!=null?Qt:Pe(x,!0))!=null?Ft:`reason-${u()}`,G=typeof x.text=="string"?x.text:"";!P.get(q)&&(G||x.scope==="loop")&&ae(q);let K=P.get(q);if(K!=null&&K.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Ae((Zt=x.completedAt)!=null?Zt:x.timestamp);let nt=(yr=K.reasoning.startedAt)!=null?yr:Date.now();K.reasoning.durationMs=Math.max(0,((Wr=K.reasoning.completedAt)!=null?Wr:Date.now())-nt),K.streaming=!1,m(K)}let De=N(x);De&&_.byStep.delete(De)}else if(ot==="tool_start"){v&&(v.streaming=!1,m(v),v=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(rr=(nr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?nr:V(x,!0))!=null?rr:`tool-${u()}`,q=(Vr=x.toolName)!=null?Vr:x.name;if(_e(q)){ne.add(j);continue}fe(te(x),j);let G=X(j),K=(jt=G.toolCall)!=null?jt:{id:j,status:"pending"};K.name=q!=null?q:K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=(Rr=K.startedAt)!=null?Rr:Ae((or=x.startedAt)!=null?or:x.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,x.executionId&&(G.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(G)}else if(ot==="tool_output_delta"){let j=(kn=(Hn=V(x,!1))!=null?Hn:V(x,!0))!=null?kn:`tool-${u()}`;if(ne.has(j))continue;let q=X(j),G=(Bn=q.toolCall)!=null?Bn:{id:j,status:"running"};G.startedAt=(br=G.startedAt)!=null?br:Ae((sr=x.startedAt)!=null?sr:x.timestamp);let K=(Gr=(jn=(Kr=x.text)!=null?Kr:x.delta)!=null?jn:x.message)!=null?Gr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Hr=q.agentMetadata)!=null?Hr:{executionId:(vr=De==null?void 0:De.executionId)!=null?vr:x.executionId,iteration:(wr=De==null?void 0:De.iteration)!=null?wr:x.iteration}),m(q)}else if(ot==="tool_complete"){let j=(yt=(ar=V(x,!1))!=null?ar:V(x,!0))!=null?yt:`tool-${u()}`;if(ne.has(j)){ne.delete(j);continue}let q=X(j),G=(wo=q.toolCall)!=null?wo:{id:j,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=Ae((xr=x.completedAt)!=null?xr:x.timestamp);let K=(xo=x.duration)!=null?xo:x.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((Ko=G.completedAt)!=null?Ko:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Xr=q.agentMetadata)!=null?Xr:{executionId:(Qr=De==null?void 0:De.executionId)!=null?Qr:x.executionId,iteration:(Br=De==null?void 0:De.iteration)!=null?Br:x.iteration}),m(q);let nt=te(x);nt&&I.byCall.delete(nt)}else if(ot==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,q=(Jr=j!=null?j:x.toolId)!=null?Jr:`local-${u()}`,G=X(q),K=x.toolName,De=x.origin==="webmcp"&&!as(K)?`webmcp:${K}`:K,nt=as(De),ct=(Co=G.toolCall)!=null?Co:{id:q,status:"pending"};ct.name=De,ct.args=x.parameters,ct.status=nt?"running":"complete",ct.chunks=(Ao=ct.chunks)!=null?Ao:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Ae((wt=(Yr=x.startedAt)!=null?Yr:x.timestamp)!=null?wt:x.awaitedAt),nt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=x.executionId)!=null?St:(xn=G.agentMetadata)==null?void 0:xn.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},m(G)}else if(ot==="text_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q);continue}let G=v;G&&(Ye==="flow"?(ue(G),ft=G):(G.streaming=!1,m(G)),v=null),S=typeof x.id=="string"?x.id:S,L=""}else if(ot==="text_delta"){let j=typeof x.id=="string"?x.id:null,q=j?M.get(j):void 0;if(j&&q){let K=typeof x.delta=="string"?x.delta:"",De=((Vn=C.get(j))!=null?Vn:"")+K;if(C.set(j,De),De.trim()==="")continue;let nt=Q(j,q);nt.agentMetadata={...nt.agentMetadata,executionId:x.executionId,parentToolId:q},rt(nt,De,K,void 0);continue}if(S=typeof x.id=="string"?x.id:S,Ye==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(L+=K,L.trim()==="")continue;let De=Y();De.agentMetadata={executionId:x.executionId,iteration:x.iteration},rt(De,L,K,void 0),w=De;continue}let G=Y();G.content+=(Kn=x.delta)!=null?Kn:"",G.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:ye!=null?ye:void 0,agentName:pe==null?void 0:pe.agentName},w=G,m(G)}else if(ot==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)){let G=k.get(j);G&&ue(G),M.delete(j),C.delete(j),k.delete(j);continue}let q=v;q&&(Ye==="flow"?(ue(q),ft=q):(((Fn=q.content)!=null?Fn:"")===""&&typeof x.text=="string"&&(q.content=x.text),q.streaming=!1,m(q)),v=null),S=null,L=""}else if(ot==="step_complete"){let j=x.stepType,q=x.executionType;if(j==="tool"||q==="context")continue;if(x.success===!1){let G=x.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((Zr=G.message)!=null?Zr:"Step failed"):"Step failed";t({type:"error",error:new Error(K)});let De=v;De&&De.streaming&&(De.streaming=!1,m(De)),t({type:"status",status:"idle"});continue}{let G=ft;ft=null;let K=x.stopReason,De=(xe=x.result)==null?void 0:xe.response;if(G)K&&(G.stopReason=K),De!=null?Wt(G,De):G.streaming!==!1&&(ie.delete(G.id),Se.delete(G.id),G.streaming=!1,m(G));else{let nt=De!=null&&De!=="";if(nt||K){let ct=Y();K&&(ct.stopReason=K),nt?ue(ct,De):(ct.streaming=!1,m(ct))}}continue}}else if(ot==="execution_start")Ye=x.kind==="flow"?"flow":"agent",qt=!0,Ye==="agent"&&(pe={executionId:x.executionId,agentId:(Dr=x.agentId)!=null?Dr:"virtual",agentName:(Gn=x.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ot=x.maxTurns)!=null?Ot:1,startedAt:Ae(x.startedAt)});else if(ot==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(pe&&(pe.currentIteration=j),Ct==="separate"&&j>1){let q=v;q&&(q.streaming=!1,m(q),wn.set(j-1,q),v=null)}we=j}ye=typeof x.id=="string"?x.id:null,w=null}else if(ot==="tool_input_delta"){let j=(Qn=x.toolCallId)!=null?Qn:I.lastId;if(j){let q=U.get(j);q!=null&&q.toolCall&&(q.toolCall.chunks=(Nr=q.toolCall.chunks)!=null?Nr:[],q.toolCall.chunks.push((As=x.delta)!=null?As:""),m(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=x.stopReason,q=v!=null?v:w;if(j&&q!==null){let G=x.id;(!G||((Go=q.agentMetadata)==null?void 0:Go.turnId)===G)&&(q.stopReason=j,m(q))}ye===x.id&&(ye=null)}else if(ot==="media_start"){let j=String(x.id);Te.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Te.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(ot==="media_complete"){let j=String(x.id),q=Te.get(j);Te.delete(j);let G=(So=(Ss=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ss:q==null?void 0:q.mediaType)!=null?So:"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,De=typeof x.url=="string"?x.url:q&&q.parts.length>0?q.parts.join(""):void 0,nt=null;if(K)nt={type:"media",data:K,mediaType:G};else if(De){let Pn=G.toLowerCase();nt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:De,mediaType:G}}let ct=(Cr=x.toolCallId)!=null?Cr:q==null?void 0:q.toolCallId,ii=nt?[nt]:[],ro=[];for(let Pn of ii){if(!Pn||typeof Pn!="object")continue;let Xt=Pn,oo=typeof Xt.type=="string"?Xt.type:void 0,Xn=typeof Xt.mediaType=="string"?Xt.mediaType.toLowerCase():"",Sn=null,In="";if(oo==="media"){let Tn=typeof Xt.data=="string"?Xt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(oo==="image-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(oo==="file-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(oo==="image-url"||In.startsWith("image/"))ro.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))ro.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))ro.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";ro.push({type:"file",data:Sn,mimeType:Tn,filename:_f(Tn)})}}if(ro.length>0){let Pn=u(),Xt=ct,Xn={id:`agent-media-${typeof Xt=="string"&&Xt.length>0?`${Xt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:ro,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};m(Xn);let Sn=v;Sn&&(Sn.streaming=!1,m(Sn)),v=null,T.current=null}}else if(ot==="execution_complete"){let j=(eo=x.kind)!=null?eo:Ye;j==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=Ae(x.completedAt),pe.stopReason=x.stopReason);let q=v;q&&(j==="flow"&&q.streaming!==!1?ue(q):(q.streaming=!1,m(q)),v=null),S=null,L="",ft=null,t({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let j=typeof x.error=="string"?x.error:(nn=(lt=x.error)==null?void 0:lt.message)!=null?nn:"Execution error";t({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(rn=x.approvalId)!=null?rn:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(Ar=pe==null?void 0:pe.agentId)!=null?Ar:"virtual",executionId:(Fr=(Ts=x.executionId)!=null?Ts:pe==null?void 0:pe.executionId)!=null?Fr:"",toolName:(To=x.toolName)!=null?To:"",toolType:x.toolType,description:(F=x.description)!=null?F:`Execute ${(Sr=x.toolName)!=null?Sr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="step_await"&&x.awaitReason==="approval_required"){let j=(Qo=x.approvalId)!=null?Qo:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(ir=pe==null?void 0:pe.agentId)!=null?ir:"virtual",executionId:(Or=(Tr=x.executionId)!=null?Tr:pe==null?void 0:pe.executionId)!=null?Or:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Xo=x.description)!=null?Xo:`Execute ${(lr=x.toolName)!=null?lr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="approval_complete"){let j=x.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:(pa=x.decision)!=null?pa:"approved",agentId:(fn=pe==null?void 0:pe.agentId)!=null?fn:"virtual",executionId:(cr=(Cn=x.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?cr:"",toolName:(An=x.toolName)!=null?An:"",description:(Mo=x.description)!=null?Mo:"",resolvedAt:Date.now()}};m(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=x.artifactType,q=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:q,artifactType:j,title:G,component:typeof x.component=="string"?x.component:void 0}),Ce.set(q,{markdown:"",title:G}),!ce.has(q)){ce.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:j,status:"streaming"}})};re.set(q,K),m(K)}}else if(ot==="artifact_delta"){let j=String(x.id),q=typeof x.delta=="string"?x.delta:String((dr=x.delta)!=null?dr:"");t({type:"artifact_delta",id:j,artDelta:q});let G=Ce.get(j);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(ot==="artifact_complete"){let j=String(x.id);t({type:"artifact_complete",id:j});let q=re.get(j);if(q){q.streaming=!1;try{let G=JSON.parse((hn=q.rawContent)!=null?hn:"{}");if(G.props){G.props.status="complete";let K=Ce.get(j);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}Ce.delete(j),m(q),re.delete(j)}}}else if(ot==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let q=String((Er=j.id)!=null?Er:`msg-${u()}`),G=j.role,De={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:u()};if(m(De),De.rawContent)try{let nt=JSON.parse(De.rawContent),ct=(Jo=nt==null?void 0:nt.props)==null?void 0:Jo.artifactId;typeof ct=="string"&&ce.add(ct)}catch{}v=null,T.current=null,ie.delete(q),Se.delete(q)}else if(ot==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Eo=x.error)==null?void 0:Eo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(j)});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(ot==="dispatch_error"){let q=(Yo=x.message)!=null?Yo:x.error;q!=null&&q!==""&&(j=new Error(String(q)))}else{let q=x.error;typeof q=="string"&&q!==""?j=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(j=new Error(String((to=q.message)!=null?to:q)))}if(j){t({type:"error",error:j});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:E,value:me}=await s.read();if(E)break;i+=a.decode(me,{stream:!0});let Me=i.split(`
|
|
8
|
+
${t.description}`:"");return window.confirm(n)},hf=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},yf=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},bf=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Eo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function Ys(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var vf="agent_",wf="flow_";function Qc(t){return t.startsWith(vf)?{kind:"agentId",agentId:t}:t.startsWith(wf)?{kind:"flowId",flowId:t}:null}function Jc(t,e){let n=t.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=Qc(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[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=Qc(n);if(r)return r;let s=e?.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 xf,ARR as Cf,OBJ as Af,STR as Sf}from"partial-json";var m=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Sn=(t,e,n)=>{let o=t.createElement(e);return n&&(o.className=n),o},Yc=()=>document.createDocumentFragment(),nt=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let p=a[l];p!=null&&(s[l]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},ko=(...t)=>t.filter(Boolean).join(" ");var Ei="ask_user_question",Ur=8,Yo="data-persona-ask-sheet-for",Tf="Other",Mf="Other\u2026",ed="Type your own answer here",td="Send",Ef="Next",kf="Back",Lf="Submit all",Pf="Skip",If=3,ki="data-ask-current-index",Li="data-ask-question-count",nd="data-ask-answers",Pi="data-ask-grouped",od="data-ask-layout",Rf=t=>t.layout==="pills"?"pills":"rows",Wf=t=>t.getAttribute(od)==="pills"?"pills":"rows",Zc=!1,rd=t=>t.replace(/["\\]/g,"\\$&"),Lo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Ei,Ii=t=>t?.features?.askUserQuestion??{},Zo=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=xf(r,Sf|Af|Cf);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},zr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ur&&!Zc&&(Zc=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ur}.`)),e.slice(0,Ur)},Bf=t=>zr(t)[0]??null,Hf=(t,e)=>zr(t)[e]??null,Df=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},sd=(t,e,n)=>{if(t!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Nf=(t,e,n,o)=>{let s=m("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(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=m("span","persona-ask-row-content"),l=m("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let d=m("span","persona-ask-row-description");d.textContent=t.description,a.appendChild(d)}s.appendChild(a);let p=sd(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Ff=t=>{let n=m("span",t==="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},Of=(t,e,n,o)=>{let s=m("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=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<If;c++)s.appendChild(Ff(o));return s}if(p.forEach((c,u)=>{s.appendChild(Nf(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?Tf:Mf;if(o==="rows"){let u=m("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=m("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=e.freeTextPlaceholder??ed,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=sd(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=m("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=e.freeTextLabel??c,s.appendChild(u)}}return s},ad=(t,e)=>{let o=m("div",e==="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=t.freeTextPlaceholder??ed,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??td,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},_f=t=>{let e=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??td,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},$f=(t,e,n)=>{let o=m("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=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??kf,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Pf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=m("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??Lf:n.nextLabel??Ef,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=t=>{let e=t.getAttribute(nd);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},id=(t,e)=>{t.setAttribute(nd,JSON.stringify(e))},pn=t=>{let e=Number(t.getAttribute(ki)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Uf=(t,e)=>{t.setAttribute(ki,String(Math.max(0,Math.floor(e))))},er=t=>{let e=Number(t.getAttribute(Li)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Yn=t=>t.getAttribute(Pi)==="true",zf=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.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},jf=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Zs=(t,e)=>{let{payload:n}=Zo(e),o=zr(n),r=Po(t),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},ld=t=>{let e=Po(t),n=pn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.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=t.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="")},cd=t=>{if(!Yn(t))return;let e=Po(t),n=pn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ri=(t,e,n)=>{let o=Ii(n),r=Wf(t),{payload:s,complete:a}=Zo(e),l=Yn(t),p=pn(t),d=er(t),c=l?Hf(s,p):Bf(s),u=!!c?.multiSelect,w=t.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=t.querySelector('[data-ask-question="true"]');if(v){let T=typeof c?.question=="string"?c.question:"";v.textContent=T,v.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let x=t.querySelector('[data-ask-pill-list="true"]');if(x){let T=Of(c,o,a,r);x.replaceWith(T)}if(r!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(ad(o,r))}let P=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?t.appendChild(_f(o)):(!u||l)&&P&&P.remove(),t.setAttribute("data-multi-select",u?"true":"false");let W=t.querySelector('[data-ask-nav-row="true"]');if(l){let T=$f(p,d,o);W?W.replaceWith(T):t.appendChild(T)}else W&&W.remove();ld(t),cd(t)},qf=(t,e,n)=>{let o=Ii(e),r=Rf(o),s=t.toolCall.id,a=zr(n),l=Math.max(1,a.length),p=l>1,d=zf(t,a),c=p?jf(t,l):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Yo,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Li,String(l)),u.setAttribute(ki,String(c)),u.setAttribute(Pi,p?"true":"false"),u.setAttribute(od,r),id(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`),Df(u,o);let w=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let v=m("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let P=m("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(ad(o,r)),Ri(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Vf=(t,e,n)=>{let{payload:o}=Zo(e),r=Math.max(1,zr(o).length);r>er(t)&&(t.setAttribute(Li,String(r)),r>1&&!Yn(t)&&t.setAttribute(Pi,"true")),Ri(t,e,n)};var ea=(t,e,n)=>{if(!n||!Lo(t)||Ii(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Yo}]`).forEach(d=>{d.getAttribute(Yo)!==r&&d.remove()});let a=n.querySelector(`[${Yo}="${rd(r)}"]`);if(a){Vf(a,t,e);return}let{payload:l}=Zo(t),p=qf(t,e,l);n.appendChild(p)},tr=(t,e)=>{if(!t)return;let n=e?`[${Yo}="${rd(e)}"]`:`[${Yo}]`;t.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)})},Wi=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Zn=(t,e)=>{let n=Po(t),o=pn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,id(t,n),ld(t),cd(t)},ta=(t,e,n,o)=>{let r=er(t),s=Math.max(0,Math.min(r-1,o));Uf(t,s),Ri(t,e,n)};var Hn="suggest_replies";var Kf={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},dd={name:Hn,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:Kf,origin:"sdk",annotations:{readOnlyHint:!0}},Bi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Hi=t=>t.variant==="tool"&&t.toolCall?.name===Hn,Gf=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.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},pd=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Hi(n))continue;let o=Gf(n.toolCall?.args);return o.length>0?o:null}return null},ud=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var Xf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ur,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},Qf={name:Ei,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:Xf,origin:"sdk",annotations:{readOnlyHint:!0}},na=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Qf),ud(t)&&e.push(dd),e};import{parse as Jf,STR as Yf,OBJ as Zf}from"partial-json";var fd=t=>t.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),eo=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},eg=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},gd=t=>t.status==="complete"?eg(t):t.status==="pending"?"Waiting":"",tg=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.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 md=t=>t.status==="complete"?tg(t):"Using tool...",oa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},qr=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return oa(e)},ra=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return oa(e)},Di=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=qr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},sa=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&jr(o,n.slice(s,a.index),[]),a[1]!==void 0?jr(o,a[1],["bold"]):a[2]!==void 0?jr(o,a[2],["italic"]):a[3]!==void 0&&jr(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&jr(o,n.slice(s),[]),o},jr=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},ng=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
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:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Vr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},hd=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},yd=()=>{let t=ng();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},bd=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=Jf(n,Yf|Zf);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?fd(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=fd(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var vd=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var wd="4.8.0";var Kr=wd;var rg="https://api.runtype.com/v1/dispatch",aa="https://api.runtype.com";function sg(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ni=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function ag(t){switch(t){case"json":return bd;case"regex-json":return yd;case"xml":return vd;default:return hd}}var xd=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function ig(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=xd(n);if(!xd(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Vr(t);return Vr(e)!==null&&a===null?e:t}var Gr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??rg,this.headers={"Content-Type":"application/json","X-Persona-Version":Kr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??ag(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new Js(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Jc(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(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||aa}/v1/client/${e}`}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Kr},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$/,"")||aa}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Kr},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(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,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:e,comment:n})}async submitNPSFeedback(e,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:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,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(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:e.messages.filter(Ni).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...e.assistantMessageId&&{assistantMessageId:e.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":Kr},body:JSON.stringify(c),signal:e.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,e.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(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.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:e.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:e.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(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.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:e.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:e.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,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||aa}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?Gc(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,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=e,s?this.sentNonEmptyClientToolsSessionId=e:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||aa}/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:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...na(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})}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(Ni).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,l)=>{let p=new Date(a.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(a=>({role:a.role,content:a.contentParts??a.llmContent??a.rawContent??a.content,createdAt:a.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...na(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(a,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(e){let n=e.slice().filter(Ni).sort((a,l)=>{let p=new Date(a.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(a=>({role:a.role,content:a.contentParts??a.llmContent??a.rawContent??a.content,createdAt:a.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[a,l]of Object.entries(o.targetPayload))a!=="messages"&&(r[a]=l);let s=[...na(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(a,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let l=a;return r.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=r.clientTools),l}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);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(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=M=>{let X=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,y=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,A=M.tools?M.tools.map(E=>({...E,chunks:E.chunks?[...E.chunks]:void 0})):void 0;return{...M,reasoning:X,toolCall:y,tools:A}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let X=Array.isArray(M.contentParts)&&M.contentParts.length>0,y=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||X||y||!!M.stopReason},f=M=>{w(M)&&n({type:"message",message:u(M)})},v=null,x=null,P={current:null},W={current:null},T=null,I="",H=new Map,q=new Map,U=new Map,$=new Map,C=new Map,j={lastId:null,byStep:new Map},J={lastId:null,byCall:new Map},D=M=>{if(M==null)return null;try{return String(M)}catch{return null}},_=M=>D(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),ce=M=>D(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),he=o,Me=!1,Ce=()=>{if(v)return v;let M,X="",y=T;return!Me&&he?(M=he,Me=!0,X=r??""):he&&y?M=`${he}_${y}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:X,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},te=(M,X)=>{j.lastId=X,M&&j.byStep.set(M,X)},ge=(M,X)=>{let y=M.reasoningId??M.id,A=_(M);if(y){let R=String(y);return te(A,R),R}if(A){let R=j.byStep.get(A);if(R)return j.lastId=R,R}if(j.lastId&&!X)return j.lastId;if(!X)return null;let E=`reason-${c()}`;return te(A,E),E},Y=M=>{let X=$.get(M);if(X)return X;let y={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return $.set(M,y),f(y),y},le=(M,X)=>{J.lastId=X,M&&J.byCall.set(M,X)},Z=new Set,be=new Map,ve=new Set,fe=new Map,Te=M=>{if(!M)return!1;let X=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return X==="emit_artifact_markdown"||X==="emit_artifact_component"},Ae=(M,X)=>{let y=M.toolId??M.id,A=ce(M);if(y){let R=String(y);return le(A,R),R}if(A){let R=J.byCall.get(A);if(R)return J.lastId=R,R}if(J.lastId&&!X)return J.lastId;if(!X)return null;let E=`tool-${c()}`;return le(A,E),E},ze=M=>{let X=C.get(M);if(X)return X;let y={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return C.set(M,y),f(y),y},Ne=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let X=Number(M);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let y=Date.parse(M);if(!Number.isNaN(y))return y}return Date.now()},Pe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},We=new Map,at=new Map,Oe=new Map,Xe=(M,X,y)=>{let A=Oe.get(M);A||(A=[],Oe.set(M,A));let E=0,R=A.length;for(;E<R;){let B=E+R>>>1;A[B].seq<X?E=B+1:R=B}A[E]?.seq===X?A[E]={seq:X,text:y}:A.splice(E,0,{seq:X,text:y});let K="";for(let B=0;B<A.length;B++)K+=A[B].text;return K},sn=(M,X)=>{let y=Pe(X),A=at.get(M.id),E=ig(A,y);M.rawContent=E;let R=We.get(M.id),K=Re=>{let lt=M.content??"";Re.trim()!==""&&(lt.trim().length===0||Re.startsWith(lt)||Re.trimStart().startsWith(lt.trim()))&&(M.content=Re)},B=()=>{if(R){let Re=R.close?.();Re instanceof Promise&&Re.catch(()=>{})}We.delete(M.id),at.delete(M.id),M.streaming=!1,f(M)};if(!R){K(y),B();return}let z=Vr(E);if(z!==null&&z.trim()!==""){K(z),B();return}let re=Re=>{let lt=typeof Re=="string"?Re:Re?.text??null;if(lt!==null&<.trim()!=="")return lt;let V=R.getExtractedText();return V!==null&&V.trim()!==""?V:y},et;try{et=R.processChunk(E)}catch{K(y),B();return}if(et instanceof Promise){et.then(Re=>{K(re(Re)),B()}).catch(()=>{K(y),B()});return}K(re(et)),B()},Et=null,ft=(M,X,y,A)=>{M.rawContent=X,We.has(M.id)||We.set(M.id,this.createStreamParser());let E=We.get(M.id),R=X.trim().startsWith("{")||X.trim().startsWith("[");if(R&&at.set(M.id,X),E.__isPlainTextParser===!0){M.content=A!==void 0?X:M.content+y,at.delete(M.id),We.delete(M.id),M.rawContent=void 0,f(M);return}let B=E.processChunk(X);if(B instanceof Promise)B.then(z=>{let re=typeof z=="string"?z:z?.text??null;re!==null&&re.trim()!==""?(M.content=re,f(M)):!R&&!X.trim().startsWith("<")&&(M.content=A!==void 0?X:M.content+y,at.delete(M.id),We.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=A!==void 0?X:M.content+y,at.delete(M.id),We.delete(M.id),M.rawContent=void 0,f(M)});else{let z=typeof B=="string"?B:B?.text??null;z!==null&&z.trim()!==""?(M.content=z,f(M)):!R&&!X.trim().startsWith("<")&&(M.content=A!==void 0?X:M.content+y,at.delete(M.id),We.delete(M.id),M.rawContent=void 0,f(M))}},Ee=(M,X)=>{let y=X??M.content;if(y==null||y===""){M.streaming=!1,f(M);return}let E=at.get(M.id)??Pe(y);M.rawContent=E;let R=We.get(M.id),K=null,B=!1;if(R&&(K=R.getExtractedText(),K===null&&(K=Vr(E)),K===null)){let z=R.processChunk(E);z instanceof Promise?(B=!0,z.then(re=>{let et=typeof re=="string"?re:re?.text??null;et!==null&&(M.content=et,M.streaming=!1,We.delete(M.id),at.delete(M.id),f(M))}).catch(()=>{})):K=typeof z=="string"?z:z?.text??null}if(!B){K!==null&&K.trim()!==""?M.content=K:at.has(M.id)||(M.content=Pe(y));let z=We.get(M.id);if(z){let re=z.close?.();re instanceof Promise&&re.catch(()=>{}),We.delete(M.id)}at.delete(M.id),M.streaming=!1,f(M)}},me=(M,X,y)=>{let A=q.get(M);if(A)return A;let E={id:`nested-${X}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:X}};return q.set(M,E),f(E),E},it=[],Ie,ue=new Map,ie=0,ye="agent",bt=!1,N=null,ne=null,De=new Map,ke=this.config.iterationDisplay??"separate";for(Ie=()=>{for(let M=0;M<it.length;M++){let X=it[M].payloadType,y=it[M].payload;if(!bt&&ye!=="flow"&&typeof y.stepType=="string"&&(ye="flow"),X==="reasoning_start"){let A=typeof y.id=="string"?y.id:null,E=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(A&&E){H.set(A,E),me(A,E,"reasoning");continue}let R=ge(y,!0)??`reason-${c()}`,K=Y(R);K.reasoning=K.reasoning??{id:R,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ne(y.startedAt??y.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(X==="reasoning_delta"){let A=typeof y.id=="string"?y.id:null;if(A&&H.has(A)&&q.has(A)){let B=q.get(A),z=y.reasoningText??y.text??y.delta??"";z&&y.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(z)),f(B));continue}let E=ge(y,!1)??ge(y,!0)??`reason-${c()}`,R=Y(E);R.reasoning=R.reasoning??{id:E,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Ne(y.startedAt??y.timestamp);let K=y.reasoningText??y.text??y.delta??"";if(K&&y.hidden!==!0){let B=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(B!==void 0){let z=Xe(E,B,String(K));R.reasoning.chunks=[z]}else R.reasoning.chunks.push(String(K))}if(R.reasoning.status=y.done?"complete":"streaming",y.done){R.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let B=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-B)}R.streaming=R.reasoning.status!=="complete",f(R)}else if(X==="reasoning_complete"){let A=typeof y.id=="string"?y.id:null;if(A&&H.has(A)&&q.has(A)){let z=q.get(A);if(z.reasoning){let re=typeof y.text=="string"?y.text:"";re&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(re),z.reasoning.status="complete",z.streaming=!1,f(z)}H.delete(A),q.delete(A);continue}let E=ge(y,!1)??ge(y,!0)??`reason-${c()}`,R=typeof y.text=="string"?y.text:"";!$.get(E)&&(R||y.scope==="loop")&&Y(E);let K=$.get(E);if(K?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),R&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(R),K.reasoning.status="complete",K.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let z=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-z),K.streaming=!1,f(K)}let B=_(y);B&&j.byStep.delete(B)}else if(X==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(ie=y.iteration);let A=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??Ae(y,!0)??`tool-${c()}`,E=y.toolName??y.name;if(Te(E)){Z.add(A);continue}le(ce(y),A);let R=ze(A),K=R.toolCall??{id:A,status:"pending"};K.name=E??K.name,K.status="running",y.parameters!==void 0?K.args=y.parameters:y.args!==void 0&&(K.args=y.args),K.startedAt=K.startedAt??Ne(y.startedAt??y.timestamp),K.completedAt=void 0,K.durationMs=void 0,R.toolCall=K,R.streaming=!0,y.executionId&&(R.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(R)}else if(X==="tool_output_delta"){let A=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(A))continue;let E=ze(A),R=E.toolCall??{id:A,status:"running"};R.startedAt=R.startedAt??Ne(y.startedAt??y.timestamp);let K=y.text??y.delta??y.message??"";K&&(R.chunks=R.chunks??[],R.chunks.push(String(K))),R.status="running",E.toolCall=R,E.streaming=!0;let B=y.agentContext;(B||y.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:B?.executionId??y.executionId,iteration:B?.iteration??y.iteration}),f(E)}else if(X==="tool_complete"){let A=Ae(y,!1)??Ae(y,!0)??`tool-${c()}`;if(Z.has(A)){Z.delete(A);continue}let E=ze(A),R=E.toolCall??{id:A,status:"running"};R.status="complete",y.result!==void 0&&(R.result=y.result),typeof y.duration=="number"&&(R.duration=y.duration),R.completedAt=Ne(y.completedAt??y.timestamp);let K=y.duration??y.executionTime;if(typeof K=="number")R.durationMs=K;else{let re=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-re)}E.toolCall=R,E.streaming=!1;let B=y.agentContext;(B||y.executionId)&&(E.agentMetadata=E.agentMetadata??{executionId:B?.executionId??y.executionId,iteration:B?.iteration??y.iteration}),f(E);let z=ce(y);z&&J.byCall.delete(z)}else if(X==="await"&&y.toolName){let A=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,E=A??y.toolId??`local-${c()}`,R=ze(E),K=y.toolName,B=y.origin==="webmcp"&&!Jo(K)?`webmcp:${K}`:K,z=Jo(B),re=R.toolCall??{id:E,status:"pending"};re.name=B,re.args=y.parameters,re.status=z?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ne(y.startedAt??y.timestamp??y.awaitedAt),z?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,R.toolCall=re,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:y.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...A?{webMcpToolCallId:A}:{}},f(R)}else if(X==="text_start"){let A=typeof y.id=="string"?y.id:null,E=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(A&&E){H.set(A,E);continue}let R=v;R&&(ye==="flow"?(Ee(R),Et=R):(R.streaming=!1,f(R)),v=null),T=typeof y.id=="string"?y.id:T,I=""}else if(X==="text_delta"){let A=typeof y.id=="string"?y.id:null,E=A?H.get(A):void 0;if(A&&E){let K=typeof y.delta=="string"?y.delta:"",B=(U.get(A)??"")+K;if(U.set(A,B),B.trim()==="")continue;let z=me(A,E);z.agentMetadata={...z.agentMetadata,executionId:y.executionId,parentToolId:E},ft(z,B,K,void 0);continue}if(T=typeof y.id=="string"?y.id:T,ye==="flow"){let K=typeof y.delta=="string"?y.delta:"";if(I+=K,I.trim()==="")continue;let B=Ce();B.agentMetadata={executionId:y.executionId,iteration:y.iteration},ft(B,I,K,void 0),x=B;continue}let R=Ce();R.content+=y.delta??"",R.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:N??void 0,agentName:ne?.agentName},x=R,f(R)}else if(X==="text_complete"){let A=typeof y.id=="string"?y.id:null;if(A&&H.has(A)){let R=q.get(A);R&&Ee(R),H.delete(A),U.delete(A),q.delete(A);continue}let E=v;E&&(ye==="flow"?(Ee(E),Et=E):((E.content??"")===""&&typeof y.text=="string"&&(E.content=y.text),E.streaming=!1,f(E)),v=null),T=null,I=""}else if(X==="step_complete"){let A=y.stepType,E=y.executionType;if(A==="tool"||E==="context")continue;if(y.success===!1){let R=y.error,K=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let B=v;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let R=Et;Et=null;let K=y.stopReason,B=y.result?.response;if(R)K&&(R.stopReason=K),B!=null?sn(R,B):R.streaming!==!1&&(We.delete(R.id),at.delete(R.id),R.streaming=!1,f(R));else{let z=B!=null&&B!=="";if(z||K){let re=Ce();K&&(re.stopReason=K),z?Ee(re,B):(re.streaming=!1,f(re))}}continue}}else if(X==="execution_start")ye=y.kind==="flow"?"flow":"agent",bt=!0,ye==="agent"&&(ne={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Ne(y.startedAt)});else if(X==="turn_start"){let A=typeof y.iteration=="number"?y.iteration:ie;if(A!==ie){if(ne&&(ne.currentIteration=A),ke==="separate"&&A>1){let E=v;E&&(E.streaming=!1,f(E),De.set(A-1,E),v=null)}ie=A}N=typeof y.id=="string"?y.id:null,x=null}else if(X==="tool_input_delta"){let A=y.toolCallId??J.lastId;if(A){let E=C.get(A);E?.toolCall&&(E.toolCall.chunks=E.toolCall.chunks??[],E.toolCall.chunks.push(y.delta??""),f(E))}}else{if(X==="tool_input_complete")continue;if(X==="turn_complete"){let A=y.stopReason,E=v??x;if(A&&E!==null){let R=y.id;(!R||E.agentMetadata?.turnId===R)&&(E.stopReason=A,f(E))}N===y.id&&(N=null)}else if(X==="media_start"){let A=String(y.id);ue.set(A,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(X==="media_delta"){let A=ue.get(String(y.id));A&&typeof y.delta=="string"&&A.parts.push(y.delta)}else if(X==="media_complete"){let A=String(y.id),E=ue.get(A);ue.delete(A);let R=(typeof y.mediaType=="string"?y.mediaType:void 0)??E?.mediaType??"application/octet-stream",K=typeof y.data=="string"?y.data:void 0,B=typeof y.url=="string"?y.url:E&&E.parts.length>0?E.parts.join(""):void 0,z=null;if(K)z={type:"media",data:K,mediaType:R};else if(B){let lt=R.toLowerCase();z={type:lt==="image"||lt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:R}}let re=y.toolCallId??E?.toolCallId,et=z?[z]:[],Re=[];for(let lt of et){if(!lt||typeof lt!="object")continue;let V=lt,$e=typeof V.type=="string"?V.type:void 0,xe=typeof V.mediaType=="string"?V.mediaType.toLowerCase():"",Be=null,Le="";if($e==="media"){let Qe=typeof V.data=="string"?V.data:void 0;if(!Qe)continue;Le=xe.length>0?xe:"application/octet-stream",Be=`data:${Le};base64,${Qe}`}else if($e==="image-url"){let Qe=typeof V.url=="string"?V.url:void 0;if(!Qe)continue;Le=xe,Be=Qe}else if($e==="file-url"){let Qe=typeof V.url=="string"?V.url:void 0;if(!Qe)continue;Le=xe,Be=Qe}else continue;if(Be)if($e==="image-url"||Le.startsWith("image/"))Re.push({type:"image",image:Be,...Le.includes("/")?{mimeType:Le}:{}});else if(Le.startsWith("audio/"))Re.push({type:"audio",audio:Be,mimeType:Le});else if(Le.startsWith("video/"))Re.push({type:"video",video:Be,mimeType:Le});else{let Qe=Le||"application/octet-stream";Re.push({type:"file",data:Be,mimeType:Qe,filename:sg(Qe)})}}if(Re.length>0){let lt=c(),V=re,xe={id:`agent-media-${typeof V=="string"&&V.length>0?`${V}-${lt}`:String(lt)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:lt,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:ie}};f(xe);let Be=v;Be&&(Be.streaming=!1,f(Be)),v=null,P.current=null}}else if(X==="execution_complete"){let A=y.kind??ye;A==="agent"&&ne&&(ne.status=y.success?"complete":"error",ne.completedAt=Ne(y.completedAt),ne.stopReason=y.stopReason);let E=v;E&&(A==="flow"&&E.streaming!==!1?Ee(E):(E.streaming=!1,f(E)),v=null),T=null,I="",Et=null,n({type:"status",status:"idle",terminal:!0})}else if(X==="execution_error"){let A=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(A)})}else if(X!=="ping"){if(X==="approval_start"){let A=y.approvalId??`approval-${c()}`,E={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:ne?.agentId??"virtual",executionId:y.executionId??ne?.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(E)}else if(X==="step_await"&&y.awaitReason==="approval_required"){let A=y.approvalId??`approval-${c()}`,E={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:ne?.agentId??"virtual",executionId:y.executionId??ne?.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(E)}else if(X==="approval_complete"){let A=y.approvalId;if(A){let R={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:y.decision??"approved",agentId:ne?.agentId??"virtual",executionId:y.executionId??ne?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(R)}}else if(X==="artifact_start"||X==="artifact_delta"||X==="artifact_update"||X==="artifact_complete"){if(X==="artifact_start"){let A=y.artifactType,E=String(y.id),R=typeof y.title=="string"?y.title:void 0,K=y.file,B;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(B={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:E,artifactType:A,title:R,component:typeof y.component=="string"?y.component:void 0,...B?{file:B}:{}});let z=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(fe.set(E,{markdown:"",title:R,file:B,...z?{props:z}:{}}),!ve.has(E)){ve.add(E);let re=Eo(this.config.features?.artifacts,A),et=typeof y.component=="string"?y.component:void 0,Re={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ys(re,{artifactId:E,title:R,artifactType:A,status:"streaming",...B?{file:B}:{},...et?{component:et}:{}})};be.set(E,Re),f(Re)}}else if(X==="artifact_delta"){let A=String(y.id),E=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:A,artDelta:E});let R=fe.get(A);R&&(R.markdown+=E)}else if(X==="artifact_update"){let A=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:A,component:typeof y.component=="string"?y.component:void 0});let E=fe.get(String(y.id));E&&(E.props={...E.props??{},...A})}else if(X==="artifact_complete"){let A=String(y.id);n({type:"artifact_complete",id:A});let E=be.get(A);if(E){E.streaming=!1;try{let R=JSON.parse(E.rawContent??"{}");if(R.props){R.props.status="complete";let K=fe.get(A);K?.markdown&&(R.props.markdown=K.markdown),K?.file&&(R.props.file=K.file),R.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(R.props.componentProps=K.props)}E.rawContent=JSON.stringify(R)}catch{}fe.delete(A),f(E),be.delete(A)}}}else if(X==="transcript_insert"){let A=y.message;if(!A||typeof A!="object")continue;let E=String(A.id??`msg-${c()}`),R=A.role,B={id:E,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof A.content=="string"?A.content:"",rawContent:typeof A.rawContent=="string"?A.rawContent:void 0,createdAt:typeof A.createdAt=="string"?A.createdAt:new Date().toISOString(),streaming:A.streaming===!0,...typeof A.variant=="string"?{variant:A.variant}:{},sequence:c()};if(f(B),B.rawContent)try{let re=JSON.parse(B.rawContent)?.props?.artifactId;typeof re=="string"&&ve.add(re)}catch{}v=null,P.current=null,We.delete(E),at.delete(E)}else if(X==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let A=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(A)});let E=v;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}else if(X==="step_error"||X==="dispatch_error"||X==="flow_error"){let A=null;if(y.error instanceof Error)A=y.error;else if(X==="dispatch_error"){let E=y.message??y.error;E!=null&&E!==""&&(A=new Error(String(E)))}else{let E=y.error;typeof E=="string"&&E!==""?A=new Error(E):E!=null&&typeof E=="object"&&Reflect.has(E,"message")&&(A=new Error(String(E.message??E)))}if(A){n({type:"error",error:A});let E=v;E&&E.streaming&&(E.streaming=!1,f(E)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:X}=await s.read();if(M)break;l+=a.decode(X,{stream:!0});let y=l.split(`
|
|
12
12
|
|
|
13
|
-
`);
|
|
14
|
-
`),tt="message",Qe="",ht=null;for(let le of Re)le.startsWith("event:")?tt=le.replace("event:","").trim():le.startsWith("data:")?Qe+=le.replace("data:","").trim():le.startsWith("id:")&&(ht=le.slice(3).trim());let ge=()=>{ht!==null&&ht!==""&&t({type:"cursor",id:ht})};if(!Qe){ge();continue}let H;try{H=JSON.parse(Qe)}catch(le){t({type:"error",error:le instanceof Error?le:new Error("Failed to parse chat stream payload")});continue}let be=tt!=="message"?tt:(hr=H.type)!=null?hr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,be,H),this.parseSSEEvent){T.current=v;let le=await this.handleCustomSSEEvent(H,t,T,m,u,B);if(T.current&&T.current!==v&&(v=T.current),le){ge();continue}}it.push({payloadType:be,payload:H}),je(),ge()}}je()}};function ka(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function ps(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var La="[Image]";function Wi(n){return{type:"text",text:n}}var Du=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zf=["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"],qr=[...Du,...zf];function qf(n){return Du.includes(n)||n.startsWith("image/")}function Pa(n){return qf(n.type)}async function Nu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Pa(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function Fu(n,e=qr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function jf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Ou(n,e){let t=jf(e).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"}[n]||t||"FILE"}var _u=16e3,Vf=24e3,Kf=4096,Gf=1380533830;function Qf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===Gf?new Uint8Array(n,44):new Uint8Array(n)}function Xf(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Ks=class{constructor(e){this.config=e;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(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:_u,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:_u});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Zp(Vf);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Xf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(m,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,v,o))},v.onmessage=w=>this.handleMessage(w,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let T=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(Kf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let g=Math.max(-1,Math.min(1,d[u]));c[u]=g<0?g*32768:g*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Qf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var _o=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function us(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ks(n.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function $u(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return us({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return us({type:"runtype",runtype:n.runtype});if(_o.isSupported())return us({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ri(n){try{return $u(n),!0}catch{return!1}}function Ia(n){var t;let e=["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 r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var ms=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(u=t.onError)==null||u.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Gs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function Hi(n){if(!n)return"";let e=Jf(n);return Uu(e!==null?e:n)}function Jf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Uu(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);l=y.pop()??"";for(let A of y){let E=A.split(`
|
|
14
|
+
`),R="message",K="",B=null;for(let Re of E)Re.startsWith("event:")?R=Re.replace("event:","").trim():Re.startsWith("data:")?K+=Re.replace("data:","").trim():Re.startsWith("id:")&&(B=Re.slice(3).trim());let z=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!K){z();continue}let re;try{re=JSON.parse(K)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let et=R!=="message"?R:re.type??"message";if(this.onSSEEvent?.(et,re),this.parseSSEEvent){P.current=v;let Re=await this.handleCustomSSEEvent(re,n,P,f,c,W);if(P.current&&P.current!==v&&(v=P.current),Re){z();continue}}it.push({payloadType:et,payload:re}),Ie(),z()}}Ie()}};function ia(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function nr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var la="[Image]";function Fi(t){return{type:"text",text:t}}var Cd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],lg=["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"],Dn=[...Cd,...lg];function cg(t){return Cd.includes(t)||t.startsWith("image/")}function ca(t){return cg(t.type)}async function Ad(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ca(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Sd(t,e=Dn,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function dg(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Td(t,e){let n=dg(e).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"}[t]||n||"FILE"}var Md=16e3,pg=24e3,ug=4096,fg=1380533830;function gg(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===fg?new Uint8Array(t,44):new Uint8Array(t)}function mg(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Xr=class{constructor(e){this.config=e;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 e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)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:Md,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:Md});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Nc(pg);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=`${mg(o)}/ws/agents/${encodeURIComponent(e)}/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(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(ug,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(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.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(e,n){if(n!==this.callGeneration||!this.playback)return;let o=gg(e);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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Io=class{constructor(e={}){this.config=e;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(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,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(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function or(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Xr(t.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;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: ${t.type}`)}}function Ed(t){if(t?.type==="custom"&&t.custom)return or({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return or({type:"runtype",runtype:t.runtype});if(Io.isSupported())return or({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Oi(t){try{return Ed(t),!0}catch{return!1}}function da(t){let e=["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 e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var rr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):da(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.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(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Qr=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"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(e,"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(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function _i(t){if(!t)return"";let e=hg(t);return kd(e!==null?e:t)}function hg(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function kd(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),e=e.replace(/\n{2,}/g,`
|
|
16
|
-
`),e.trim()}var
|
|
16
|
+
`),e.trim()}var Ld=null;var $i=()=>Ld?Ld():import("./runtype-tts-entry-UJAEF7NZ.js");var yg=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function bg(t,e){return yg.some(n=>t[n]!==e[n])}function Ui(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(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: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]}),qu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,ju=n=>as(n)||n===zr,Wa=class{constructor(e={},t){this.config=e;this.callbacks=t;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 Gs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,u,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(as(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Vs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!t||!r||!this.config.clientToken||Bi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Ri((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=ms.isSupported()?new ms({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&u&&g)return Bi().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:v})=>{let w=new m({host:c,agentId:u,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new v(w,t,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=us(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,u,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Zf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Vs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:g}=e,m={id:a!=null?a:t==="user"?ka():t==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?ka():o==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,u,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=ka(),s=ps();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){if(this.status==="resuming"||this.reconnecting)return;let w=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!w){let T=Di(v,this.config.errorMessage);if(T){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(v instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,v):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=ps();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=Di(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var u,g,h,m,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let T=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}T=w.body}else w instanceof ReadableStream&&(T=w);T?await this.connectStream(T,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.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(w){let T=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(v=(m=this.callbacks).onError)==null||v.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,g,h,m,v,w,T,B,S,L,M,k;let r=this.messages.find(C=>C.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,P=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(P.length===1){let U=typeof((T=P[0])==null?void 0:T.question)=="string"?P[0].question:"";U&&(a={[U]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(S=e.toolCall)==null?void 0:S.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([P,U])=>`${P}: ${Array.isArray(U)?U.join(", "):U}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((P,U)=>{let _=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!_)return;let I=C[_],$=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let P=await C.json().catch(()=>null);throw new Error((L=P==null?void 0:P.error)!=null?L:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let P=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(k=(M=this.callbacks).onError)==null||k.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,u,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var k,C,P,U,_,I,$;let m=(k=h.toolCall)==null?void 0:k.name,v=(C=h.toolCall)==null?void 0:C.id;if(!m||!v)return null;let w=`${e}:${v}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let T=this.markWebMcpToolRunning(h),B=(U=(P=h.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?U:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Ei(),toolMessage:h,startedAt:T,completedAt:Date.now()};let S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let L=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,S.signal),M;if(!L)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await L}catch(N){let te=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return te||($=(I=this.callbacks).onError)==null||$.call(I,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(h,Qs(te?"Aborted by cancel()":qu(N)),T),this.webMcpInflightKeys.delete(w),null}return S.signal.aborted?(this.markWebMcpToolComplete(h,Qs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let h={};for(let v of i)h[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,h instanceof Error?h:new Error(String(h)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,Qs("Aborted by cancel()"),v.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,w,T,B,S,L,M,k,C,P,U,_;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(T=e.toolCall)==null?void 0:T.id;if(!t){(S=(B=this.callbacks).onError)==null||S.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let I=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(I)}catch($){(M=(L=this.callbacks).onError)==null||M.call(L,$ instanceof Error?$:new Error(String($)))}finally{this.webMcpInflightKeys.delete(I)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(k=e.toolCall)==null?void 0:k.args,g=c?null:this.client.executeWebMcpToolCall(r,u,d),h="execute",m=a;try{let I;if(c?I=Ei():g?I=await g:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Qs("Aborted by cancel()"),a);return}let $=(P=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?P:r;h="resume",await this.resumeWithToolOutput(t,$,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,I,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(I){let $=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(h==="execute"||$||d.aborted)&&this.markWebMcpToolComplete(e,Qs($||d.aborted?"Aborted by cancel()":qu(I)),a),$||(_=(U=this.callbacks).onError)==null||_.call(U,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-U77QFUR7.js").then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Di(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=ps(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Hi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ia(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Hi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var u,g,h,m,v,w,T,B,S,L,M,k,C,P,U;if(s!==r)return o;let a={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,I=t.approval;a.approval={..._,...I,executionId:I.executionId||_.executionId,toolName:I.toolName||_.toolName,description:I.description||_.description,toolType:(m=I.toolType)!=null?m:_.toolType,reason:(v=I.reason)!=null?v:_.reason,parameters:(w=I.parameters)!=null?w:_.parameters}}let i=(T=t.toolCall)==null?void 0:T.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(S=t.toolCall)==null?void 0:S.id;if(i&&ju(i)&&d&&c&&((L=t.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let _=`${d}:${c}`,I=this.webMcpInflightKeys.has(_),$=this.webMcpResolvedKeys.has(_),N=(M=o.toolCall)==null?void 0:M.name,te=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&N!==void 0&&ju(N)&&((P=o.toolCall)==null?void 0:P.status)==="complete";(I||$||te)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};import{Activity as eh,ArrowDown as th,ArrowUp as nh,ArrowUpRight as rh,Bot as oh,ChevronDown as sh,ChevronUp as ah,ChevronRight as ih,ChevronLeft as lh,Check as ch,Clipboard as dh,ClipboardCopy as ph,Copy as uh,File as mh,FileCode as gh,FileSpreadsheet as fh,FileText as hh,ImagePlus as yh,Loader as bh,LoaderCircle as vh,Mic as wh,Paperclip as xh,RefreshCw as Ch,Search as Ah,Send as Sh,ShieldAlert as Th,ShieldCheck as Mh,ShieldX as Eh,Square as kh,ThumbsDown as Lh,ThumbsUp as Ph,Upload as Ih,Volume2 as Wh,X as Rh,User as Hh,Mail as Bh,Phone as Dh,Calendar as Nh,Clock as Fh,Building as Oh,MapPin as _h,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Vh,Link as Kh,CircleCheck as Gh,CircleX as Qh,TriangleAlert as Xh,Info as Jh,Ban as Yh,Shield as Zh,ArrowLeft as ey,ArrowRight as ty,ExternalLink as ny,Ellipsis as ry,EllipsisVertical as oy,Menu as sy,House as ay,Plus as iy,Minus as ly,Pencil as cy,Trash as dy,Trash2 as py,Save as uy,Download as my,Share as gy,Funnel as fy,Settings as hy,RotateCw as yy,Maximize as by,Minimize as vy,ShoppingCart as wy,ShoppingBag as xy,Package as Cy,Truck as Ay,Tag as Sy,Gift as Ty,Receipt as My,Wallet as Ey,Store as ky,DollarSign as Ly,Percent as Py,Play as Iy,Pause as Wy,VolumeX as Ry,Camera as Hy,Image as By,Film as Dy,Headphones as Ny,MessageCircle as Fy,MessageSquare as Oy,Bell as _y,Heart as $y,Star as Uy,Eye as zy,EyeOff as qy,Bookmark as jy,CalendarDays as Vy,History as Ky,Timer as Gy,Folder as Qy,FolderOpen as Xy,Files as Jy,Sparkles as Yy,Zap as Zy,Sun as eb,Moon as tb,Flag as nb,Monitor as rb,Smartphone as ob}from"lucide";var sb={activity:eh,"arrow-down":th,"arrow-up":nh,"arrow-up-right":rh,bot:oh,"chevron-down":sh,"chevron-up":ah,"chevron-right":ih,"chevron-left":lh,check:ch,clipboard:dh,"clipboard-copy":ph,copy:uh,file:mh,"file-code":gh,"file-spreadsheet":fh,"file-text":hh,"image-plus":yh,loader:bh,"loader-circle":vh,mic:wh,paperclip:xh,"refresh-cw":Ch,search:Ah,send:Sh,"shield-alert":Th,"shield-check":Mh,"shield-x":Eh,square:kh,"thumbs-down":Lh,"thumbs-up":Ph,upload:Ih,"volume-2":Wh,x:Rh,user:Hh,mail:Bh,phone:Dh,calendar:Nh,clock:Fh,building:Oh,"map-pin":_h,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Vh,link:Kh,"circle-check":Gh,"circle-x":Qh,"triangle-alert":Xh,info:Jh,ban:Yh,shield:Zh,"arrow-left":ey,"arrow-right":ty,"external-link":ny,ellipsis:ry,"ellipsis-vertical":oy,menu:sy,house:ay,plus:iy,minus:ly,pencil:cy,trash:dy,"trash-2":py,save:uy,download:my,share:gy,funnel:fy,settings:hy,"rotate-cw":yy,maximize:by,minimize:vy,"shopping-cart":wy,"shopping-bag":xy,package:Cy,truck:Ay,tag:Sy,gift:Ty,receipt:My,wallet:Ey,store:ky,"dollar-sign":Ly,percent:Py,play:Iy,pause:Wy,"volume-x":Ry,camera:Hy,image:By,film:Dy,headphones:Ny,"message-circle":Fy,"message-square":Oy,bell:_y,heart:$y,star:Uy,eye:zy,"eye-off":qy,bookmark:jy,"calendar-days":Vy,history:Ky,timer:Gy,folder:Qy,"folder-open":Xy,files:Jy,sparkles:Yy,zap:Zy,sun:eb,moon:tb,flag:nb,monitor:rb,smartphone:ob},he=(n,e=24,t="currentColor",r=2)=>{let o=sb[n];return o?ab(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ab(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Ra={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function ib(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function lb(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var Xs=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ra.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ra.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ra.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ra.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let u=Fu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Nu(c),h=Pa(c)?URL.createObjectURL(c):null,m={id:ib(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Pa(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.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",r.appendChild(a)}else{let a=b("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 i=lb(e.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Ou(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Vu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Js(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Vu(s)&&Vu(o)?t[r]=Js(s,o):t[r]=o}return t}var jr="min(440px, calc(100vw - 24px))",Gu="440px",cb={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:jr,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)"},Ht={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:cb,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,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 Ku(n,e){if(!(!n&&!e))return n?e?Js(n,e):n:e}function Qu(n){var e,t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k;return n?{...Ht,...n,theme:Ku(Ht.theme,n.theme),darkTheme:Ku(Ht.darkTheme,n.darkTheme),launcher:{...Ht.launcher,...n.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...n.copy},sendButton:{...Ht.sendButton,...n.sendButton},statusIndicator:{...Ht.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...n.voiceRecognition},features:(()=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie;let C=(ne=Ht.features)==null?void 0:ne.artifacts,P=(re=n.features)==null?void 0:re.artifacts,U=(ce=Ht.features)==null?void 0:ce.scrollToBottom,_=(Ce=n.features)==null?void 0:Ce.scrollToBottom,I=(_e=Ht.features)==null?void 0:_e.scrollBehavior,$=(V=n.features)==null?void 0:V.scrollBehavior,N=(X=Ht.features)==null?void 0:X.streamAnimation,te=(Ae=n.features)==null?void 0:Ae.streamAnimation,Ee=(J=Ht.features)==null?void 0:J.askUserQuestion,de=(ie=n.features)==null?void 0:ie.askUserQuestion,Y=C===void 0&&P===void 0?void 0:{...C,...P,layout:{...C==null?void 0:C.layout,...P==null?void 0:P.layout}},Le=U===void 0&&_===void 0?void 0:{...U,..._},Pe=I===void 0&&$===void 0?void 0:{...I,...$},ae=N===void 0&&te===void 0?void 0:{...N,...te},fe=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ht.features,...n.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...Y!==void 0?{artifacts:Y}:{},...ae!==void 0?{streamAnimation:ae}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ht.layout,...n.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(v=Ht.layout)==null?void 0:v.messages)==null?void 0:w.timestamp,...(B=(T=n.layout)==null?void 0:T.messages)==null?void 0:B.timestamp}},slots:{...(S=Ht.layout)==null?void 0:S.slots,...(L=n.layout)==null?void 0:L.slots}},markdown:{...Ht.markdown,...n.markdown,options:{...(M=Ht.markdown)==null?void 0:M.options,...(k=n.markdown)==null?void 0:k.options}},messageActions:{...Ht.messageActions,...n.messageActions}}:Ht}var db={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"}},pb={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"}},ub={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"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:jr,maxWidth:Gu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},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 gs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?gs(n,r):r}function Xu(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=gs(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function mb(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Ju(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Ju(s,o):t[r]=o}return t}function gb(n,e){return e?Ju(n,e):n}function $o(n,e={}){var o,s,a,i,d,c,u,g,h,m,v,w,T;let t={palette:db,semantic:pb,components:ub},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(u=n==null?void 0:n.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(T=n==null?void 0:n.semantic)==null?void 0:T.typography}},components:gb(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=mb(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(S=>S.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function Yu(n){var w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue,Q,it,je,Te,we,Ye,qt,ye,pe,wn,Ct,gn,fr,hr,Ue,E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr;let e=Xu(n),t={};for(let[xe,Dr]of Object.entries(e)){let Gn=xe.replace(/\./g,"-");t[`--persona-${Gn}`]=Dr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(L=t["--persona-semantic-colors-background"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(k=t["--persona-semantic-colors-text"])!=null?k:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(U=t["--persona-semantic-colors-border"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(I=t["--persona-components-voice-recording-indicator"])!=null?I:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=($=t["--persona-components-voice-recording-background"])!=null?$:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(N=t["--persona-components-voice-processing-icon"])!=null?N:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-surface"],t["--persona-approval-border"]=(de=t["--persona-components-approval-requested-border"])!=null?de:t["--persona-border"],t["--persona-approval-text"]=(Y=t["--persona-components-approval-requested-text"])!=null?Y:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Le=t["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Pe=t["--persona-components-approval-approve-background"])!=null?Pe:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ae=t["--persona-components-approval-deny-background"])!=null?ae:t["--persona-container"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ne=t["--persona-components-attachment-image-border"])!=null?ne:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ce=t["--persona-semantic-typography-fontSize"])!=null?ce:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ce=t["--persona-semantic-typography-fontWeight"])!=null?Ce:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(_e=t["--persona-semantic-typography-lineHeight"])!=null?_e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(X=t["--persona-palette-radius-md"])!=null?X:"0.375rem",t["--persona-radius-lg"]=(Ae=t["--persona-palette-radius-lg"])!=null?Ae:"0.5rem",t["--persona-radius-xl"]=(J=t["--persona-palette-radius-xl"])!=null?J:"0.75rem",t["--persona-radius-full"]=(ie=t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-launcher-radius"]=(Je=(Se=t["--persona-components-launcher-borderRadius"])!=null?Se:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-launcher-bg"]=(et=t["--persona-components-launcher-background"])!=null?et:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ft=t["--persona-components-launcher-border"])!=null?ft:t["--persona-border"],t["--persona-button-primary-bg"]=(rt=t["--persona-components-button-primary-background"])!=null?rt:t["--persona-primary"],t["--persona-button-primary-fg"]=(ue=t["--persona-components-button-primary-foreground"])!=null?ue:t["--persona-text-inverse"],t["--persona-button-radius"]=(it=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-panel-radius"]=(Te=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?Te:"0.75rem",t["--persona-panel-border"]=(we=t["--persona-components-panel-border"])!=null?we:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(qt=(Ye=t["--persona-components-panel-shadow"])!=null?Ye:t["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(ye=t["--persona-components-launcher-shadow"])!=null?ye:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(wn=(pe=t["--persona-components-input-borderRadius"])!=null?pe:t["--persona-radius-lg"])!=null?wn:"0.5rem",t["--persona-message-user-radius"]=(gn=(Ct=t["--persona-components-message-user-borderRadius"])!=null?Ct:t["--persona-radius-lg"])!=null?gn:"0.5rem",t["--persona-message-assistant-radius"]=(hr=(fr=t["--persona-components-message-assistant-borderRadius"])!=null?fr:t["--persona-radius-lg"])!=null?hr:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(E=t["--persona-components-header-border"])!=null?E:t["--persona-divider"],t["--persona-header-icon-bg"]=(me=t["--persona-components-header-iconBackground"])!=null?me:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ke=t["--persona-components-header-titleForeground"])!=null?ke:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Re=t["--persona-components-header-subtitleForeground"])!=null?Re:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(tt=t["--persona-components-header-actionIconForeground"])!=null?tt:t["--persona-muted"];let r=(Qe=n.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=n.components)==null?void 0:ht.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(H=t["--persona-components-introCard-borderRadius"])!=null?H:"1rem",t["--persona-intro-card-padding"]=(be=t["--persona-components-introCard-padding"])!=null?be:"1.5rem",t["--persona-intro-card-shadow"]=(gt=(le=o==null?void 0:o.shadow)!=null?le:t["--persona-components-introCard-shadow"])!=null?gt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ke=t["--persona-components-input-background"])!=null?Ke:t["--persona-surface"],t["--persona-input-placeholder"]=(Lt=t["--persona-components-input-placeholder"])!=null?Lt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Et=t["--persona-components-message-user-background"])!=null?Et:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Rt=t["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Qt=t["--persona-components-message-assistant-background"])!=null?Qt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ft=t["--persona-components-message-assistant-text"])!=null?Ft:t["--persona-text"],t["--persona-message-assistant-border"]=(Zt=t["--persona-components-message-assistant-border"])!=null?Zt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(yr=t["--persona-components-message-assistant-shadow"])!=null?yr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(nr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?nr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Vr=(rr=t["--persona-components-scrollToBottom-foreground"])!=null?rr:t["--persona-button-primary-fg"])!=null?Vr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(jt=t["--persona-components-scrollToBottom-border"])!=null?jt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(or=t["--persona-components-scrollToBottom-size"])!=null?or:"40px",t["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Rr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Rr:t["--persona-button-radius"])!=null?Hn:t["--persona-radius-full"])!=null?kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(sr=(Bn=t["--persona-components-scrollToBottom-shadow"])!=null?Bn:t["--persona-palette-shadows-sm"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(br=t["--persona-components-scrollToBottom-padding"])!=null?br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Kr=t["--persona-components-scrollToBottom-gap"])!=null?Kr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Gr=(jn=t["--persona-components-scrollToBottom-fontSize"])!=null?jn:t["--persona-palette-typography-fontSize-sm"])!=null?Gr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(At=t["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",t["--persona-tool-bubble-shadow"]=(vr=t["--persona-components-toolBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(wr=t["--persona-components-reasoningBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Hr=t["--persona-components-composer-shadow"])!=null?Hr:"none",t["--persona-md-inline-code-bg"]=(ar=t["--persona-components-markdown-inlineCode-background"])!=null?ar:t["--persona-container"],t["--persona-md-inline-code-color"]=(yt=t["--persona-components-markdown-inlineCode-foreground"])!=null?yt:t["--persona-text"],t["--persona-md-link-color"]=(xr=(wo=t["--persona-components-markdown-link-foreground"])!=null?wo:t["--persona-accent"])!=null?xr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(xo=t["--persona-components-markdown-codeBlock-background"])!=null?xo:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Ln=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Ko=t["--persona-components-markdown-codeBlock-textColor"])!=null?Ko:"inherit",t["--persona-md-table-header-bg"]=(Qr=t["--persona-components-markdown-table-headerBackground"])!=null?Qr:t["--persona-container"],t["--persona-md-table-border-color"]=(Br=t["--persona-components-markdown-table-borderColor"])!=null?Br:t["--persona-border"],t["--persona-md-hr-color"]=(Xr=t["--persona-components-markdown-hr-color"])!=null?Xr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Jr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Jr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Co=t["--persona-components-markdown-blockquote-background"])!=null?Co:"transparent",t["--persona-md-blockquote-text-color"]=(Ao=t["--persona-components-markdown-blockquote-textColor"])!=null?Ao:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Yr=t["--persona-components-collapsibleWidget-container"])!=null?Yr:t["--persona-surface"],t["--cw-surface"]=(wt=t["--persona-components-collapsibleWidget-surface"])!=null?wt:t["--persona-surface"],t["--cw-border"]=(Dn=t["--persona-components-collapsibleWidget-border"])!=null?Dn:t["--persona-border"],t["--persona-message-border"]=(Nn=t["--persona-components-message-border"])!=null?Nn:t["--persona-border"];let u=n.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=u==null?void 0:u.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let xe=v.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(xn=t["--persona-dropdown-bg"])!=null?xn:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(St=t["--persona-dropdown-border"])!=null?St:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Kn=t["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(v!=null&&v.tab){let xe=v.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(v!=null&&v.pane){let xe=v.pane;if(xe.toolbarBackground){let Dr=(Zr=gs(n,xe.toolbarBackground))!=null?Zr:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Dr}}return t}var fb={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"}}},Zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ni=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},hb=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ni()},yb=n=>hb(n),bb=n=>$o(n),vb=n=>{var t;let e=$o(void 0,{validate:!1});return $o({...n,palette:{...e.palette,colors:{...fb.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ha=n=>{let e=yb(n),t=Zu(n==null?void 0:n.theme),r=Zu(n==null?void 0:n.darkTheme);return e==="dark"?vb(Js(t!=null?t:{},r!=null?r:{})):bb(t)},wb=n=>Yu(n),fs=(n,e)=>{let t=Ha(e),r=wb(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},em=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ni())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ni());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};import{Idiomorph as xb}from"idiomorph";var Ba=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;xb.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var tm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Da={index:-1,draft:""};function nm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Da}}}function rm(n,e){var t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=n.llmContent)==null?void 0:c.length)!=null?u:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(T=(w=n.toolCall)==null?void 0:w.name)!=null?T:"",(L=(S=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:S.length)!=null?L:0,(P=(C=(k=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:k[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?P:"",typeof((U=n.toolCall)==null?void 0:U.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(N=($=(I=n.reasoning)==null?void 0:I.chunks)==null?void 0:$.length)!=null?N:0,(Y=(de=(Ee=(te=n.reasoning)==null?void 0:te.chunks)==null?void 0:Ee[n.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Y:0,(fe=(ae=(Pe=(Le=n.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[n.reasoning.chunks.length-1])==null?void 0:ae.slice(-32))!=null?fe:"",(re=(ne=n.contentParts)==null?void 0:ne.length)!=null?re:0,(ce=n.stopReason)!=null?ce:"",e].join("\0")}function om(){return new Map}function sm(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function am(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function im(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Na(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ir(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function yo(n,e){return Ir(n)-n.scrollTop<=e}function Fa(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Oa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function lm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function cm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function dm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},bn=1e5,bo=bn+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Cb=["pre","code","a","script","style"],_a=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:Ys.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:Ys.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:Ys.speed,duration:(o=n==null?void 0:n.duration)!=null?o:Ys.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:Ys.buffer}},Ab=[{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"}],um=new Map;for(let n of Ab)um.set(n.name,n);var hs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=um.get(n))!=null?r:null},$a=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
19
|
-
`);return s<0?"":n.slice(0,s)}return n},Sb=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Tb=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Fi=/\s/,Mb=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Eb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Fi.test(s[i])){let c=i;for(;c<s.length&&Fi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Fi.test(s[u]);)c.appendChild(Sb(r,s[u],e,t.value)),t.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,n)},kb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Tb(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},Zs=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:Cb).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mb(d,s)||i.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},u=e==="char"?Eb:kb;for(let m of i)u(m,t,c);return o.innerHTML},Ua=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ea=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},pm=new WeakMap,Lb=(n,e)=>{var s;if(!n.styles)return;let t=pm.get(e);if(t||(t=new Set,pm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Oi=new WeakMap,Pb=(n,e)=>{if(!n.onAttach)return;let t=Oi.get(e);if(t||(t=new Map,Oi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},mm=n=>{let e=Oi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},za=(n,e)=>{Lb(n,e),Pb(n,e)};function _i(n,e=bn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var ta=0,vo=null;function $i(n=document){var t;if(ta++,ta===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;vo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,ta=Math.max(0,ta-1),ta===0&&vo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=vo.originalOverflow,o.style.position=vo.originalPosition,o.style.top=vo.originalTop,o.style.width=vo.originalWidth,s.scrollTo(0,vo.scrollY),vo=null}}}var na={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},mn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},ra=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},mr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:na.side,width:(o=e==null?void 0:e.width)!=null?o:na.width,animate:(s=e==null?void 0:e.animate)!=null?s:na.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:na.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:na.maxHeight}};var gr={"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 Ib="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",qa=(n,e={})=>{var T,B,S,L,M,k;let{showClose:t=!0,wrapperClassName:r=Ib,buttonSize:o,iconSize:s="28px"}=e,a=(T=n==null?void 0:n.launcher)!=null?T:{},i=(B=o!=null?o:a.closeButtonSize)!=null?B:"32px",d=b("div",r),c=(S=a.closeButtonTooltipText)!=null?S:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0,g=(M=a.closeButtonIconName)!=null?M:"x",h=(k=a.closeButtonIconText)!=null?k:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Mt("button",{className:Os("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||En.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${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}}),w=he(g,s,"currentColor",1);if(w?(w.style.display="block",v.appendChild(w)):v.textContent=h,d.appendChild(v),u&&c){let C=null,P=()=>{if(C)return;let _=v.ownerDocument,I=_.body;if(!I)return;C=Pr(_,"div","persona-clear-chat-tooltip"),C.textContent=c;let $=Pr(_,"div");$.className="persona-clear-chat-tooltip-arrow",C.appendChild($);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(bo),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",I.appendChild(C)},U=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",P),d.addEventListener("mouseleave",U),v.addEventListener("focus",P),v.addEventListener("blur",U),d._cleanupTooltip=()=>{U(),d.removeEventListener("mouseenter",P),d.removeEventListener("mouseleave",U),v.removeEventListener("focus",P),v.removeEventListener("blur",U)}}return{button:v,wrapper:d}},Wb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ja=(n,e={})=>{var C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe;let{wrapperClassName:t=Wb,buttonSize:r,iconSize:o="20px"}=e,a=(P=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?P:{},i=(U=r!=null?r:a.size)!=null?U:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(I=a.iconColor)!=null?I:"",u=($=a.backgroundColor)!=null?$:"",g=(N=a.borderWidth)!=null?N:"",h=(te=a.borderColor)!=null?te:"",m=(Ee=a.borderRadius)!=null?Ee:"",v=(de=a.paddingX)!=null?de:"",w=(Y=a.paddingY)!=null?Y:"",T=(Le=a.tooltipText)!=null?Le:"Clear chat",B=(Pe=a.showTooltip)!=null?Pe:!0,S=b("div",t),L=!!(g||h),M=Mt("button",{className:Os("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:c||En.actionIconColor,backgroundColor:u||void 0,border:L?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),k=he(d,o,"currentColor",1);if(k&&(k.style.display="block",M.appendChild(k)),S.appendChild(M),B&&T){let ae=null,fe=()=>{if(ae)return;let re=M.ownerDocument,ce=re.body;if(!ce)return;ae=Pr(re,"div","persona-clear-chat-tooltip"),ae.textContent=T;let Ce=Pr(re,"div");Ce.className="persona-clear-chat-tooltip-arrow",ae.appendChild(Ce);let _e=M.getBoundingClientRect();ae.style.position="fixed",ae.style.zIndex=String(bo),ae.style.left=`${_e.left+_e.width/2}px`,ae.style.top=`${_e.top-8}px`,ae.style.transform="translate(-50%, -100%)",ce.appendChild(ae)},ne=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};S.addEventListener("mouseenter",fe),S.addEventListener("mouseleave",ne),M.addEventListener("focus",fe),M.addEventListener("blur",ne),S._cleanupTooltip=()=>{ne(),S.removeEventListener("mouseenter",fe),S.removeEventListener("mouseleave",ne),M.removeEventListener("focus",fe),M.removeEventListener("blur",ne)}}return{button:M,wrapper:S}};var En={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Uo=n=>{var k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe;let{config:e,showClose:t=!0}=n,r=Mt("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)))"}}),o=(k=e==null?void 0:e.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(P=o.closeButtonPlacement)!=null?P:"inline",i=(U=o.headerIconHidden)!=null?U:!1,d=o.headerIconName,c=Mt("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(!i)if(d){let ne=parseFloat(s)||24,re=he(d,ne*.6,"currentColor",1);re?c.replaceChildren(re):c.textContent=(I=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?I:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let ne=b("img");ne.src=e.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=s,ne.style.width=s,c.replaceChildren(ne)}else c.textContent=(te=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?te:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=e==null?void 0:e.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:En.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Le=(Y=e==null?void 0:e.launcher)==null?void 0:Y.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:En.subtitleColor}});u.append(g,h),i?r.append(u):r.append(c,u);let m=(Pe=o.clearChat)!=null?Pe:{},v=(ae=m.enabled)!=null?ae:!0,w=(fe=m.placement)!=null?fe:"inline",T=null,B=null;if(v){let re=ja(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=re.button,B=re.wrapper,w==="top-right"&&(B.style.right="48px"),w==="inline"&&r.appendChild(B)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:L,wrapper:M}=qa(e,{showClose:t,wrapperClassName:S});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:L,closeButtonWrapper:M,clearChatButton:T,clearChatButtonWrapper:B}},oa=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function ys(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("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(bo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let T=he(m.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,v.appendChild(w),v.addEventListener("click",T=>{T.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?c():u()}function h(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:g,destroy:h}}function vn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=he(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,g]of Object.entries(i))d.setAttribute(u,g);return d}function Ui(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=b("button",c);if(u.type="button",u.setAttribute("aria-label",t),e){let h=he(e,s!=null?s:14,"currentColor",2);h&&u.appendChild(h)}let g=b("span");if(g.textContent=t,u.appendChild(g),i&&u.addEventListener("click",i),d)for(let[h,m]of Object.entries(d))u.setAttribute(h,m);return u}function gm(n){var m,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=b("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let g=he(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var w,T;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=ys({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let T=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{u.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var Rb=n=>{var r;let e=Uo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function Hb(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=ys({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var Bb=n=>{var S,L,M,k,C,P,U,_,I;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=gm({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=En.titleColor,u=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=En.titleColor,u.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(u),Hb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let N=o.onTitleClick;c.addEventListener("click",te=>{te.target.closest("button")||N()}),c.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),N())})}let $=o==null?void 0:o.titleRowHover;$&&(c.style.borderRadius=(P=$.borderRadius)!=null?P:"10px",c.style.padding=(U=$.padding)!=null?U:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var N,te;c.style.backgroundColor=(N=$.background)!=null?N:"",c.style.borderColor=(te=$.border)!=null?te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let g=(_=a.closeButtonSize)!=null?_:"32px",h=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||En.actionIconColor;let v=(I=a.closeButtonIconName)!=null?I:"x",w=he(v,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),i.appendChild(h);let T=b("div");T.style.display="none";let B=b("span");return B.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:B,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},fm={default:Rb,minimal:Bb},Db=n=>{var e;return(e=fm[n])!=null?e:fm.default},Va=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=b("div");u.style.display="none";let g=b("span"),h=b("span"),m=b("button");m.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Db(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ka=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Ga=n=>{var k,C,P,U,_,I,$,N,te,Ee,de,Y;let e=(k=n==null?void 0:n.sendButton)!=null?k:{},t=(C=e.useIcon)!=null?C:!1,r=(P=e.iconText)!=null?P:"\u2191",o=e.iconName,s=(U=e.stopIconName)!=null?U:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(I=e.stopTooltipText)!=null?I:"Stop generating",d=(N=($=n==null?void 0:n.copy)==null?void 0:$.sendButtonLabel)!=null?N:"Send",c=(Ee=(te=n==null?void 0:n.copy)==null?void 0:te.stopButtonLabel)!=null?Ee:"Stop",u=(de=e.showTooltip)!=null?de:!1,g=(Y=e.size)!=null?Y:"40px",h=e.backgroundColor,m=e.textColor,v=b("div","persona-send-button-wrapper"),w=Mt("button",{className:Os("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),T=null,B=null;if(t){let Le=parseFloat(g)||24,Pe=(m==null?void 0:m.trim())||"currentColor";o?(T=he(o,Le,Pe,2),T?w.appendChild(T):w.textContent=r):w.textContent=r,B=he(s,Le,Pe,2)}else w.textContent=d;let S=null;u&&a&&(S=b("div","persona-send-button-tooltip"),S.textContent=a,v.appendChild(S)),w.setAttribute("aria-label",a),v.appendChild(w);let L="send";return{button:w,wrapper:v,setMode:Le=>{if(Le===L)return;L=Le;let Pe=Le==="stop"?i:a;if(w.setAttribute("aria-label",Pe),S&&(S.textContent=Pe),t){if(T&&B){let ae=Le==="stop"?B:T;w.replaceChildren(ae)}}else w.textContent=Le==="stop"?c:d}}},Qa=n=>{var S,L,M,k,C,P,U,_,I,$,N,te;let e=(S=n==null?void 0:n.voiceRecognition)!=null?S:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((L=e.provider)==null?void 0:L.type)==="runtype";if(!(r||o))return null;let a=(k=(M=n==null?void 0:n.sendButton)==null?void 0:M.size)!=null?k:"40px",i=(C=e.iconName)!=null?C:"mic",d=(P=e.iconSize)!=null?P:a,c=parseFloat(d)||24,u=(_=e.backgroundColor)!=null?_:(U=n==null?void 0:n.sendButton)==null?void 0:U.backgroundColor,g=($=e.iconColor)!=null?$:(I=n==null?void 0:n.sendButton)==null?void 0:I.textColor,h=b("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=he(i,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let T=(N=e.tooltipText)!=null?N:"Start voice recognition";if(((te=e.showTooltip)!=null?te:!1)&&T){let Ee=b("div","persona-send-button-tooltip");Ee.textContent=T,h.appendChild(Ee)}return{button:m,wrapper:h}},Xa=n=>{var v,w,T,B,S,L,M,k;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(T=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?T:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((B=e.allowedTypes)!=null?B:qr).join(","),o.multiple=((S=e.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(L=e.buttonIconName)!=null?L:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),u=Mt("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":(M=e.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=he(s,d,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(u);let h=(k=e.buttonTooltipText)!=null?k:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},Ja=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Ya=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Za=n=>{var v,w,T,B,S,L;let{config:e}=n,t=Mt("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"}}),r=Ya(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ka(e);a();let i=Ga(e),d=Qa(e),c=Xa(e),u=Ja(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(h,m),o.append(g),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:u,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}};var hm=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=he("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},ym=n=>{var v,w,T,B,S,L;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ya();r.style.display="none";let o=Ja(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ka(e);s.style.maxHeight="100px",a();let i=Ga(e),d=Qa(e),c=Xa(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(i.wrapper),u.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(g,s,h),c&&t.append(c.previewsContainer),t.append(u,r,o);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:i.setMode}};var bm=n=>{var u,g,h,m,v,w,T,B,S,L,M,k,C,P,U,_,I;let e=(g=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?g:!0,t=mn(n);if(ra(n)){let $=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},N=b("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=$.expandedSize)!=null?v:"anchored",N.style.zIndex=String((T=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?T:bn);let te=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",N.appendChild(te);let Ee=b("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(B=$.expandedSize)!=null?B:"anchored",Ee.style.zIndex=String((L=(S=n==null?void 0:n.launcher)==null?void 0:S.zIndex)!=null?L:bn),{wrapper:N,panel:te,pillRoot:Ee}}if(t){let $=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(N),{wrapper:$,panel:N}}if(!e){let $=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(k=(M=n==null?void 0:n.launcher)==null?void 0:M.width)!=null?k:"100%";return $.style.width=te,N.style.width="100%",$.appendChild(N),{wrapper:$,panel:N}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&gr[o.position]?gr[o.position]:gr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((U=(P=n==null?void 0:n.launcher)==null?void 0:P.zIndex)!=null?U:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(I=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?I:n==null?void 0:n.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Nb=(n,e)=>{var M,k,C,P,U,_,I,$,N;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=qa(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(k=(M=n==null?void 0:n.launcher)==null?void 0:M.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let te=ja(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=te.button,i=te.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let u=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(U=(P=n==null?void 0:n.copy)==null?void 0:P.welcomeTitle)!=null?U:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(_=n==null?void 0:n.copy)==null?void 0:_.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),h=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=b("div","persona-flex persona-flex-col persona-gap-3"),v=($=n==null?void 0:n.layout)==null?void 0:$.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((N=n==null?void 0:n.copy)==null?void 0:N.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let T=Mt("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=ym({config:n}),{root:S,textNode:L}=hm();return t.append(d,o,c,T),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:T,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:u,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,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:S,peekTextNode:L}},vm=(n,e=!0)=>{var T,B,S,L,M,k,C,P,U;if(ra(n))return Nb(n,e);let t=Mt("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"}}),r=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=((B=n==null?void 0:n.layout)==null?void 0:B.showHeader)!==!1,s=r?Va(n,r,{showClose:e}):Uo({config:n,showClose:e}),a=Mt("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 i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(L=(S=n==null?void 0:n.copy)==null?void 0:S.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(M=n==null?void 0:n.copy)==null?void 0:M.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:mn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=b("div","persona-flex persona-flex-col persona-gap-3"),g=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((P=n==null?void 0:n.copy)==null?void 0:P.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=Za({config:n}),v=((U=n==null?void 0:n.layout)==null?void 0:U.showFooter)!==!1;o?oa(t,s,n):(s.header.style.display="none",oa(t,s,n)),t.append(a);let w=Mt("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||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:u,composerOverlay:w,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var zi=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:o}var Jr=t=>({isError:!0,content:[{type:"text",text:t}]}),Pd=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Id=t=>Jo(t)||t===Hn,pa=class{constructor(e={},n){this.config=e;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 Qr(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Jo(n.name)||n.name===Hn&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.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"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.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?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Gr(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||$i().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Oi(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 e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=rr.isSupported()?new rr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return $i().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.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(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=or(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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!bg(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Gr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=e,f={id:a??(n==="user"?ia():n==="assistant"?nr():`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(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,x={id:p??(r==="user"?ia():r==="assistant"?nr():`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(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=e,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 sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ia(),s=nr();this.activeAssistantMessageId=null;let a={id:r,role:"user",content:o||la,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let c=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!c){let u=Ui(d,this.config.errorMessage);if(u){let w={id:s,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(w)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=nr();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:e},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=Ui(r,this.config.errorMessage);if(a){let l={id:e,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(e,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(e,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 e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.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(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,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:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):c=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.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-${e.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(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(c=>c.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.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=e.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(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.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],x=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: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(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});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(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Hn?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,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=`${e}:${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===Hn)return{dedupeKey:u,resumeKey:f,output:Bi(),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(W){let T=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));return T||this.callbacks.onError?.(W instanceof Error?W:new Error(String(W))),this.markWebMcpToolComplete(p,Jr(T?"Aborted by cancel()":Pd(W)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,Jr("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,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(e,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===Hn?{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,Jr("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(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.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(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Hn,c=e.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Bi():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,Jr("Aborted by cancel()"),a);return}let x=e.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,v,a,f,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(e,Jr(x||p.aborted?"Aborted by cancel()":Pd(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(e,n,o,r){let s=await this.client.resumeFlow(e,{[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 e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Eo(this.config.features?.artifacts,e.artifactType),r=Ys(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.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})}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(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,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(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.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(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Ui(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=nr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];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 e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){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(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.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=_i(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return da(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=_i(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),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&&Id(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&&Id(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(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].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)})}};import{Activity as vg,ArrowDown as wg,ArrowUp as xg,ArrowUpRight as Cg,Bot as Ag,ChevronDown as Sg,ChevronUp as Tg,ChevronRight as Mg,ChevronLeft as Eg,Check as kg,Clipboard as Lg,ClipboardCopy as Pg,CodeXml as Ig,Copy as Rg,File as Wg,FileCode as Bg,FileSpreadsheet as Hg,FileText as Dg,ImagePlus as Ng,Loader as Fg,LoaderCircle as Og,Mic as _g,Paperclip as $g,RefreshCw as Ug,Search as zg,Send as jg,ShieldAlert as qg,ShieldCheck as Vg,ShieldX as Kg,Square as Gg,ThumbsDown as Xg,ThumbsUp as Qg,Upload as Jg,Volume2 as Yg,X as Zg,User as em,Mail as tm,Phone as nm,Calendar as om,Clock as rm,Building as sm,MapPin as am,Lock as im,Key as lm,CreditCard as cm,AtSign as dm,Hash as pm,Globe as um,Link as fm,CircleCheck as gm,CircleX as mm,TriangleAlert as hm,Info as ym,Ban as bm,Shield as vm,ArrowLeft as wm,ArrowRight as xm,ExternalLink as Cm,Ellipsis as Am,EllipsisVertical as Sm,Menu as Tm,House as Mm,Plus as Em,Minus as km,Pencil as Lm,Trash as Pm,Trash2 as Im,Save as Rm,Download as Wm,Share as Bm,Funnel as Hm,Settings as Dm,RotateCw as Nm,Maximize as Fm,Minimize as Om,ShoppingCart as _m,ShoppingBag as $m,Package as Um,Truck as zm,Tag as jm,Gift as qm,Receipt as Vm,Wallet as Km,Store as Gm,DollarSign as Xm,Percent as Qm,Play as Jm,Pause as Ym,VolumeX as Zm,Camera as eh,Image as th,Film as nh,Headphones as oh,MessageCircle as rh,MessageSquare as sh,Bell as ah,Heart as ih,Star as lh,Eye as ch,EyeOff as dh,Bookmark as ph,CalendarDays as uh,History as fh,Timer as gh,Folder as mh,FolderOpen as hh,Files as yh,Sparkles as bh,Zap as vh,Sun as wh,Moon as xh,Flag as Ch,Monitor as Ah,Smartphone as Sh}from"lucide";var Th={activity:vg,"arrow-down":wg,"arrow-up":xg,"arrow-up-right":Cg,bot:Ag,"chevron-down":Sg,"chevron-up":Tg,"chevron-right":Mg,"chevron-left":Eg,check:kg,clipboard:Lg,"clipboard-copy":Pg,"code-xml":Ig,copy:Rg,file:Wg,"file-code":Bg,"file-spreadsheet":Hg,"file-text":Dg,"image-plus":Ng,loader:Fg,"loader-circle":Og,mic:_g,paperclip:$g,"refresh-cw":Ug,search:zg,send:jg,"shield-alert":qg,"shield-check":Vg,"shield-x":Kg,square:Gg,"thumbs-down":Xg,"thumbs-up":Qg,upload:Jg,"volume-2":Yg,x:Zg,user:em,mail:tm,phone:nm,calendar:om,clock:rm,building:sm,"map-pin":am,lock:im,key:lm,"credit-card":cm,"at-sign":dm,hash:pm,globe:um,link:fm,"circle-check":gm,"circle-x":mm,"triangle-alert":hm,info:ym,ban:bm,shield:vm,"arrow-left":wm,"arrow-right":xm,"external-link":Cm,ellipsis:Am,"ellipsis-vertical":Sm,menu:Tm,house:Mm,plus:Em,minus:km,pencil:Lm,trash:Pm,"trash-2":Im,save:Rm,download:Wm,share:Bm,funnel:Hm,settings:Dm,"rotate-cw":Nm,maximize:Fm,minimize:Om,"shopping-cart":_m,"shopping-bag":$m,package:Um,truck:zm,tag:jm,gift:qm,receipt:Vm,wallet:Km,store:Gm,"dollar-sign":Xm,percent:Qm,play:Jm,pause:Ym,"volume-x":Zm,camera:eh,image:th,film:nh,headphones:oh,"message-circle":rh,"message-square":sh,bell:ah,heart:ih,star:lh,eye:ch,"eye-off":dh,bookmark:ph,"calendar-days":uh,history:fh,timer:gh,folder:mh,"folder-open":hh,files:yh,sparkles:bh,zap:vh,sun:wh,moon:xh,flag:Ch,monitor:Ah,smartphone:Sh},ae=(t,e=24,n="currentColor",o=2)=>{let r=Th[t];return r?Mh(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mh(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var ua={allowedTypes:Dn,maxFileSize:10*1024*1024,maxFiles:4};function Eh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function kh(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var Yr=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??ua.allowedTypes,maxFileSize:e.maxFileSize??ua.maxFileSize,maxFiles:e.maxFiles??ua.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ua.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Sd(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 Ad(n),s=ca(n)?URL.createObjectURL(n):null,a={id:Eh(),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(e){let n=this.attachments.findIndex(s=>s.id===e);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="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=ca(e.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let a=m("img");a.src=e.previewUrl,a.alt=e.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=m("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=kh(e.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Td(e.file.type,e.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=m("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(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};var Rd=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Zr(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];Rd(s)&&Rd(r)?n[o]=Zr(s,r):n[o]=r}return n}var Nn="min(440px, calc(100vw - 24px))",Bd="440px",Lh={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:Nn,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)"},dt={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:Lh,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 Wd(t,e){if(!(!t&&!e))return t?e?Zr(t,e):t:e}function Hd(t){return t?{...dt,...t,theme:Wd(dt.theme,t.theme),darkTheme:Wd(dt.darkTheme,t.darkTheme),launcher:{...dt.launcher,...t.launcher,dock:{...dt.launcher?.dock,...t.launcher?.dock},clearChat:{...dt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...dt.copy,...t.copy},sendButton:{...dt.sendButton,...t.sendButton},statusIndicator:{...dt.statusIndicator,...t.statusIndicator},voiceRecognition:{...dt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=dt.features?.artifacts,n=t.features?.artifacts,o=dt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=dt.features?.scrollBehavior,a=t.features?.scrollBehavior,l=dt.features?.streamAnimation,p=t.features?.streamAnimation,d=dt.features?.askUserQuestion,c=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.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},x=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...dt.features,...t.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...x!==void 0?{askUserQuestion:x}:{}}})(),suggestionChips:t.suggestionChips??dt.suggestionChips,suggestionChipsConfig:{...dt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...dt.layout,...t.layout,header:{...dt.layout?.header,...t.layout?.header},messages:{...dt.layout?.messages,...t.layout?.messages,avatar:{...dt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...dt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...dt.layout?.slots,...t.layout?.slots}},markdown:{...dt.markdown,...t.markdown,options:{...dt.markdown?.options,...t.markdown?.options}},messageActions:{...dt.messageActions,...t.messageActions}}:dt}var fa="16px",ga="transparent",Ph={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"}},Ih={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"}},Rh={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"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Nn,maxWidth:Bd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:fa,canvasBackground:ga},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Kt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Kt(t,o):o}function Dd(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Kt(t,a);p!==void 0&&(e[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(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Wh(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Nd(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Nd(s,r):n[o]=r}return n}function Bh(t,e){return e?Nd(t,e):t}function Ro(t,e={}){let n={palette:Ph,semantic:Ih,components:Rh},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:Bh(n.components,t?.components)};if(e.validate!==!1){let r=Wh(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function Fd(t){let e=Dd(t),n={};for(let[C,j]of Object.entries(e)){let J=C.replace(/\./g,"-");n[`--persona-${J}`]=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-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"]??fa,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ga,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=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=t.components?.introCard;n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??n["--persona-surface"],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"]=r?.shadow??n["--persona-components-introCard-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",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 s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let l=n["--persona-components-markdown-heading-h2-fontSize"];l&&(n["--persona-md-h2-size"]=l);let p=n["--persona-components-markdown-heading-h2-fontWeight"];p&&(n["--persona-md-h2-weight"]=p);let d=n["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(n["--persona-md-prose-font-family"]=d),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=t.components,u=c?.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let w=c?.labelButton;w&&(w.background&&(n["--persona-label-btn-bg"]=w.background),w.border&&(n["--persona-label-btn-border"]=w.border),w.color&&(n["--persona-label-btn-color"]=w.color),w.padding&&(n["--persona-label-btn-padding"]=w.padding),w.borderRadius&&(n["--persona-label-btn-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-label-btn-hover-bg"]=w.hoverBackground),w.fontSize&&(n["--persona-label-btn-font-size"]=w.fontSize),w.gap&&(n["--persona-label-btn-gap"]=w.gap));let f=c?.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=c?.artifact;if(v?.toolbar){let C=v.toolbar;C.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=C.iconHoverColor),C.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=C.iconHoverBackground),C.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=C.iconPadding),C.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=C.iconBorderRadius),C.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=C.iconBorder),C.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=C.toggleGroupGap),C.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=C.toggleBorderRadius),C.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=C.toggleGroupPadding),C.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=C.toggleGroupBorder),C.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=C.toggleGroupBorderRadius),C.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Kt(t,C.toggleGroupBackground)??C.toggleGroupBackground),C.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=C.copyBackground),C.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=C.copyBorder),C.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=C.copyColor),C.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=C.copyBorderRadius),C.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=C.copyPadding),C.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=C.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??C.copyMenuBackground),C.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=C.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??C.copyMenuBorder),C.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=C.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??C.copyMenuShadow),C.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=C.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??C.copyMenuBorderRadius),C.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=C.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??C.copyMenuItemHoverBackground),C.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=C.iconBackground),C.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=C.toolbarBorder)}if(v?.tab){let C=v.tab;C.background&&(n["--persona-artifact-tab-bg"]=C.background),C.activeBackground&&(n["--persona-artifact-tab-active-bg"]=C.activeBackground),C.activeBorder&&(n["--persona-artifact-tab-active-border"]=C.activeBorder),C.borderRadius&&(n["--persona-artifact-tab-radius"]=C.borderRadius),C.textColor&&(n["--persona-artifact-tab-color"]=C.textColor),C.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=C.hoverBackground),C.listBackground&&(n["--persona-artifact-tab-list-bg"]=C.listBackground),C.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=C.listBorderColor),C.listPadding&&(n["--persona-artifact-tab-list-padding"]=C.listPadding)}if(v?.pane){let C=v.pane;if(C.toolbarBackground){let j=Kt(t,C.toolbarBackground)??C.toolbarBackground;n["--persona-artifact-toolbar-bg"]=j}}if(v?.card){let C=v.card;C.background&&(n["--persona-artifact-card-bg"]=C.background),C.border&&(n["--persona-artifact-card-border"]=C.border),C.borderRadius&&(n["--persona-artifact-card-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=C.hoverBackground),C.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=C.hoverBorderColor)}if(v?.inline){let C=v.inline;C.background&&(n["--persona-artifact-inline-bg"]=Kt(t,C.background)??C.background),C.border&&(n["--persona-artifact-inline-border"]=C.border),C.borderRadius&&(n["--persona-artifact-inline-radius"]=C.borderRadius),C.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Kt(t,C.chromeBackground)??C.chromeBackground),C.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Kt(t,C.chromeBorder)??C.chromeBorder),C.titleColor&&(n["--persona-artifact-inline-title-color"]=Kt(t,C.titleColor)??C.titleColor),C.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Kt(t,C.mutedColor)??C.mutedColor),C.frameHeight&&(n["--persona-artifact-inline-frame-height"]=C.frameHeight)}let x=c?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=Kt(t,x.background)??x.background));let P=n["--persona-surface"],W=n["--persona-container"],T=n["--persona-palette-colors-gray-100"]??"#f3f4f6",I=n["--persona-palette-colors-gray-200"]??"#e5e7eb",H=n["--persona-palette-colors-gray-300"]??"#d1d5db",q=!W||W===P,U=q?T:W,$=q?I:W;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"]??$,q&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??H),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 Hh={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"}}},Od=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},zi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Dh=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":zi()},_d=t=>Dh(t),Nh=t=>Ro(t),Fh=t=>{let e=Ro(void 0,{validate:!1});return Ro({...t,palette:{...e.palette,colors:{...Hh.colors,...t?.palette?.colors}}},{validate:!1})},sr=t=>{let e=_d(t),n=Od(t?.theme),o=Od(t?.darkTheme);return e==="dark"?Fh(Zr(n??{},o??{})):Nh(n)},Oh=t=>Fd(t),es=(t,e)=>{let n=sr(e),o=Oh(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",_d(e))},ma=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(zi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(zi());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};function Tn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function $d(t){let e=Tn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function ha(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
19
|
+
`);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
|
|
20
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ts(t){let e=$d(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function to(t){switch(ts(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=$d(t.path);return e?e.toUpperCase():"File"}}}function Ud(t){let e=t.markdown??"";return t.file?{filename:Tn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:ha(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var ji="http://www.w3.org/2000/svg";function zd(t){let e=document.createElementNS(ji,"svg");e.setAttribute("class",ko("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(ji,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(ji,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var no=(t,e,n)=>{let o=n;for(let r of e){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function jd(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),no(t,e,0)}var qi="persona-artifact-status-label",qd="persona-artifact-status-detail",Vd="data-artifact-status-label",Vi=new Map,Kd=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function ar(t){t&&Vi.delete(t)}function _h(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?to(e):t.artifactType==="component"?"Component":"Document"}function ir(t,e,n){let o=_h(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Vi.get(a);t.status!=="complete"&&l===void 0&&(l=Kd(),Vi.set(a,l));let p=l===void 0?0:Math.max(0,Kd()-l),d=t.artifactType==="component",c=!d&&typeof t.markdown=="string"?t.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
|
|
21
|
+
`).length,f=t.artifactType==="markdown"?t.file:void 0,v={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,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 $h(t){t.className=qi,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function Wo(t,e,n){let o=t.querySelector(`:scope > .${qi}`);o||(o=m("span",qi),t.appendChild(o)),o.getAttribute(Vd)!==e.label&&($h(o),jd(o,e.label,n),o.setAttribute(Vd,e.label));let r=t.querySelector(`:scope > .${qd}`),s=e.detail;s?(r||(r=m("span",qd),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Uh={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"},zh=15e4,ya={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 jh(t,e){let n=(t||"").trim().toLowerCase();if(n&&ya[n])return ya[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(ya[r])return ya[r]}}return null}function ba(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);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(t.length),n}var qh=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"]),Vh=[{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:t=>qh.has(t)?"keyword":"plain"}];function Gd(t){return ba(t,Vh)}var Kh=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function Gh(t){let e=ba(t,Kh);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var Xh=[{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 Xd(t){let e=ba(t,Xh),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[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 e}var Qh=[{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 Jh(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,p=t.slice(r,l);for(let c of ba(p,Qh))e.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(t.slice(r)),f=w?r+w.index:o,v=t.slice(r,f),x=c==="script"?Gd(v):Xd(v);for(let P of x)e.push(P);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function Yh(t,e){switch(e){case"html":return Jh(t);case"css":return Xd(t);case"js":return Gd(t);case"json":return Gh(t)}}function Zh(t){let e=Yc(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=Uh[r];if(a){let l=m("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
|
|
22
|
+
`);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
|
|
23
|
+
`)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Qd(t,e,n){let o=t.length<=zh?jh(e,n):null,r=o?Yh(t,o):[{type:"plain",value:t}];return Zh(r)}var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,oo=Ut+1;function lr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,a=m("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(oo)):(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 e){if(f.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",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let P=ae(f.icon,16,"currentColor",1.5);P&&v.appendChild(P)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",P=>{P.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 Wt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(e,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 Bo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=t,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),e){let w=ae(e,s??14,"currentColor",2);w&&c.appendChild(w)}let u=m("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 va(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=m("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 e){let u;c.icon?u=Wt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("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 Jd(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=t,d=m("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",e);let c=m("span","persona-combo-btn-label");c.textContent=e,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=lr({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 wa="persona-artifact-custom-action-btn";function cr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+wa+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+wa+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=m("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Bo({icon:t.icon,label:t.label,className:wa+(n?" persona-artifact-doc-copy-btn":"")}):o=Wt({icon:t.icon,label:t.label,className:wa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function ns(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function Yd(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Tn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=n?to(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let w=document.createElement("div");w.className="persona-truncate persona-text-sm persona-font-medium",w.style.color="var(--persona-text, #1f2937)",w.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let v=e?.config?.features?.artifacts,x={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},P=ir(x,v,"card");Wo(f,P,v)}else s&&ar(s),f.textContent=p;if(u.append(w,f),d.append(c,u),a==="complete"){let v=e?.config?.features?.artifacts?.cardActions;if(v&&v.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let W of v)try{if(W.visible===void 0||W.visible(P)){let T=cr(W);T.setAttribute("data-artifact-custom-action",W.id),T.className=`${T.className} persona-flex-shrink-0`,d.append(T)}}catch{}}let x=Bo({label:"Download",className:"persona-flex-shrink-0"});x.title=`Download ${r}`,x.setAttribute("data-download-artifact",s),d.append(x)}return d}var xa=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>Yd(t,e)});if(l)return l}return Yd(t,e)};var ro=new WeakMap;function Ki(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=ro.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function op(t){return ro.has(t)}function ey(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete";if(t.artifactType==="component"){let s=t.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:a}}let r=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...r?{file:r}:{}}}function Zd(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Tn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?to(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function ty(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var ep=180,ny=240,oy=.8,ry=300,sy=500,ay="cubic-bezier(0.2, 0, 0, 1)",tp=240,iy=.35;function ly(t,e,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(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:ep,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let W of a)W.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let d=Math.abs(e-p),c=Math.round(Math.min(sy,Math.max(ry,ny+d*oy))),u=Math.round(c*iy),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:tp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:ay});t.style.height=`${p}px`;let x=!1,P=()=>{x||(x=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+tp)+120)},ep)}function cy(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var os="--persona-artifact-inline-body-height";function dy(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,d,c,u=e?.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=e?.transition==="none"?"none":"auto",f=e?.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 np(t,e){let n=ey(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=cy(o),p=o?.inlineActions??[],d=dy(o),c=d.completeDisplay==="card",u=null,w=n,f=m("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=Y=>xa(ty(Y),e),x=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(os),f.replaceChildren(v(Y)),ro.set(f,le=>{f.replaceChildren(v(le))})};if(c&&n.status==="complete")return x(n),f;let P=Ca(n,{config:e.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),W=m("div","persona-artifact-inline-body");W.appendChild(P.el);let T=Y=>{let le=Y.status!=="complete",Z=le?d.streamingHeight:d.completeHeight,be=typeof Z=="number";be?f.style.setProperty(os,`${Z}px`):f.style.removeProperty(os);let ve=!!P.el.querySelector(".persona-code-pre"),fe=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");W.classList.toggle("persona-artifact-content-flush",ve),W.classList.toggle("persona-artifact-inline-body--sized",be&&fe),W.classList.toggle("persona-artifact-inline-body--cap",!le&&!fe&&typeof d.completeHeight=="number")},I=n.status,H=(Y,le)=>{I!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(os,`${d.completeHeight}px`):f.style.removeProperty(os),sp(W,le?.suppressTransition?"none":d.transition,Y.id,()=>{P.update(Y),T(Y)})):P.update(Y),T(Y),I=Y.status};T(n);let q=d.overflow==="clip"&&a&&!!n.id;if(q&&(W.setAttribute("data-expand-artifact-inline",n.id),W.setAttribute("role","button"),W.setAttribute("tabindex","0"),W.classList.add("persona-cursor-pointer"),W.setAttribute("aria-label",`Open ${Zd(n).title} in panel`)),!r)return f.appendChild(W),ro.set(f,H),f;let U=m("div","persona-artifact-inline-chrome");U.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let $=m("div","persona-artifact-inline-chrome-lead"),C=m("span","persona-flex persona-items-center persona-flex-shrink-0"),j=ae("file-text",16,"currentColor",2);j&&C.appendChild(j);let J=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");$.append(C,J,D);let _=m("div","persona-artifact-inline-chrome-actions"),ce=m("span","persona-flex persona-items-center persona-gap-1"),he=()=>u??d.viewMode,Me=l?va({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:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let le=Y==="source"?"source":"rendered";le!==he()&&(u=le,P.update(w),T(w))}}):null,Ce=s?Wt({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 te=a?Wt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),_.appendChild(ce),Me&&_.appendChild(Me.element),Ce&&_.appendChild(Ce),te&&_.appendChild(te),U.append($,_),f.append(U,W);let ge=Y=>{let{title:le,typeLabel:Z}=Zd(Y);J.textContent=le,J.title=le,q&&W.setAttribute("aria-label",`Open ${le} in panel`);let be=Y.status!=="complete";if(be){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ve=ir(Y,o,"inline-chrome");Wo(D,ve,o)}else ar(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(Ce&&Ce.classList.toggle("persona-hidden",be),Me){let ve=Y.artifactType==="markdown"?Y.file:void 0,fe=!1;if(!be&&ve&&d.viewMode!=="source"){let Te=ts(ve);Te==="markdown"?fe=!0:(Te==="html"||Te==="svg")&&(fe=o?.filePreview?.enabled!==!1)}Me.element.classList.toggle("persona-hidden",!fe),Me.setSelected(he())}if(ce.replaceChildren(),!be&&p.length>0){let ve=ns(Y);if(ve)for(let fe of p)try{if(fe.visible===void 0||fe.visible(ve)){let Te=cr(fe,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",fe.id),Te.classList.add("persona-flex-shrink-0"),ce.appendChild(Te)}}catch{}}};return ge(n),ro.set(f,(Y,le)=>{if(c&&I!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;I="complete";let be=Y,ve=!1,fe=Te=>{be=Te,ve=!0};ro.set(f,fe),ly(f,Z,{swap:()=>{x(be),ve=!1,ro.set(f,fe)},onSettled:()=>{ve?x(be):ro.set(f,Te=>{f.replaceChildren(v(Te))})}});return}(Y.status!=="complete"||Y.id!==w.id)&&(u=null),w=Y,H(Y,le),ge(Y)}),f}var rp=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>np(t,e)});if(l)return l}return np(t,e)};var Gi=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Fn=new Gi;Fn.register("PersonaArtifactCard",xa,{bubbleChrome:!1});Fn.register("PersonaArtifactInline",rp,{bubbleChrome:!1});function rs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?ha(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Xi=!1;function py(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function sp(t,e,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(e!=="auto"||!t||typeof r!="function"||Xi||s){o();return}Xi=!0;let a=py(n);t.style.setProperty("view-transition-name",a);let l=()=>{Xi=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var uy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",fy="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function gy(t){let e=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function my(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var hy=220;function yy(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function by(t){return`
|
|
24
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(t)+";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 vy(t,e,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(zd());let s=null;return n.label!==!1&&(s=m("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 wy(t,e,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(I=>clearTimeout(I)),d.clear()},u=(I,H)=>{let q=setTimeout(()=>{d.delete(q),I()},H);d.add(q)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let I=vy(r,s,o);a=I.el,t.appendChild(a),l=Date.now(),o.label!==!1&&u(I.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,hy))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",W):e.removeEventListener("load",T)},P=()=>{if(p||(p=!0,x(),c(),!a))return;let I=Math.max(0,o.minVisibleMs-(Date.now()-l));I>0?u(v,I):v()};function W(I){if(n===null)return;let H=I.data;!H||H.persona!=="artifact-preview-ready"||H.token!==n||I.source===e.contentWindow&&P()}function T(){let I=H=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>H()):setTimeout(H,0)};I(()=>I(()=>P()))}return u(f,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",W):e.addEventListener("load",T),()=>{p=!0,c(),x(),w()}}function Ca(t,e){let{config:n}=e,o=e.registry??Fn,r=e.bodyLayout,s=n.markdown?Gs(n.markdown):null,a=Xs(n.sanitize),l=t,p=!1,d=te=>{let ge=Wn()!==null;s&&!ge&&!p&&(p=!0,Ks(()=>Ce(l)));let Y=s?s(te):Jn(te);return s&&ge&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},x=null,P=null,W=null,T=!1,I=()=>{x=null,P=null,W=null,T=!1},H=null,q=null,U=()=>{H=null,q=null},$=40,C=0,j=te=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>te()):setTimeout(te,0),J=te=>te.scrollHeight-te.clientHeight-te.scrollTop<=$,D=te=>{if(!r)return;let ge=te.scrollHeight-te.clientHeight>1,Y=te.scrollHeight-te.clientHeight-te.scrollTop;te.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&te.scrollTop>1),te.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Y>1)},_=te=>{C||(C=j(()=>{C=0,te.scrollTop=te.scrollHeight,D(te)}))},ce=(te,ge,Y,le)=>{let Z=!!r,be=Y.id+"|"+(Z?"w":"p");if(!x||W!==be||x.parentElement!==c){v(),U(),c.replaceChildren();let Te=m("pre",uy+" persona-code-pre"),Ae=m("code","persona-code");if(Te.appendChild(Ae),Z){let ze=m("div","persona-artifact-source-window");if(ze.appendChild(Te),c.appendChild(ze),!(r?.overflow==="clip")&&typeof ze.addEventListener=="function"){let Pe=()=>ze.scrollHeight-ze.clientHeight>1;ze.addEventListener("scroll",()=>{J(ze)&&(T=!1),D(ze)},{passive:!0}),ze.addEventListener("wheel",We=>{Pe()&&We.deltaY<0&&(T=!0)},{passive:!0}),ze.addEventListener("touchmove",()=>{Pe()&&(T=!0)},{passive:!0})}x=ze}else c.appendChild(Te),x=Te;P=Ae,W=be}let ve=Z?x:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",le),ve.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let fe=ve?J(ve):!0;if(P.replaceChildren(Qd(te,ge?.language,ge?.path)),ve){let Te=Y.status!=="complete";le&&Te&&r?.followOutput&&!T&&fe?_(ve):Te||(T=!1),D(ve)}},he=te=>{v(),I(),U(),c.replaceChildren();let ge=m("div",fy);ge.innerHTML=d(te),c.appendChild(ge)},Me=te=>{let ge=te.id,Y=n.features?.artifacts,le=ir(te,Y,"status-body");if(H&&q===ge&&H.parentElement===c){let ve=H.querySelector(".persona-artifact-status-view-text");ve&&Wo(ve,le,Y);return}v(),I(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),be=m("div","persona-artifact-status-view-text");Wo(be,le,Y),Z.appendChild(be),c.appendChild(Z),H=Z,q=ge},Ce=te=>{l=te;let ge=e.resolveViewMode?.(te)??r?.viewMode??"rendered",Y=te.artifactType==="markdown"?te.file:void 0,le=te.status!=="complete";le||ar(te.id);let Z=le?r?.streamingHeight:r?.completeHeight,be=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){Me(te);return}if(Y){let fe=ha(te.markdown??""),Te=ts(Y),Ae=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ge==="rendered"&&Ae&&(Te==="html"||Te==="svg")){let Ne=te.id+"\0"+fe;if(u&&w===Ne&&u.parentElement===c)return;I(),U(),v(),c.replaceChildren();let Pe=n.features?.artifacts?.filePreview,We=Pe?.iframeSandbox??"allow-scripts";!Pe?.dangerouslyAllowSameOrigin&&We.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."),We=We.split(/\s+/).filter(Et=>Et&&Et!=="allow-same-origin").join(" "));let at=my(Pe?.loading),Oe=m("div","persona-artifact-frame"),Xe=m("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",We),Xe.setAttribute("data-artifact-id",te.id);let sn=null;at.enabled&&at.injectReadySignal?(sn=yy(),Xe.srcdoc=fe+by(sn)):Xe.srcdoc=fe,Oe.appendChild(Xe),c.appendChild(Oe),at.enabled&&(f=wy(Oe,Xe,sn,at,te.id,n)),u=Oe,w=Ne;return}if(v(),!le&&Te==="markdown"&&ge==="rendered"){he(fe);return}ce(fe,{language:Y.language,path:Y.path},te,be);return}if(te.artifactType==="markdown"){if(ge==="source"){v(),ce(te.markdown??"",void 0,te,be);return}he(te.markdown??"");return}v(),I(),U(),c.replaceChildren();let ve=te.component?o.get(te.component):void 0;if(ve){let Te={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ae=ve(te.props??{},Te);if(Ae){c.appendChild(Ae);return}}catch{}}c.appendChild(gy(te))};return Ce(t),{el:c,update(te){Ce(te)}}}import{Idiomorph as xy}from"idiomorph";var Aa=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;xy.morph(t,e.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 ap=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Sa={index:-1,draft:""};function ip(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="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:{...Sa}}}function lp(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function cp(){return new Map}function dp(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function pp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function up(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Ta(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Mn(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function so(t,e){return Mn(t)-t.scrollTop<=e}function Ma(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=t,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!e&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:e&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ea(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function fp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function gp(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function mp(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var ss={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Cy=["pre","code","a","script","style"],ka=t=>({type:t?.type??ss.type,placeholder:t?.placeholder??ss.placeholder,speed:t?.speed??ss.speed,duration:t?.duration??ss.duration,buffer:t?.buffer??ss.buffer}),Ay=[{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"}],yp=new Map;for(let t of Ay)yp.set(t.name,t);var dr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:yp.get(t)??null,La=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
25
|
+
`);return s<0?"":t.slice(0,s)}return t},Sy=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},Ty=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},Qi=/\s/,My=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Ey=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Qi.test(s[l])){let p=l;for(;p<s.length&&Qi.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&&!Qi.test(s[d]);)p.appendChild(Sy(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},ky=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.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(Ty(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},as=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??Cy).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)My(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?Ey:ky;for(let u of l)c(u,n,d);return r.innerHTML},Pa=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},is=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},hp=new WeakMap,Ly=(t,e)=>{if(!t.styles)return;let n=hp.get(e);if(n||(n=new Set,hp.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},Ji=new WeakMap,Py=(t,e)=>{if(!t.onAttach)return;let n=Ji.get(e);if(n||(n=new Map,Ji.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},bp=t=>{let e=Ji.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ia=(t,e)=>{Ly(t,e),Py(t,e)};function Yi(t,e=Ut){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var ls=0,ao=null;function Zi(t=document){if(ls++,ls===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;ao={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 e=!1;return()=>{if(!e&&(e=!0,ls=Math.max(0,ls-1),ls===0&&ao)){let n=t.body,o=t.defaultView??window;n.style.overflow=ao.originalOverflow,n.style.position=ao.originalPosition,n.style.top=ao.originalTop,n.style.width=ao.originalWidth,o.scrollTo(0,ao.scrollY),ao=null}}}var cs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ft=t=>(t?.launcher?.mountMode??"floating")==="docked",ds=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",un=t=>{let e=t?.launcher?.dock;return{side:e?.side??cs.side,width:e?.width??cs.width,animate:e?.animate??cs.animate,reveal:e?.reveal??cs.reveal,maxHeight:e?.maxHeight??cs.maxHeight}};var wn={"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 Iy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ra=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Iy,buttonSize:r,iconSize:s="28px"}=e,a=t?.launcher??{},l=r??a.closeButtonSize??"32px",p=m("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=nt("button",{className:ko("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||Gt.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}}),x=ae(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=w,p.appendChild(v),c&&d){let P=null,W=()=>{if(P)return;let I=v.ownerDocument,H=I.body;if(!H)return;P=Sn(I,"div","persona-clear-chat-tooltip"),P.textContent=d;let q=Sn(I,"div");q.className="persona-clear-chat-tooltip-arrow",P.appendChild(q);let U=v.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(oo),P.style.left=`${U.left+U.width/2}px`,P.style.top=`${U.top-8}px`,P.style.transform="translate(-50%, -100%)",H.appendChild(P)},T=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};p.addEventListener("mouseenter",W),p.addEventListener("mouseleave",T),v.addEventListener("focus",W),v.addEventListener("blur",T),p._cleanupTooltip=()=>{T(),p.removeEventListener("mouseenter",W),p.removeEventListener("mouseleave",T),v.removeEventListener("focus",W),v.removeEventListener("blur",T)}}return{button:v,wrapper:p}},Ry="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wa=(t,e={})=>{let{wrapperClassName:n=Ry,buttonSize:o,iconSize:r="20px"}=e,a=(t?.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??"",x=a.paddingY??"",P=a.tooltipText??"Clear chat",W=a.showTooltip??!0,T=m("div",n),I=!!(u||w),H=nt("button",{className:ko("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Gt.actionIconColor,backgroundColor:c||void 0,border:I?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),q=ae(p,r,"currentColor",1);if(q&&(q.style.display="block",H.appendChild(q)),T.appendChild(H),W&&P){let U=null,$=()=>{if(U)return;let j=H.ownerDocument,J=j.body;if(!J)return;U=Sn(j,"div","persona-clear-chat-tooltip"),U.textContent=P;let D=Sn(j,"div");D.className="persona-clear-chat-tooltip-arrow",U.appendChild(D);let _=H.getBoundingClientRect();U.style.position="fixed",U.style.zIndex=String(oo),U.style.left=`${_.left+_.width/2}px`,U.style.top=`${_.top-8}px`,U.style.transform="translate(-50%, -100%)",J.appendChild(U)},C=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};T.addEventListener("mouseenter",$),T.addEventListener("mouseleave",C),H.addEventListener("focus",$),H.addEventListener("blur",C),T._cleanupTooltip=()=>{C(),T.removeEventListener("mouseenter",$),T.removeEventListener("mouseleave",C),H.removeEventListener("focus",$),H.removeEventListener("blur",C)}}return{button:H,wrapper:T}};var Gt={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=t=>{let{config:e,showClose:n=!0}=t,o=nt("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=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=nt("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 q=parseFloat(s)||24,U=ae(p,q*.6,"currentColor",1);U?d.replaceChildren(U):d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let q=m("img");q.src=e.launcher.iconUrl,q.alt="",q.className="persona-rounded-xl persona-object-cover",q.style.height=s,q.style.width=s,d.replaceChildren(q)}else d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=nt("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Gt.titleColor}}),w=nt("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Gt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},v=f.enabled??!0,x=f.placement??"inline",P=null,W=null;if(v){let U=Wa(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=U.button,W=U.wrapper,x==="top-right"&&(W.style.right="48px"),x==="inline"&&o.appendChild(W)}let T=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:I,wrapper:H}=Ra(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&o.appendChild(H),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:I,closeButtonWrapper:H,clearChatButton:P,clearChatButtonWrapper:W}},ps=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var Wy=t=>{let e=Ho({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.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 e};function By(t,e,n){if(e?.length)for(let o of e){let r=m("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=m("div","persona-relative");s.appendChild(r);let a=lr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var Hy=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=m("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=Jd({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Gt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Gt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),By(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let I=r.onTitleClick;d.addEventListener("click",H=>{H.target.closest("button")||I()}),d.addEventListener("keydown",H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),I())})}let T=r?.titleRowHover;T&&(d.style.borderRadius=T.borderRadius??"10px",d.style.padding=T.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=T.background??"",d.style.borderColor=T.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=m("div",""),f=m("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||Gt.actionIconColor;let v=a.closeButtonIconName??"x",x=ae(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let P=m("div");P.style.display="none";let W=m("span");return W.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:W,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},vp={default:Wy,minimal:Hy},Dy=t=>vp[t]??vp.default,Ba=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=m("div");l.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=Dy(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ha=t=>{let e=m("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let a=parseFloat(e.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,r());e.style.height=`${a}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Da=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",d=t?.copy?.stopButtonLabel??"Stop",c=e.showTooltip??!1,u=e.size??"40px",w=e.backgroundColor,f=e.textColor,v=m("div","persona-send-button-wrapper"),x=nt("button",{className:ko("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:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),P=null,W=null;if(n){let q=parseFloat(u)||24,U=f?.trim()||"currentColor";r?(P=ae(r,q,U,2),P?x.appendChild(P):x.textContent=o):x.textContent=o,W=ae(s,q,U,2)}else x.textContent=p;let T=null;c&&a&&(T=m("div","persona-send-button-tooltip"),T.textContent=a,v.appendChild(T)),x.setAttribute("aria-label",a),v.appendChild(x);let I="send";return{button:x,wrapper:v,setMode:q=>{if(q===I)return;I=q;let U=q==="stop"?l:a;if(x.setAttribute("aria-label",U),T&&(T.textContent=U),n){if(P&&W){let $=q==="stop"?W:P;x.replaceChildren($)}}else x.textContent=q==="stop"?d:p}}},Na=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??a,d=parseFloat(p)||24,c=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,w=m("div","persona-send-button-wrapper"),f=nt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=ae(l,d,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",w.appendChild(f);let P=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&P){let T=m("div","persona-send-button-tooltip");T.textContent=P,w.appendChild(T)}return{button:f,wrapper:w}},Fa=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=m("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=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Dn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=m("div","persona-send-button-wrapper"),c=nt("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":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});c.addEventListener("mouseenter",()=>{c.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="transparent"});let u=ae(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",v=>{v.preventDefault(),r.click()}),d.appendChild(c);let w=e.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=w,d.appendChild(f),{button:c,wrapper:d,input:r,previewsContainer:o}},Oa=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=m("a");a.href=e.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},_a=()=>nt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var $a=t=>{let{config:e}=t,n=nt("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=_a(),r=nt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ha(e);a();let l=Da(e),p=Na(e),d=Fa(e),c=Oa(e);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=nt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("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 wp=()=>{let t=nt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=m("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},xp=t=>{let{config:e}=t,n=nt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=_a(),r=Oa(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ha(e);s.style.maxHeight="100px",a();let l=Da(e),p=Na(e),d=Fa(e);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=nt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=m("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 Cp=t=>{let e=t?.launcher?.enabled??!0,n=Ft(t);if(ds(t)){let c=t?.launcher?.composerBar??{},u=m("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(t?.launcher?.zIndex??Ut);let w=m("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=m("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(t?.launcher?.zIndex??Ut),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("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(!e){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=t?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=t?.launcher??{},s=r.position&&wn[r.position]?wn[r.position]:wn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Ut);let l=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=t?.launcher?.width??t?.launcherWidth??Nn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},Ny=(t,e)=>{let n=m("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}=Ra(t,{showClose:e,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=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let H=Wa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=H.button,l=H.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=nt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=nt("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=nt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=nt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=nt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),v=t?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let P=nt("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"}}),W=xp({config:t}),{root:T,textNode:I}=wp();return n.append(p,r,d,P),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:P,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:T,peekTextNode:I}},Ap=(t,e=!0)=>{if(ds(t))return Ny(t,e);let n=nt("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=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Ba(t,o,{showClose:e}):Ho({config:t,showClose:e}),a=nt("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=nt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=nt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=nt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:Ft(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},l,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),t?.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=$a({config:t}),v=t?.layout?.showFooter!==!1;r?ps(n,s,t):(s.header.style.display="none",ps(n,s,t)),n.append(a);let x=nt("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(x),{container:n,body:a,messagesWrapper:c,composerOverlay:x,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 el=(t,e)=>{let n=m("button");n.type="button",n.innerHTML=`
|
|
20
26
|
<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>
|
|
21
27
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
22
28
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -24,14 +30,14 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
24
30
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
25
31
|
</span>
|
|
26
32
|
<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>
|
|
27
|
-
`,t.addEventListener("click",e);let r=s=>{var L,M,k,C,P,U,_,I,$,N,te,Ee,de;let a=(L=s.launcher)!=null?L:{},i=mn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let Y=(M=a.title)!=null?M:"Chat Assistant";d.textContent=Y,d.setAttribute("title",Y)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let Y=(k=a.subtitle)!=null?k:"Here to help you get answers fast";c.textContent=Y,c.setAttribute("title",Y)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let g=t.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let Y=(C=a.agentIconSize)!=null?C:"40px";if(g.style.height=Y,g.style.width=Y,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let Le=parseFloat(Y)||24,Pe=he(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(g.appendChild(Pe),g.style.display=""):(g.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",g.style.display="")}let h=t.querySelector("[data-role='launcher-image']");if(h){let Y=(_=a.agentIconSize)!=null?_:"40px";h.style.height=Y,h.style.width=Y,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Y=(I=a.callToActionIconSize)!=null?I:"32px";m.style.height=Y,m.style.width=Y,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Pe=parseFloat(Y)||24,ae=Math.max(Pe-Le,8),fe=he(a.callToActionIconName,ae,"currentColor",2);fe?m.appendChild(fe):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&gr[a.position]?gr[a.position]:gr["bottom-right"],w="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?T:`${w} ${v}`,i||(t.style.zIndex=String((te=a.zIndex)!=null?te:bn));let B="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Ee=a.border)!=null?Ee:B,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:S,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var wm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=bm(n),s=vm(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={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:i,header:d,composer:c,replaceHeader:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{c.footer.replaceWith(h),c.footer=h}}},qi=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>zi(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=zi(n,t);return{instance:o,element:o.element}};var Fb=n=>{switch(n){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}},Ob=(n,e)=>{if(!n)return null;let t=Fb(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},_b=(n,e)=>{let t=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},$b=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},ji=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},Vi=320,Cm=320,Ub=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),zb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),qb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),jb=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Vb=(n,e,t)=>{if(n.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var g;let c=b("img");c.alt=((g=i.alt)==null?void 0:g.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Vi}px`,c.style.maxHeight=`${Cm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),$b(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Kb=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!ji(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vi}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Gb=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!ji(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Vi}px`,o.style.maxHeight=`${Cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Qb=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!ji(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},sa=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},Xb=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:sa};if(e){let o=e(r);if(o!==null)return o}return sa()},Jb=(n,e)=>{let t=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},xm=(n,e,t="div")=>{let r=b(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Yb=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Zb=(n,e,t)=>{var v,w,T,B,S,L,M;let r=(v=e.showCopy)!=null?v:!0,o=(w=e.showUpvote)!=null?w:!0,s=(T=e.showDownvote)!=null?T:!0,a=(B=e.showReadAloud)!=null?B:!1;if(!r&&!o&&!s&&!a){let k=b("div");return k.style.display="none",k.id=`actions-${n.id}`,k.setAttribute("data-actions-for",n.id),k}let i=(S=e.visibility)!=null?S:"hover",d=(L=e.align)!=null?L:"right",c=(M=e.layout)!=null?M:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],h=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);h.id=`actions-${n.id}`,h.setAttribute("data-actions-for",n.id);let m=(k,C,P)=>{let U=vn({icon:k,label:C,size:14,className:"persona-message-action-btn"});return U.setAttribute("data-action",P),U};return r&&h.appendChild(m("copy","Copy message","copy")),a&&h.appendChild(m("volume-2","Read aloud","read-aloud")),o&&h.appendChild(m("thumbs-up","Upvote","upvote")),s&&h.appendChild(m("thumbs-down","Downvote","downvote")),h},Ki=(n,e,t,r,o,s)=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue;let a=t!=null?t:{},i=(ne=a.layout)!=null?ne:"bubble",d=a.avatar,c=a.timestamp,u=(re=d==null?void 0:d.show)!=null?re:!1,g=(ce=c==null?void 0:c.show)!=null?ce:!1,h=(Ce=d==null?void 0:d.position)!=null?Ce:"left",m=(_e=c==null?void 0:c.position)!=null?_e:"below",v=Yb(n.role,i),w=b("div",v.join(" "));w.id=`bubble-${n.id}`,w.setAttribute("data-message-id",n.id),w.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Ub(n),B=(X=(V=n.content)==null?void 0:V.trim())!=null?X:"",L=T.length>0&&B===La,M=_a((J=(Ae=s==null?void 0:s.widgetConfig)==null?void 0:Ae.features)==null?void 0:J.streamAnimation),k=(Je=(Se=(ie=s==null?void 0:s.widgetConfig)==null?void 0:ie.features)==null?void 0:Se.streamAnimation)==null?void 0:Je.plugins,C=n.role==="assistant"&&M.type!=="none"?hs(M.type,k):null,P=n.role==="assistant"&&((et=C==null?void 0:C.isAnimating)==null?void 0:et.call(C,n))===!0,U=n.role==="assistant"&&C!==null&&(!!n.streaming||P);U&&(C!=null&&C.bubbleClass)&&w.classList.add(C.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),n.streaming&&_.classList.add("persona-content-streaming"),U&&C&&(C.containerClass&&_.classList.add(C.containerClass),_.style.setProperty("--persona-stream-step",`${M.speed}ms`),_.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let I=U?$a((Wt=n.content)!=null?Wt:"",M.buffer,C,n,!!n.streaming):(ft=n.content)!=null?ft:"",$=e({text:I,message:n,streaming:!!n.streaming,raw:n.rawContent}),N=$;U&&(C==null?void 0:C.wrap)==="char"?N=Zs($,"char",n.id,{skipTags:C.skipTags}):U&&(C==null?void 0:C.wrap)==="word"&&(N=Zs($,"word",n.id,{skipTags:C.skipTags}));let te=null;if(L?(te=document.createElement("div"),te.innerHTML=N,te.style.display="none",_.appendChild(te)):_.innerHTML=N,U&&(C!=null&&C.useCaret)&&!L&&B){let Q=Ua(),it=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),je=it[it.length-1];if(je!=null&&je.parentNode)je.parentNode.insertBefore(Q,je.nextSibling);else{let Te=_.lastElementChild;Te?Te.appendChild(Q):_.appendChild(Q)}}if(g&&m==="inline"&&n.createdAt){let Q=xm(n,c,"span");Q.classList.add("persona-timestamp-inline");let it=_.lastElementChild;it?it.appendChild(Q):_.appendChild(Q)}if(T.length>0){let Q=Vb(T,!L&&!!B,()=>{L&&te&&(te.style.display="")});Q?w.appendChild(Q):L&&te&&(te.style.display="")}let Ee=zb(n);if(Ee.length>0){let Q=Kb(Ee);Q&&w.appendChild(Q)}let de=qb(n);if(de.length>0){let Q=Gb(de);Q&&w.appendChild(Q)}let Y=jb(n);if(Y.length>0){let Q=Qb(Y);Q&&w.appendChild(Q)}if(w.appendChild(_),g&&m==="below"&&n.createdAt){let Q=xm(n,c);Q.classList.add("persona-mt-1"),w.appendChild(Q)}let Le=n.role==="assistant"?Ob(n.stopReason,(ue=(rt=s==null?void 0:s.widgetConfig)==null?void 0:rt.copy)==null?void 0:ue.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let Q=!!(I&&I.trim()),it=M.placeholder==="skeleton",je=it&&M.buffer==="line"&&Q;if(Q)je&&w.appendChild(ea());else if(it)w.appendChild(ea());else{let Te=Xb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Te&&w.appendChild(Te)}}if(Le&&n.stopReason&&!n.streaming&&(B||(_.style.display="none"),w.appendChild(_b(n.stopReason,Le))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=Zb(n,r,o);w.appendChild(Q)}if(!u||n.role==="system")return w;let ae=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),fe=Jb(d,n.role);return h==="right"||h==="left"&&n.role==="user"?ae.append(w,fe):ae.append(fe,w),w.classList.remove("persona-max-w-[85%]"),w.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ae};var bs=new Set,ev=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),tv=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
-
`):""},
|
|
29
|
-
`);let
|
|
30
|
-
`):""},Qi=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},ov=(n,e)=>{var u,g,h,m,v;let t=n.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(g=r==null?void 0:r.collapsedMode)!=null?g:"tool-call",s=rv(n,(h=r==null?void 0:r.previewMaxLines)!=null?h:3),a=t?Lu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Pi(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Pi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Sm=(n,e,t)=>{var u;let r=vs.has(n),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let g=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",h=he(r?"chevron-up":"chevron-down",16,g,2);h?c.appendChild(h):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Xi=(n,e)=>{var N,te,Ee,de,Y,Le,Pe,ae,fe;let t=n.toolCall,r=(N=e==null?void 0:e.toolCall)!=null?N:{},o=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(Ee=(te=e==null?void 0:e.features)==null?void 0:te.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&vs.has(n.id),{summary:d,previewText:c,isActive:u}=ov(n,e),g=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=b("div","persona-flex persona-flex-col persona-text-left"),m=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let v=String((de=t.startedAt)!=null?de:Date.now()),w=()=>{let ne=b("span","");return ne.setAttribute("data-tool-elapsed",v),ne.textContent=zs(t),ne},T=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(Y=s.collapsedMode)!=null?Y:"tool-call",isActive:u,config:e!=null?e:{},elapsed:zs(t),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,h.appendChild(m)):T instanceof HTMLElement?h.appendChild(T):(m.textContent=d,h.appendChild(m));let B=(Pe=s.loadingAnimation)!=null?Pe:"none",S=r.activeTextTemplate,L=r.completeTextTemplate,M=u?S:L,k=T instanceof HTMLElement,C=(ne,re,ce)=>{let Ce=ce;for(let _e of re){let V=b("span","persona-tool-char");V.style.setProperty("--char-index",String(Ce)),V.textContent=_e===" "?"\xA0":_e,ne.appendChild(V),Ce++}return Ce},P=(ne,re)=>{var V;m.textContent="";let ce=((V=t.name)==null?void 0:V.trim())||"tool",Ce=Ma(ne,ce),_e=0;for(let X of Ce){let Ae=X.styles.length>0?(()=>{let J=b("span",X.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(J),J})():m;if(X.isDuration&&u)Ae.appendChild(w());else{let J=X.isDuration?zs(t):X.text;re?_e=C(Ae,J,_e):Ae.appendChild(document.createTextNode(J))}}};if(!k)if(u&&B!=="none"){let ne=(ae=r.loadingAnimationDuration)!=null?ae:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),M&&P(M,!1);else if(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),B==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)P(M,!0);else{let re=m.textContent||d;m.textContent="",C(m,re,0)}}else M&&P(M,!1);let U=null;if(a){U=b("div","persona-flex persona-items-center");let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",re=he(i?"chevron-up":"chevron-down",16,ne,2);re?U.appendChild(re):U.textContent=i?"Hide":"Show";let ce=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ce.append(U),g.append(h,ce)}else g.append(h);let _=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&c){let ne=(fe=r.renderCollapsedPreview)==null?void 0:fe.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:u,config:e!=null?e:{}});nv(_,ne)||(_.textContent=c),_.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(g,_),o;let I=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",r.contentBackgroundColor&&(I.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(I.style.color=r.contentTextColor),r.contentPaddingX&&(I.style.paddingLeft=r.contentPaddingX,I.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(I.style.paddingTop=r.contentPaddingY,I.style.paddingBottom=r.contentPaddingY),t.name){let ne=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ne.style.color=r.contentTextColor:r.headerTextColor&&(ne.style.color=r.headerTextColor),ne.textContent=t.name,I.appendChild(ne)}if(t.args!==void 0){let ne=b("div","persona-space-y-1"),re=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Arguments";let ce=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Qi(ce,r),ce.textContent=ho(t.args),ne.append(re,ce),I.appendChild(ne)}if(t.chunks&&t.chunks.length){let ne=b("div","persona-space-y-1"),re=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Activity";let ce=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Qi(ce,r),ce.textContent=t.chunks.join(""),ne.append(re,ce),I.appendChild(ne)}if(t.status==="complete"&&t.result!==void 0){let ne=b("div","persona-space-y-1"),re=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Result";let ce=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",Qi(ce,r),ce.textContent=ho(t.result),ne.append(re,ce),I.appendChild(ne)}if(t.status==="complete"&&typeof t.duration=="number"){let ne=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ne.style.color=r.contentTextColor),ne.textContent=`Duration: ${t.duration}ms`,I.appendChild(ne)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),U){U.innerHTML="";let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",re=he(i?"chevron-up":"chevron-down",16,ne,2);re?U.appendChild(re):U.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),o.append(g,_,I),o};var zo=new Map,ei=n=>{let t=(n.startsWith(Ur)?n.slice(Ur.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Tm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Mm=(n,e)=>{var r,o,s;let t=(o=(r=Tm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=zo.get(n))!=null?s:t==="expanded"},Em=(n,e,t)=>{var a,i;let r=Tm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=he(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},km=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=Mm(n,t);Em(r,s,t),o.style.display=s?"":"none"};var ti=(n,e)=>{var P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(P=r==null?void 0:r.backgroundColor)!=null?P:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(U=r==null?void 0:r.borderColor)!=null?U:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(_=r==null?void 0:r.titleColor)!=null?_:"currentColor",u=he(d,20,c,2);u&&i.appendChild(u);let g=b("div","persona-flex-1 persona-min-w-0"),h=b("div","persona-flex persona-items-center persona-gap-2"),m=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(I=r==null?void 0:r.title)!=null?I:"Approval Required",h.appendChild(m),!o){let re=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");re.setAttribute("data-approval-status",t.status),t.status==="approved"?(re.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",re.style.color="var(--persona-palette-colors-success-700, #15803d)",re.textContent="Approved"):t.status==="denied"?(re.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",re.style.color="var(--persona-palette-colors-error-700, #b91c1c)",re.textContent="Denied"):t.status==="timeout"&&(re.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",re.style.color="var(--persona-palette-colors-warning-700, #b45309)",re.textContent="Timeout"),h.appendChild(re)}g.appendChild(h);let w=t.toolType==="webmcp"||t.toolName.startsWith(Ur)?Fs(t.toolName):void 0,T=($=r==null?void 0:r.formatDescription)==null?void 0:$.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...w?{displayTitle:w}:{},...t.reason?{reason:t.reason}:{}}),B=!t.toolName,S=T||(B?t.description:`The assistant wants to use \u201C${w!=null?w:ei(t.toolName)}\u201D.`),L=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=S,g.appendChild(L),t.reason){let re=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");re.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?re.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let ce=b("span","persona-font-medium");ce.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,re.appendChild(ce),re.appendChild(document.createTextNode(t.reason)),g.appendChild(re)}let M=(te=r==null?void 0:r.detailsDisplay)!=null?te:"collapsed",k=!!t.description&&!B,C=k||!!t.parameters;if(M!=="hidden"&&C){let re=Mm(n.id,e),ce=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ce.type="button",ce.setAttribute("data-expand-header","true"),ce.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ce.style.color=r.descriptionColor);let Ce=b("span");Ce.setAttribute("data-approval-details-label","true");let _e=b("span","persona-inline-flex persona-items-center");_e.setAttribute("data-approval-details-chevron","true"),ce.append(Ce,_e),Em(ce,re,e),g.appendChild(ce);let V=b("div");if(V.setAttribute("data-approval-details","true"),V.style.display=re?"":"none",k){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=t.description,V.appendChild(X)}if(t.parameters){let X=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=ho(t.parameters),V.appendChild(X)}g.appendChild(V)}if(o){let re=b("div","persona-flex persona-gap-2 persona-mt-2");re.setAttribute("data-approval-buttons","true");let ce=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ce.type="button",ce.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ce.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ce.setAttribute("data-approval-action","approve");let Ce=he("shield-check",14,(Y=r==null?void 0:r.approveButtonTextColor)!=null?Y:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",ce.appendChild(Ce));let _e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ce.appendChild(_e);let V=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ae=r==null?void 0:r.denyButtonTextColor)!=null?ae:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let X=he("shield-x",14,(fe=r==null?void 0:r.denyButtonTextColor)!=null?fe:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let Ae=document.createTextNode((ne=r==null?void 0:r.denyLabel)!=null?ne:"Deny");V.appendChild(Ae),re.append(ce,V),g.appendChild(re)}return a.append(i,g),s.appendChild(a),s};function sv(n){var t,r;let e=(t=n.getRootNode)==null?void 0:t.call(n);return e instanceof ShadowRoot?e:((r=n.ownerDocument)!=null?r:document).body}function Lm(n){var w;let{anchor:e,content:t,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=n,c=(w=n.container)!=null?w:sv(e),u=!1,g=null,h=()=>{if(!u)return;let T=e.getBoundingClientRect();t.style.position="fixed",s&&(t.style.minWidth=`${T.width}px`);let B=r==="top-start"||r==="top-end"?T.top-o-t.getBoundingClientRect().height:T.bottom+o,S=r==="bottom-end"||r==="top-end"?T.right-t.getBoundingClientRect().width:T.left;t.style.top=`${B}px`,t.style.left=`${S}px`},m=()=>{u&&(u=!1,g&&(g(),g=null),t.remove())},v=()=>{var k,C,P;if(u)return;u=!0,a!=null&&(t.style.zIndex=String(a)),c.appendChild(t),h();let T=(C=((k=e.ownerDocument)!=null?k:document).defaultView)!=null?C:window,B=(P=e.ownerDocument)!=null?P:document,S=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}h()},L=U=>{let _=typeof U.composedPath=="function"?U.composedPath():[];_.includes(t)||_.includes(e)||(m(),d==null||d("outside"))},M=T.setTimeout(()=>{B.addEventListener("pointerdown",L,!0)},0);T.addEventListener("scroll",S,!0),T.addEventListener("resize",S),g=()=>{T.clearTimeout(M),B.removeEventListener("pointerdown",L,!0),T.removeEventListener("scroll",S,!0),T.removeEventListener("resize",S)},i==null||i()};return{get isOpen(){return u},open:v,close:m,toggle:()=>u?m():v(),reposition:h,destroy:m}}function Pm(n){return(typeof n.composedPath=="function"?n.composedPath():[]).some(t=>t instanceof HTMLElement&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}var av=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Im=(n,e)=>{let t=n.keyHandlers.get(e);t&&(document.removeEventListener("keydown",t),n.keyHandlers.delete(e));let r=n.popovers.get(e);r&&(r.destroy(),n.popovers.delete(e))},qo=(n,e)=>{Im(n,e);let t=n.pendingOrder.indexOf(e);t!==-1&&n.pendingOrder.splice(t,1),n.latestPendingApprovalId===e&&(n.latestPendingApprovalId=n.pendingOrder.length?n.pendingOrder[n.pendingOrder.length-1]:null)},iv=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,lv=(n,e)=>{var r,o;let t=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=zo.get(n))!=null?o:t==="expanded"},Ji=n=>{let e=b("span","persona-approval-kbd");return e.textContent=n,e},cv=(n,e)=>{var c,u;let t=b("span","persona-approval-title");e!=null&&e.titleColor&&(t.style.color=e.titleColor);let o=n.toolType==="webmcp"||n.toolName.startsWith(Ur)?Fs(n.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:n.toolName,toolType:n.toolType,description:(c=n.description)!=null?c:"",parameters:n.parameters,...o?{displayTitle:o}:{},...n.reason?{reason:n.reason}:{}});if(s)return t.textContent=s,t;let a=o!=null?o:ei(n.toolName),i=n.toolType&&n.toolType!=="webmcp"?n.toolType:null;t.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,t.appendChild(d),i){t.append(" from ");let g=document.createElement("strong");g.textContent=i,t.appendChild(g)}return t},dv=n=>{let e=b("div","persona-approval-resolved"),t=he("ban",15,"currentColor",2);t&&e.appendChild(t);let r=b("span","persona-approval-resolved-name");return r.textContent=n.toolName?ei(n.toolName):"Tool",e.append(r,document.createTextNode(n.status==="timeout"?" timed out":" denied")),e},pv=(n,e,t,r,o,s,a)=>{var U,_,I,$,N,te,Ee;let i=b("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(U=r==null?void 0:r.detailsDisplay)!=null?U:"collapsed",c=!!t.description&&d!=="hidden",u=t.parameters!=null&&d!=="hidden",g=c||u,h=g&&lv(e.id,r),m=(_=r==null?void 0:r.showDetailsLabel)!=null?_:"Show details",v=(I=r==null?void 0:r.hideDetailsLabel)!=null?I:"Hide details",w=b("button","persona-approval-head");w.type="button",g?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",h?"true":"false"),w.setAttribute("aria-label",h?v:m)):w.setAttribute("data-static","true");let T=b("span","persona-approval-logo"),B=he("shield-check",16,"currentColor",2);B&&T.appendChild(B),w.appendChild(T);let S=cv(t,r);if(g){let de=b("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let Y=he("chevron-down",14,"currentColor",2);Y&&de.appendChild(Y),S.append(" "),S.appendChild(de)}w.appendChild(S),i.appendChild(w);let L=b("div","persona-approval-body");if(g){let de=b("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!h,c){let Y=b("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Y.style.color=r.descriptionColor),Y.textContent=t.description,de.appendChild(Y)}if(u){let Y=b("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(Y.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Y.style.color=r.parameterTextColor),Y.textContent=ho(t.parameters),de.appendChild(Y)}L.appendChild(de)}if(t.reason){let de=b("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Y=b("span","persona-approval-reason-label");Y.textContent=`${($=r==null?void 0:r.reasonLabel)!=null?$:"Agent's stated reason:"} `,de.append(Y,document.createTextNode(t.reason)),L.appendChild(de)}let M=b("div","persona-approval-actions"),k=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},P=b("button","persona-approval-deny");if(P.type="button",P.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(P.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(P.style.color=r.denyButtonTextColor),P.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let de=b("div","persona-approval-split"),Y=b("button","persona-approval-primary");Y.type="button",Y.setAttribute("data-action","always"),C(Y),Y.append((te=r==null?void 0:r.approveLabel)!=null?te:"Always allow",Ji("\u23CE"));let Le=b("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),C(Le);let Pe=he("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(Y,Le),M.append(de,P),P.append(Ji("Esc"));let ae=b("div","persona-approval-menu"),fe=b("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",Ji("\u2318\u23CE")),ae.appendChild(fe),k=Lm({anchor:de,content:ae,placement:"bottom-start",matchAnchorWidth:!0}),n.popovers.set(e.id,k),fe.addEventListener("click",()=>{qo(n,e.id),o()})}else{let de=b("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),C(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),M.append(de,P)}return L.appendChild(M),i.appendChild(L),i.addEventListener("click",de=>{let Y=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!Y)return;let Le=Y.getAttribute("data-action");if(Le==="toggle-params"){let Pe=i.querySelector('[data-role="params"]');if(Pe){let ae=Pe.hidden;Pe.hidden=!ae,w.setAttribute("aria-expanded",ae?"true":"false"),w.setAttribute("aria-label",ae?v:m),zo.set(e.id,ae)}return}if(Le==="toggle-menu"){k==null||k.toggle();return}if(Le==="always"){qo(n,e.id),o({remember:!0});return}if(Le==="allow"){qo(n,e.id),o();return}if(Le==="deny"){qo(n,e.id),s();return}}),i},Wm=()=>{let n=av();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=iv(a);if(i.status!=="pending"){if(qo(n,r.id),i.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return dv(i)}Im(n,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=pv(n,r,i,d,o,s,c);if(c){n.pendingOrder.includes(r.id)||n.pendingOrder.push(r.id),n.latestPendingApprovalId=n.pendingOrder[n.pendingOrder.length-1];let g=h=>{Pm(h)||r.id===n.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),qo(n,r.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?o():o({remember:!0})))};n.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return u}},teardown:()=>{for(let r of[...n.keyHandlers.keys(),...n.popovers.keys()])qo(n,r);n.latestPendingApprovalId=null}}};var Rm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(t=null),!o||!o.length||!u&&(i!=null?i:s?s.getMessages():[]).some(T=>T.role==="user"))return;let g=document.createDocumentFragment(),h=s?s.isStreaming():!1,m=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(o.forEach(v=>{let w=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=v,w.disabled=h,d!=null&&d.fontFamily&&(w.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(w.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY),w.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),g.appendChild(w),e.push(w)}),n.appendChild(g),u){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var aa=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ia=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var uv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),mv=new Set(["step_start","execution_start"]),gv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),fv=new Set(["step_complete","agent_turn_complete"]),hv=new Set(["flow_complete","agent_complete"]),Hm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Dm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),qn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,jo=(n,e)=>{let t=n[e];return Dm(t)?t:void 0};function Yi(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ni(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function yv(n,e){return typeof e.type=="string"?e.type:n}function bv(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function vv(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Bm(n){var r,o,s,a,i;let e=jo(n,"result"),t=[jo(n,"tokens"),jo(n,"totalTokens"),e?jo(e,"tokens"):void 0,jo(n,"usage"),e?jo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=qn(n.outputTokens))!=null?s:qn(n.completionTokens))!=null?i:e?(a=qn(e.outputTokens))!=null?a:qn(e.completionTokens):void 0}function wv(n){var t,r,o,s,a;let e=jo(n,"result");return(a=(o=(r=(t=qn(n.executionTime))!=null?t:qn(n.executionTimeMs))!=null?r:qn(n.execution_time))!=null?o:qn(n.duration))!=null?a:e?(s=qn(e.executionTime))!=null?s:qn(e.executionTimeMs):void 0}function xv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var la=class{constructor(e=xv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:ni(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!Dm(t)){Hm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=yv(e,t),o=this.now();if(uv.has(r)){this.startRun(o);return}if(mv.has(r)){this.run||this.startRun(o);return}if(gv.has(r)){if(!vv(r,t))return;let a=bv(t);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Yi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ni(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(fv.has(r)){if(!this.run)return;let a=this.run,i=Bm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Yi(a.visibleCharCount),u=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:ni(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(hv.has(r)){if(!this.run)return;let a=this.run,i=Bm(t),d=i!=null?i:a.exactOutputTokens+Yi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:ni(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(Hm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=wv(t);return s!=null?s:r-e.startedAt}};function ws(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Cv={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)"}},Av={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Sv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Tv=100;function Mv(n,e){let t={...Cv,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Av}function Ev(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function kv(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Lv(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)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 Pv(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Iv(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Wv(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Rv(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function Hv(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Zi(n,e,t,r,o,s,a,i){var h;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");ws(c,(h=r.classNames)==null?void 0:h.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(g()),c;function g(){var N,te;let m=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let w=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=he(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&w.appendChild(T);let B=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(N=r.timestampFormat)!=null?N:"relative";B.textContent=S==="relative"?Ev(n.timestamp,t):kv(n.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(e+1));let M=Mv(n.type,r.badgeColors),k=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=M.bg,k.style.color=M.text,k.style.borderColor=M.text+"50",k.textContent=n.type;let C=(te=r.descriptionFields)!=null?te:Sv,P=Lv(n.payload,C),U=null;P&&(U=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=P);let _=b("div","persona-flex-1 persona-min-w-0"),I=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=he("clipboard","12px","currentColor",1.5);return $&&I.appendChild($),I.addEventListener("click",async Ee=>{Ee.stopPropagation(),await Pv(Iv(n)),I.innerHTML="";let de=he("check","12px","currentColor",1.5);de&&I.appendChild(de),setTimeout(()=>{I.innerHTML="";let Y=he("clipboard","12px","currentColor",1.5);Y&&I.appendChild(Y)},1500)}),v.appendChild(w),v.appendChild(B),L&&v.appendChild(L),v.appendChild(k),U&&v.appendChild(U),v.appendChild(_),v.appendChild(I),m.appendChild(v),d&&m.appendChild(Hv(n,a,i)),m}}function Nm(n){var v,w,T,B,S;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(w=i==null?void 0:i.iconName)!=null?w:"arrow-down",u=(T=i==null?void 0:i.label)!=null?T:"",g=(S=(B=o==null?void 0:o.features)==null?void 0:B.eventStream)!=null?S:{},h=s.find(L=>L.renderEventStreamView);if(h!=null&&h.renderEventStreamView&&o){let L=h.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return m();function m(){let L=g.classNames,M=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ws(M,L==null?void 0:L.panel);let k=[],C="",P="",U=null,_=[],I={},$=0,N=Na(),te=0,Ee=0,de=!1,Y=null,Le=!1,Pe=0,ae=new Set,fe=new Map,ne="",re="",ce=null,Ce,_e,V,X,Ae=null,J=null,ie=null;function Se(){let ge=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),H=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ws(H,L==null?void 0:L.headerBar),a){J=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Ae=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",ie=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ie.style.display="none",ie.style.pointerEvents="none";let Ft=J,Zt=ie,yr=()=>{if(!Zt.textContent)return;let nr=Ft.getBoundingClientRect(),rr=ge.getBoundingClientRect();Zt.style.left=`${nr.left-rr.left}px`,Zt.style.top=`${nr.bottom-rr.top+4}px`,Zt.style.display="block"},Wr=()=>{Zt.style.display="none"};J.addEventListener("mouseenter",yr),J.addEventListener("mouseleave",Wr),J.appendChild(Ae)}let be=b("div","persona-flex-1");Ce=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let le=b("option","");le.value="",le.textContent="All events (0)",Ce.appendChild(le),_e=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),_e.type="button",_e.title="Copy All";let Ke=he("clipboard-copy","12px","currentColor",1.5);Ke&&_e.appendChild(Ke);let Lt=b("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",_e.appendChild(Lt),J&&H.appendChild(J),H.appendChild(be),H.appendChild(Ce),H.appendChild(_e);let Et=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ws(Et,L==null?void 0:L.searchBar);let vt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&Rt.appendChild(vt),V=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),ws(V,L==null?void 0:L.searchInput),V.type="text",V.placeholder="Search event payloads...",X=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),X.type="button",X.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&X.appendChild(Qt),Et.appendChild(Rt),Et.appendChild(V),Et.appendChild(X),ge.appendChild(H),ge.appendChild(Et),ie&&ge.appendChild(ie),ge}let Je,et=s.find(ge=>ge.renderEventStreamToolbar);if(et!=null&&et.renderEventStreamToolbar&&o){let ge=et.renderEventStreamToolbar({config:o,defaultRenderer:()=>Se(),eventCount:e.getSize(),filteredCount:0,onFilterChange:H=>{C=H,ye(),Ct()},onSearchChange:H=>{P=H,ye(),Ct()}});Je=ge!=null?ge:Se()}else Je=Se();let Wt=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Wt.style.display="none";function ft(){if(!a||!Ae||!J)return;let ge=a(),H=Wv(ge);Ae.textContent=H;let be=Rv(ge);ie&&(ie.textContent=be,be||(ie.style.display="none")),J.setAttribute("aria-label",be?`Throughput: ${H}, ${be}`:`Throughput: ${H}`)}let rt=b("div","persona-flex-1 persona-min-h-0 persona-relative"),ue=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ue.style.height="100%";let Q=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ws(Q,L==null?void 0:L.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let it=he(c,"14px","currentColor",2);it&&Q.appendChild(it);let je=b("span","");je.textContent=u,Q.appendChild(je);let Te=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",rt.appendChild(ue),rt.appendChild(Te),rt.appendChild(Q),M.setAttribute("tabindex","0"),M.appendChild(Je),M.appendChild(Wt),M.appendChild(rt);function we(){let ge=e.getAll(),H={};for(let Et of ge)H[Et.type]=(H[Et.type]||0)+1;let be=Object.keys(H).sort(),le=be.length!==_.length||!be.every((Et,vt)=>Et===_[vt]),gt=!le&&be.some(Et=>H[Et]!==I[Et]),Ke=ge.length!==Object.values(I).reduce((Et,vt)=>Et+vt,0);if(!le&&!gt&&!Ke||(_=be,I=H,!Ce))return;let Lt=Ce.value;if(Ce.options[0].textContent=`All events (${ge.length})`,le){for(;Ce.options.length>1;)Ce.remove(1);for(let Et of be){let vt=b("option","");vt.value=Et,vt.textContent=`${Et} (${H[Et]||0})`,Ce.appendChild(vt)}Lt&&be.includes(Lt)?Ce.value=Lt:Lt&&(Ce.value="",C="")}else for(let Et=1;Et<Ce.options.length;Et++){let vt=Ce.options[Et];vt.textContent=`${vt.value} (${H[vt.value]||0})`}}function Ye(){let ge=e.getAll();if(C&&(ge=ge.filter(H=>H.type===C)),P){let H=P.toLowerCase();ge=ge.filter(be=>be.type.toLowerCase().includes(H)||be.payload.toLowerCase().includes(H))}return ge}function qt(){return C!==""||P!==""}function ye(){$=0,te=0,N.resume(),Q.style.display="none"}function pe(ge){ae.has(ge)?ae.delete(ge):ae.add(ge),ce=ge;let H=ue.scrollTop,be=N.isFollowing();Le=!0,N.pause(),Ct(),ue.scrollTop=H,be&&N.resume(),Le=!1}function wn(){return yo(ue,50)}function Ct(){Ee=Date.now(),de=!1,ft(),we();let ge=e.getEvictedCount();ge>0?(Wt.textContent=`${ge.toLocaleString()} older events truncated`,Wt.style.display=""):Wt.style.display="none",k=Ye();let H=k.length,be=e.getSize()>0;H===0&&be&&qt()?(Te.textContent=P?`No events matching '${P}'`:"No events matching filter",Te.style.display="",ue.style.display="none"):(Te.style.display="none",ue.style.display=""),_e&&(_e.title=qt()?`Copy Filtered (${H})`:"Copy All"),d&&!N.isFollowing()&&H>$&&(te+=H-$,je.textContent=u?`${u}${te>0?` (${te})`:""}`:"",Q.style.display=""),$=H;let le=e.getAll(),gt=le.length>0?le[0].timestamp:0,Ke=new Set(k.map(vt=>vt.id));for(let vt of ae)Ke.has(vt)||ae.delete(vt);let Lt=C!==ne||P!==re,Et=fe.size===0&&k.length>0;if(Lt||Et||k.length===0){ue.innerHTML="",fe.clear();let vt=document.createDocumentFragment();for(let Rt=0;Rt<k.length;Rt++){let Qt=Zi(k[Rt],Rt,gt,g,ae,pe,s,o);fe.set(k[Rt].id,Qt),vt.appendChild(Qt)}ue.appendChild(vt),ne=C,re=P,ce=null}else{if(ce!==null){let Rt=fe.get(ce);if(Rt&&Rt.parentNode===ue){let Qt=k.findIndex(Ft=>Ft.id===ce);if(Qt>=0){let Ft=Zi(k[Qt],Qt,gt,g,ae,pe,s,o);ue.insertBefore(Ft,Rt),Rt.remove(),fe.set(ce,Ft)}}ce=null}let vt=new Set(k.map(Rt=>Rt.id));for(let[Rt,Qt]of fe)vt.has(Rt)||(Qt.remove(),fe.delete(Rt));for(let Rt=0;Rt<k.length;Rt++){let Qt=k[Rt];if(!fe.has(Qt.id)){let Ft=Zi(Qt,Rt,gt,g,ae,pe,s,o);fe.set(Qt.id,Ft),ue.appendChild(Ft)}}}N.isFollowing()&&(ue.scrollTop=ue.scrollHeight)}function gn(){if(Date.now()-Ee>=Tv){Y!==null&&(cancelAnimationFrame(Y),Y=null),Ct();return}de||(de=!0,Y=requestAnimationFrame(()=>{Y=null,Ct()}))}let fr=(ge,H)=>{if(!_e)return;_e.innerHTML="";let be=he(ge,"12px","currentColor",1.5);be&&_e.appendChild(be);let le=b("span","persona-text-xs");le.textContent="Copy All",_e.appendChild(le),setTimeout(()=>{_e.innerHTML="";let gt=he("clipboard-copy","12px","currentColor",1.5);gt&&_e.appendChild(gt);let Ke=b("span","persona-text-xs");Ke.textContent="Copy All",_e.appendChild(Ke),_e.disabled=!1},H)},hr=async()=>{if(_e){_e.disabled=!0;try{let ge;qt()?ge=k:t?(ge=await t(),ge.length===0&&(ge=e.getAll())):ge=e.getAll();let H=ge.map(be=>{try{return JSON.parse(be.payload)}catch{return be.payload}});await navigator.clipboard.writeText(JSON.stringify(H,null,2)),fr("check",1500)}catch{fr("x",1500)}}},Ue=()=>{Ce&&(C=Ce.value,ye(),Ct())},E=()=>{!V||!X||(X.style.display=V.value?"":"none",U&&clearTimeout(U),U=setTimeout(()=>{P=V.value,ye(),Ct()},150))},me=()=>{!V||!X||(V.value="",P="",X.style.display="none",U&&clearTimeout(U),ye(),Ct())},Me=()=>{if(Le)return;let ge=ue.scrollTop,{action:H,nextLastScrollTop:be}=Fa({following:N.isFollowing(),currentScrollTop:ge,lastScrollTop:Pe,nearBottom:wn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=be,H==="resume"?(N.resume(),te=0,Q.style.display="none"):H==="pause"&&(N.pause(),d&&(je.textContent=u,Q.style.display=""))},ke=ge=>{let H=Oa({following:N.isFollowing(),deltaY:ge.deltaY,nearBottom:wn(),resumeWhenNearBottom:!0});H==="pause"?(N.pause(),d&&(je.textContent=u,Q.style.display="")):H==="resume"&&(N.resume(),te=0,Q.style.display="none")},Re=()=>{d&&(ue.scrollTop=ue.scrollHeight,N.resume(),te=0,Q.style.display="none")},tt=ge=>{let H=ge.target;if(!H||H.closest("button"))return;let be=H.closest("[data-event-id]");if(!be)return;let le=be.getAttribute("data-event-id");le&&pe(le)},Qe=ge=>{if((ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),V==null||V.focus(),V==null||V.select();return}ge.key==="Escape"&&(V&&document.activeElement===V?(me(),V.blur(),M.focus()):r&&r())};_e&&_e.addEventListener("click",hr),Ce&&Ce.addEventListener("change",Ue),V&&V.addEventListener("input",E),X&&X.addEventListener("click",me),ue.addEventListener("scroll",Me),ue.addEventListener("wheel",ke,{passive:!0}),ue.addEventListener("click",tt),Q.addEventListener("click",Re),M.addEventListener("keydown",Qe);function ht(){U&&clearTimeout(U),Y!==null&&(cancelAnimationFrame(Y),Y=null),de=!1,fe.clear(),_e&&_e.removeEventListener("click",hr),Ce&&Ce.removeEventListener("change",Ue),V&&V.removeEventListener("input",E),X&&X.removeEventListener("click",me),ue.removeEventListener("scroll",Me),ue.removeEventListener("wheel",ke),ue.removeEventListener("click",tt),Q.removeEventListener("click",Re),M.removeEventListener("keydown",Qe)}return{element:M,update:gn,destroy:ht}}}function Fm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let h=document.createElement("span");h.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",h.style.backgroundColor="var(--persona-primary, #171717)",h.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(h);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(c.append(u,g),i.append(d,c),o==="complete"){let h=document.createElement("button");h.type="button",h.textContent="Download",h.title=`Download ${t}`,h.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",h.style.border="1px solid var(--persona-border, #e5e7eb)",h.style.color="var(--persona-text, #1f2937)",h.style.backgroundColor="transparent",h.style.cursor="pointer",h.setAttribute("data-download-artifact",r),i.append(h)}return i}var Om=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Fm(n,e)});if(u)return u}return Fm(n,e)};var el=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Vo=new el;Vo.register("PersonaArtifactCard",Om);function Bv(n){var o;let e=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=b("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function _m(n,e){var _e,V,X,Ae;let t=(V=(_e=n.features)==null?void 0:_e.artifacts)==null?void 0:V.layout,o=((X=t==null?void 0:t.toolbarPreset)!=null?X:"default")==="document",s=(Ae=t==null?void 0:t.panePadding)==null?void 0:Ae.trim(),a=n.markdown?ya(n.markdown):null,i=ba(n.sanitize),d=J=>{let ie=a?a(J):mo(J);return i?i(ie):ie},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let g=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),o&&g.classList.add("persona-artifact-pane-document");let h=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");h.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&h.classList.add("persona-artifact-toolbar-document");let m=b("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let w="rendered",T=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),B=o?vn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vn({icon:"eye",label:"Rendered view"}),S=o?vn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vn({icon:"code-2",label:"Source"}),L=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,k=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,C=t==null?void 0:t.documentToolbarCopyMenuItems,P=!!(k&&C&&C.length>0),U=null,_,I=null,$=null;if(o&&(M||k)&&!P){if(_=M?Ui({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let J=he("chevron-down",14,"currentColor",2);J&&_.appendChild(J)}}else o&&P?(U=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=M?Ui({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=vn({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(_,I)):o?_=vn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=vn({icon:"copy",label:"Copy"});let N=o?vn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vn({icon:"refresh-cw",label:"Refresh"}),te=o?vn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vn({icon:"x",label:"Close"}),Ee=()=>{var et,Wt,ft;let J=(et=fe.find(rt=>rt.id===ne))!=null?et:fe[fe.length-1],ie=(Wt=J==null?void 0:J.id)!=null?Wt:null,Se=(J==null?void 0:J.artifactType)==="markdown"&&(ft=J.markdown)!=null?ft:"",Je=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Se,jsonPayload:Je,id:ie}},de=async()=>{var et;let{markdown:J,jsonPayload:ie}=Ee(),Se=(et=fe.find(Wt=>Wt.id===ne))!=null?et:fe[fe.length-1],Je=(Se==null?void 0:Se.artifactType)==="markdown"?J:Se?ie:"";try{await navigator.clipboard.writeText(Je)}catch{}};if(_.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&P){let{markdown:ie,jsonPayload:Se,id:Je}=Ee();try{await J({actionId:"primary",artifactId:Je,markdown:ie,jsonPayload:Se})}catch{}return}await de()}),I&&(C!=null&&C.length)){let J=()=>{var Se;return(Se=g.closest("[data-persona-root]"))!=null?Se:document.body},ie=()=>{$=ys({items:C.map(Se=>({id:Se.id,label:Se.label})),onSelect:async Se=>{let{markdown:Je,jsonPayload:et,id:Wt}=Ee(),ft=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ft?await ft({actionId:Se,artifactId:Wt,markdown:Je,jsonPayload:et}):Se==="markdown"||Se==="md"?await navigator.clipboard.writeText(Je):Se==="json"||Se==="source"?await navigator.clipboard.writeText(et):await navigator.clipboard.writeText(Je||et)}catch{}},anchor:U!=null?U:I,position:"bottom-right",portal:J()})};g.isConnected?ie():requestAnimationFrame(ie),I.addEventListener("click",Se=>{Se.stopPropagation(),$==null||$.toggle()})}N.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}ce()}),te.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let Y=()=>{o&&(B.setAttribute("aria-pressed",w==="rendered"?"true":"false"),S.setAttribute("aria-pressed",w==="source"?"true":"false"))};B.addEventListener("click",()=>{w="rendered",Y(),ce()}),S.addEventListener("click",()=>{w="source",Y(),ce()});let Le=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(h.replaceChildren(),T.append(B,S),U?L.append(U,N,te):L.append(_,N,te),h.append(T,Le,L),Y()):(h.appendChild(m),h.appendChild(v)),s&&(h.style.paddingLeft=s,h.style.paddingRight=s);let Pe=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ae=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ae.style.padding=s),g.appendChild(h),g.appendChild(Pe),g.appendChild(ae);let fe=[],ne=null,re=!1,ce=()=>{var Je,et,Wt,ft;let J=o&&fe.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let rt of fe){let ue=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ue.type="button",ue.textContent=rt.title||rt.id.slice(0,8),rt.id===ne&&ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),ue.addEventListener("click",()=>e.onSelect(rt.id)),Pe.appendChild(ue)}ae.replaceChildren();let ie=ne&&fe.find(rt=>rt.id===ne)||fe[fe.length-1];if(!ie)return;if(o){let rt=ie.artifactType==="markdown"?"MD":(Je=ie.component)!=null?Je:"Component",Q=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Q} \xB7 ${rt}`}else m.textContent="Artifacts";if(ie.artifactType==="markdown"){if(o&&w==="source"){let ue=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ue.textContent=(et=ie.markdown)!=null?et:"",ae.appendChild(ue);return}let rt=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");rt.innerHTML=d((Wt=ie.markdown)!=null?Wt:""),ae.appendChild(rt);return}let Se=ie.component?Vo.get(ie.component):void 0;if(Se){let ue={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Q=Se((ft=ie.props)!=null?ft:{},ue);if(Q){ae.appendChild(Q);return}}catch{}}ae.appendChild(Bv(ie))},Ce=()=>{var ie;let J=fe.length>0;if(g.classList.toggle("persona-hidden",!J),c){let Se=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,et=((ie=Se==null?void 0:Se.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&et&&re?(c.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:c,update(J){var ie,Se,Je;fe=J.artifacts,ne=(Je=(Se=J.selectedId)!=null?Se:(ie=J.artifacts[J.artifacts.length-1])==null?void 0:ie.id)!=null?Je:null,fe.length>0&&(re=!0),ce(),Ce()},setMobileOpen(J){re=J,!J&&c?(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):Ce()}}}function tr(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function $m(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!tr(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function Dv(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ri(n,e){var d,c,u,g,h,m,v,w,T,B;if(!tr(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),Dv(n),$m(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(g=t==null?void 0:t.paneWidth)!=null?g:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(h=t==null?void 0:t.paneMaxWidth)!=null?h:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(w=t==null?void 0:t.documentToolbarIconColor)==null?void 0:w.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(B=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:B.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),$m(n,e)}var Um=["panel","seamless"];function oi(n,e){var i,d,c,u,g,h;for(let m of Um)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!tr(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Um.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=t==null?void 0:t.paneShadow)==null?void 0:g.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((h=t.unifiedSplitOuterRadius)==null?void 0:h.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function zm(n,e){var t,r,o;return!e||!tr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Nv(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function Fv(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function Ov(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function _v(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function qm(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function jm(n,e,t,r,o,s){let a=Nv(o,200),i=_v(e,t,r,200);i=Math.max(a,i);let d=Fv(s);return d!==null&&(i=Math.min(i,d)),Ov(n,a,i)}var Vm={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"}},tl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,w,T;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(w=Vm[a])!=null?w:Vm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let B=b("p","persona-text-sm persona-text-persona-muted");B.textContent=i.description,d.appendChild(B)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(B=>{var C,P;let S=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${e.id}-${a}-${B.name}`;let L=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=B.label,S.appendChild(L);let M=(C=B.type)!=null?C:"text",k;M==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=M),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=`${e.id}-${a}-${B.name}`,k.name=B.name,k.placeholder=(P=B.placeholder)!=null?P:"",B.required&&(k.required=!0),S.appendChild(k),u.appendChild(S)});let g=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=i.submitLabel)!=null?T:"Submit",g.appendChild(h),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async B=>{var k,C;B.preventDefault();let S=(k=t.formEndpoint)!=null?k:"/form",L=new FormData(u),M={};L.forEach((P,U)=>{M[U]=P}),M.type=a,m.disabled=!0,h.textContent="Submitting\u2026";try{let P=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let U=await P.json();h.textContent=(C=U.message)!=null?C:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await r.sendMessage(String(U.nextPrompt))}catch(P){h.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var nl=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},rl=new nl;var Km=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var $v=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Uv=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},sl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=$v(n),t=Uv(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ol=n=>typeof n=="string"?n:n==null?"":String(n),ca={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:ol(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=ol(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ol(t.text)}}},Gm=n=>Array.isArray(n)?n.map(e=>String(e)):[],al=n=>{let e=new Set(Gm(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Gm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.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!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let u=()=>{n.emit("action:resubmit",d)},g=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let h=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:h,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var zv=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},qv=n=>n.map(e=>({...e,streaming:!1})),jv=n=>n.map(e=>({...e,status:"complete"})),Qm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?zv(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?qv(t.messages):void 0,artifacts:t.artifacts?jv(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as tS,STR as nS,OBJ as rS}from"partial-json";function Xm(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Vo.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function Jm(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function Ym(n){let e=Jm(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Zm(n){let e=Jm(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var Vv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function eg(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Vv}=n,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,m.appendChild(w),h.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let C=1;C<=5;C++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),P.title=c[C-1],P.dataset.rating=String(C),P.innerHTML=`
|
|
33
|
+
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Ft(s),p=n.querySelector("[data-role='launcher-title']");if(p){let I=a.title??"Chat Assistant";p.textContent=I,p.setAttribute("title",I)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let I=a.subtitle??"Here to help you get answers fast";d.textContent=I,d.setAttribute("title",I)}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 I=a.agentIconSize??"40px";if(u.style.height=I,u.style.width=I,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 H=parseFloat(I)||24,q=ae(a.agentIconName,H*.6,"var(--persona-text-inverse, #ffffff)",2);q?(u.appendChild(q),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 I=a.agentIconSize??"40px";w.style.height=I,w.style.width=I,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 I=a.callToActionIconSize??"32px";f.style.height=I,f.style.width=I,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 H=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,H=(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 q=parseFloat(I)||24,U=Math.max(q-H,8),$=ae(a.callToActionIconName,U,"currentColor",2);$?f.appendChild($):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&wn[a.position]?wn[a.position]:wn["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??Ut));let W="1px solid var(--persona-border, #e5e7eb)",T="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??W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,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",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}};var Sp=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=Cp(t),s=Ap(t,e),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}}},tl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>el(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=el(t,n);return{instance:r,element:r.element}};var Fy=t=>{switch(t){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}},Oy=(t,e)=>{if(!t)return null;let n=Fy(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},_y=(t,e)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},$y=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},nl=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},ol=320,Mp=320,Uy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),zy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),jy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),qy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Vy=(t,e,n)=>{if(t.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let d=m("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=`${ol}px`,d.style.maxHeight=`${Mp}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}),$y(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}},Ky=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!nl(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ol}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Gy=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!nl(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ol}px`,r.style.maxHeight=`${Mp}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Xy=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!nl(o.data))return;let r=m("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",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},us=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.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",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},Qy=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:us};if(e){let r=e(o);if(r!==null)return r}return us()},Jy=(t,e)=>{let n=m("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=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=e==="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(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Tp=(t,e,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Yy=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Zy=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=m("div");return v.style.display="none",v.id=`actions-${t.id}`,v.setAttribute("data-actions-for",t.id),v}let l=e.visibility??"hover",p=e.align??"right",d=e.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=m("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-${t.id}`,w.setAttribute("data-actions-for",t.id);let f=(v,x,P)=>{let W=Wt({icon:v,label:x,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",P),W};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},rl=(t,e,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=Yy(t.role,l),x=m("div",v.join(" "));x.id=`bubble-${t.id}`,x.setAttribute("data-message-id",t.id),x.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=Uy(t),W=t.content?.trim()??"",I=P.length>0&&W===la,H=ka(s?.widgetConfig?.features?.streamAnimation),q=s?.widgetConfig?.features?.streamAnimation?.plugins,U=t.role==="assistant"&&H.type!=="none"?dr(H.type,q):null,$=t.role==="assistant"&&U?.isAnimating?.(t)===!0,C=t.role==="assistant"&&U!==null&&(!!t.streaming||$);C&&U?.bubbleClass&&x.classList.add(U.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),t.streaming&&j.classList.add("persona-content-streaming"),C&&U&&(U.containerClass&&j.classList.add(U.containerClass),j.style.setProperty("--persona-stream-step",`${H.speed}ms`),j.style.setProperty("--persona-stream-duration",`${H.duration}ms`));let J=C?La(t.content??"",H.buffer,U,t,!!t.streaming):t.content??"",D=e({text:J,message:t,streaming:!!t.streaming,raw:t.rawContent}),_=D;C&&U?.wrap==="char"?_=as(D,"char",t.id,{skipTags:U.skipTags}):C&&U?.wrap==="word"&&(_=as(D,"word",t.id,{skipTags:U.skipTags}));let ce=null;if(I?(ce=document.createElement("div"),ce.innerHTML=_,ce.style.display="none",j.appendChild(ce)):j.innerHTML=_,C&&U?.useCaret&&!I&&W){let Z=Pa(),be=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=be[be.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(Z,ve.nextSibling);else{let fe=j.lastElementChild;fe?fe.appendChild(Z):j.appendChild(Z)}}if(u&&f==="inline"&&t.createdAt){let Z=Tp(t,d,"span");Z.classList.add("persona-timestamp-inline");let be=j.lastElementChild;be?be.appendChild(Z):j.appendChild(Z)}if(P.length>0){let Z=Vy(P,!I&&!!W,()=>{I&&ce&&(ce.style.display="")});Z?x.appendChild(Z):I&&ce&&(ce.style.display="")}let he=zy(t);if(he.length>0){let Z=Ky(he);Z&&x.appendChild(Z)}let Me=jy(t);if(Me.length>0){let Z=Gy(Me);Z&&x.appendChild(Z)}let Ce=qy(t);if(Ce.length>0){let Z=Xy(Ce);Z&&x.appendChild(Z)}if(x.appendChild(j),u&&f==="below"&&t.createdAt){let Z=Tp(t,d);Z.classList.add("persona-mt-1"),x.appendChild(Z)}let te=t.role==="assistant"?Oy(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Z=!!(J&&J.trim()),be=H.placeholder==="skeleton",ve=be&&H.buffer==="line"&&Z;if(Z)ve&&x.appendChild(is());else if(be)x.appendChild(is());else{let fe=Qy("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);fe&&x.appendChild(fe)}}if(te&&t.stopReason&&!t.streaming&&(W||(j.style.display="none"),x.appendChild(_y(t.stopReason,te))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=Zy(t,o,r);x.appendChild(Z)}if(!c||t.role==="system")return x;let Y=m("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),le=Jy(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Y.append(x,le):Y.append(le,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y};var pr=new Set,eb=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),tb=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
34
|
+
`):""},Ep=(t,e)=>{let n=pr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.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")},sl=(t,e)=>{let n=t.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&pr.has(t.id),l=n.status!=="complete",p=tb(t,r.previewMaxLines??3),d=m("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=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",f=e?.reasoning??{},v=String(n.startedAt??Date.now()),x=()=>{let he=m("span","");return he.setAttribute("data-tool-elapsed",v),he.textContent=ra(n),he},P=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:ra(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 W=m("span","persona-text-xs persona-text-persona-primary");W.textContent=gd(n),c.appendChild(W);let T=r.loadingAnimation??"none",I=f.activeTextTemplate,H=f.completeTextTemplate,q=l?I:H,U=P instanceof HTMLElement,$=(he,Me)=>{u.textContent="";let Ce=sa(he,""),te=0;for(let ge of Ce){let Y=ge.styles.length>0?(()=>{let le=m("span",ge.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(ge.isDuration&&l)Y.appendChild(x());else{let le=ge.isDuration?ra(n):ge.text;Me?te=no(Y,le,te):Y.appendChild(document.createTextNode(le))}}};if(!U&&q)if(W.style.display="none",u.style.display="",l&&T!=="none"){let he=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),T==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),$(q,!1)):(u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),$(q,!0))}else $(q,!1);else if(!U&&l&&T!=="none"){u.style.display="";let he=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Me=u.textContent||w;u.textContent="",no(u,Me,0)}n.status==="complete"&&(u.style.display="none")}else U||(n.status==="complete"?u.style.display="none":u.style.display="");let C=null;if(s){C=m("div","persona-flex persona-items-center");let Me=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?C.appendChild(Me):C.textContent=a?"Hide":"Show";let Ce=m("div","persona-flex persona-items-center persona-ml-auto");Ce.append(C),d.append(c,Ce)}else d.append(c);let j=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","reasoning"),j.style.display="none",j.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let he=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});eb(j,he)||(j.textContent=p),j.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,j),o;let J=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");J.style.display=a?"":"none";let D=n.chunks.join(""),_=m("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"),J.appendChild(_),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),C){C.innerHTML="";let Me=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Me?C.appendChild(Me):C.textContent=a?"Hide":"Show"}J.style.display=a?"":"none",j.style.display=a?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(d,j,J),o};var ur=new Set,nb=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ob=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
|
|
35
|
+
`);let r=eo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
36
|
+
`):""},al=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},rb=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=ob(t,o?.previewMaxLines??3),a=n?md(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=Di(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Di(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},kp=(t,e,n)=>{let o=ur.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.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")},il=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.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=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&ur.has(t.id),{summary:p,previewText:d,isActive:c}=rb(t,e),u=m("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=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),x=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",v),D.textContent=qr(n),D},P=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:qr(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(f.textContent=P,w.appendChild(f)):P instanceof HTMLElement?w.appendChild(P):(f.textContent=p,w.appendChild(f));let W=s.loadingAnimation??"none",T=o.activeTextTemplate,I=o.completeTextTemplate,H=c?T:I,q=P instanceof HTMLElement,U=(D,_)=>{f.textContent="";let ce=n.name?.trim()||"tool",he=sa(D,ce),Me=0;for(let Ce of he){let te=Ce.styles.length>0?(()=>{let ge=m("span",Ce.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(ge),ge})():f;if(Ce.isDuration&&c)te.appendChild(x());else{let ge=Ce.isDuration?qr(n):Ce.text;_?Me=no(te,ge,Me):te.appendChild(document.createTextNode(ge))}}};if(!q)if(c&&W!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),W==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),H&&U(H,!1);else if(f.classList.add(`persona-tool-loading-${W}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),W==="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)),H)U(H,!0);else{let _=f.textContent||p;f.textContent="",no(f,_,0)}}else H&&U(H,!1);let $=null;if(a){$=m("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);_?$.appendChild(_):$.textContent=l?"Hide":"Show";let ce=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ce.append($),u.append(w,ce)}else u.append(w);let C=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","tool"),C.style.display="none",C.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:d,isActive:c,config:e??{}});nb(C,D)||(C.textContent=d),C.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let j=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(j.style.display=l?"":"none",o.contentBackgroundColor&&(j.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(j.style.color=o.contentTextColor),o.contentPaddingX&&(j.style.paddingLeft=o.contentPaddingX,j.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(j.style.paddingTop=o.contentPaddingY,j.style.paddingBottom=o.contentPaddingY),n.name){let D=m("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,j.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),_=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Arguments";let ce=m("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");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",al(ce,o),ce.textContent=eo(n.args),D.append(_,ce),j.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),_=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Activity";let ce=m("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");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",al(ce,o),ce.textContent=n.chunks.join(""),D.append(_,ce),j.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),_=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Result";let ce=m("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");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",al(ce,o),ce.textContent=eo(n.result),D.append(_,ce),j.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,j.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),$){$.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",_=ae(l?"chevron-up":"chevron-down",16,D,2);_?$.appendChild(_):$.textContent=l?"Hide":"Show"}j.style.display=l?"":"none",C.style.display=l?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,j),r};var Do=new Map,Ua=t=>{let n=(t.startsWith(Bn)?t.slice(Bn.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Lp=t=>t?.approval!==!1?t?.approval:void 0,Pp=(t,e)=>{let n=Lp(e)?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},Ip=(t,e,n)=>{let o=Lp(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Rp=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Pp(t,n);Ip(o,s,n),r.style.display=s?"":"none"};var za=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.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=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=m("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=m("div","persona-flex-1 persona-min-w-0"),w=m("div","persona-flex persona-items-center persona-gap-2"),f=m("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 $=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",n.status),n.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):n.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):n.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),w.appendChild($)}u.appendChild(w);let x=n.toolType==="webmcp"||n.toolName.startsWith(Bn)?$r(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}:{}}),W=!n.toolName,T=P||(W?n.description:`The assistant wants to use \u201C${x??Ua(n.toolName)}\u201D.`),I=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(I.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=T,u.appendChild(I),n.reason){let $=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");$.setAttribute("data-approval-reason","true"),o?.reasonColor?$.style.color=o.reasonColor:o?.descriptionColor&&($.style.color=o.descriptionColor);let C=m("span","persona-font-medium");C.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,$.appendChild(C),$.appendChild(document.createTextNode(n.reason)),u.appendChild($)}let H=o?.detailsDisplay??"collapsed",q=!!n.description&&!W,U=q||!!n.parameters;if(H!=="hidden"&&U){let $=Pp(t.id,e),C=m("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");C.type="button",C.setAttribute("data-expand-header","true"),C.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(C.style.color=o.descriptionColor);let j=m("span");j.setAttribute("data-approval-details-label","true");let J=m("span","persona-inline-flex persona-items-center");J.setAttribute("data-approval-details-chevron","true"),C.append(j,J),Ip(C,$,e),u.appendChild(C);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=$?"":"none",q){let _=m("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 _=m("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=eo(n.parameters),D.appendChild(_)}u.appendChild(D)}if(r){let $=m("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let C=m("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");C.type="button",C.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",C.style.color=o?.approveButtonTextColor??"#ffffff",C.setAttribute("data-approval-action","approve");let j=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);j&&(j.style.marginRight="4px",C.appendChild(j));let J=document.createTextNode(o?.approveLabel??"Approve");C.appendChild(J);let D=m("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 ce=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(ce),$.append(C,D),u.appendChild($)}return a.append(l,u),s.appendChild(a),s};function sb(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Wp(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:l,onDismiss:p}=t,d=t.container??sb(e),c=!1,u=null,w=()=>{if(!c)return;let x=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${x.width}px`);let P=o==="top-start"||o==="top-end"?x.top-r-n.getBoundingClientRect().height:x.bottom+r,W=o==="bottom-end"||o==="top-end"?x.right-n.getBoundingClientRect().width:x.left;n.style.top=`${P}px`,n.style.left=`${W}px`},f=()=>{c&&(c=!1,u&&(u(),u=null),n.remove())},v=()=>{if(c)return;c=!0,a!=null&&(n.style.zIndex=String(a)),d.appendChild(n),w();let x=(e.ownerDocument??document).defaultView??window,P=e.ownerDocument??document,W=()=>{if(!e.isConnected){f(),p?.("anchor-removed");return}w()},T=H=>{let q=typeof H.composedPath=="function"?H.composedPath():[];q.includes(n)||q.includes(e)||(f(),p?.("outside"))},I=x.setTimeout(()=>{P.addEventListener("pointerdown",T,!0)},0);x.addEventListener("scroll",W,!0),x.addEventListener("resize",W),u=()=>{x.clearTimeout(I),P.removeEventListener("pointerdown",T,!0),x.removeEventListener("scroll",W,!0),x.removeEventListener("resize",W)},l?.()};return{get isOpen(){return c},open:v,close:f,toggle:()=>c?f():v(),reposition:w,destroy:f}}function Bp(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var ab=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Hp=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},No=(t,e)=>{Hp(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},ib=t=>t?.approval!==!1?t?.approval:void 0,lb=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},ll=t=>{let e=m("span","persona-approval-kbd");return e.textContent=t,e},cb=(t,e)=>{let n=m("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Bn)?$r(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??Ua(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.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},db=t=>{let e=m("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&e.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=t.toolName?Ua(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},pb=(t,e,n,o,r,s,a)=>{let l=m("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.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&&lb(e.id,o),f=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",x=m("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:f)):x.setAttribute("data-static","true");let P=m("span","persona-approval-logo"),W=ae("shield-check",16,"currentColor",2);W&&P.appendChild(W),x.appendChild(P);let T=cb(n,o);if(u){let C=m("span","persona-approval-toggle");C.setAttribute("aria-hidden","true");let j=ae("chevron-down",14,"currentColor",2);j&&C.appendChild(j),T.append(" "),T.appendChild(C)}x.appendChild(T),l.appendChild(x);let I=m("div","persona-approval-body");if(u){let C=m("div","persona-approval-details");if(C.setAttribute("data-role","params"),C.hidden=!w,d){let j=m("p","persona-approval-desc");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,C.appendChild(j)}if(c){let j=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(j.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.textContent=eo(n.parameters),C.appendChild(j)}I.appendChild(C)}if(n.reason){let C=m("p","persona-approval-reason");o?.reasonColor?C.style.color=o.reasonColor:o?.descriptionColor&&(C.style.color=o.descriptionColor);let j=m("span","persona-approval-reason-label");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,C.append(j,document.createTextNode(n.reason)),I.appendChild(C)}let H=m("div","persona-approval-actions"),q=null,U=C=>{o?.approveButtonColor&&(C.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(C.style.color=o.approveButtonTextColor)},$=m("button","persona-approval-deny");if($.type="button",$.setAttribute("data-action","deny"),o?.denyButtonColor&&($.style.background=o.denyButtonColor),o?.denyButtonTextColor&&($.style.color=o.denyButtonTextColor),$.append(o?.denyLabel??"Deny"),a){let C=m("div","persona-approval-split"),j=m("button","persona-approval-primary");j.type="button",j.setAttribute("data-action","always"),U(j),j.append(o?.approveLabel??"Always allow",ll("\u23CE"));let J=m("button","persona-approval-caret");J.type="button",J.setAttribute("data-action","toggle-menu"),J.setAttribute("aria-label","More options"),U(J);let D=ae("chevron-down",15,"currentColor",2);D&&J.appendChild(D),C.append(j,J),H.append(C,$),$.append(ll("Esc"));let _=m("div","persona-approval-menu"),ce=m("button","persona-approval-menu-item");ce.type="button",ce.append("Allow once",ll("\u2318\u23CE")),_.appendChild(ce),q=Wp({anchor:C,content:_,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,q),ce.addEventListener("click",()=>{No(t,e.id),r()})}else{let C=m("button","persona-approval-primary persona-approval-primary--solo");C.type="button",C.setAttribute("data-action","allow"),U(C),C.append(o?.approveLabel??"Allow"),H.append(C,$)}return I.appendChild(H),l.appendChild(I),l.addEventListener("click",C=>{let j=C.target instanceof Element?C.target.closest("[data-action]"):null;if(!j)return;let J=j.getAttribute("data-action");if(J==="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:f),Do.set(e.id,_)}return}if(J==="toggle-menu"){q?.toggle();return}if(J==="always"){No(t,e.id),r({remember:!0});return}if(J==="allow"){No(t,e.id),r();return}if(J==="deny"){No(t,e.id),s();return}}),l},Dp=()=>{let t=ab();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=ib(a);if(l.status!=="pending"){if(No(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return db(l)}Hp(t,o.id);let d=p?.enableAlwaysAllow===!0,c=pb(t,o,l,p,r,s,d);if(d){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=w=>{Bp(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),No(t,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])No(t,o);t.latestPendingApprovalId=null}}};var Np=t=>{let e=[],n=null;return{buttons:e,render:(r,s,a,l,p,d)=>{t.innerHTML="",e.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(P=>P.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 x=m("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");x.type="button",x.textContent=v,x.disabled=w,p?.fontFamily&&(x.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(x.style.fontWeight=p.fontWeight),p?.paddingX&&(x.style.paddingLeft=p.paddingX,x.style.paddingRight=p.paddingX),p?.paddingY&&(x.style.paddingTop=p.paddingY,x.style.paddingBottom=p.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),e.push(x)}),t.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var fs=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;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=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}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 gs=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,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,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},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((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var ub=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),fb=new Set(["step_start","execution_start"]),gb=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),mb=new Set(["step_complete","agent_turn_complete"]),hb=new Set(["flow_complete","agent_complete"]),Fp=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),_p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),rn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Fo=(t,e)=>{let n=t[e];return _p(n)?n:void 0};function cl(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ja(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function yb(t,e){return typeof e.type=="string"?e.type:t}function bb(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function vb(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Op(t){let e=Fo(t,"result"),n=[Fo(t,"tokens"),Fo(t,"totalTokens"),e?Fo(e,"tokens"):void 0,Fo(t,"usage"),e?Fo(e,"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(t.outputTokens)??rn(t.completionTokens)??(e?rn(e.outputTokens)??rn(e.completionTokens):void 0)}function wb(t){let e=Fo(t,"result");return rn(t.executionTime)??rn(t.executionTimeMs)??rn(t.execution_time)??rn(t.duration)??(e?rn(e.executionTime)??rn(e.executionTimeMs):void 0)}function xb(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ms=class{constructor(e=xb){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ja(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!_p(n)){Fp.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=yb(e,n),r=this.now();if(ub.has(o)){this.startRun(r);return}if(fb.has(o)){this.run||this.startRun(r);return}if(gb.has(o)){if(!vb(o,n))return;let s=bb(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+cl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ja(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(mb.has(o)){if(!this.run)return;let s=this.run,a=Op(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+cl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:ja(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(hb.has(o)){if(!this.run)return;let s=this.run,a=Op(n),l=a??s.exactOutputTokens+cl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:ja(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Fp.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:wb(n)??o-e.startedAt}};function fr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Cb={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)"}},Ab={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Sb=["flowName","stepName","reasoningText","text","name","tool","toolName"],Tb=100;function Mb(t,e){let n={...Cb,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Ab}function Eb(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function kb(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Lb(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){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 Pb(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function Ib(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function Rb(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Wb(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Bb(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=m("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=m("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 dl(t,e,n,o,r,s,a,l){let p=r.has(t.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");fr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=m("div",""),f=m("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",t.id);let v=m("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=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=o.timestampFormat??"relative";P.textContent=W==="relative"?Eb(t.timestamp,n):kb(t.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let I=Mb(t.type,o.badgeColors),H=m("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");H.style.backgroundColor=I.bg,H.style.color=I.text,H.style.borderColor=I.text+"50",H.textContent=t.type;let q=o.descriptionFields??Sb,U=Lb(t.payload,q),$=null;U&&($=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=U);let C=m("div","persona-flex-1 persona-min-w-0"),j=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),J=ae("clipboard","12px","currentColor",1.5);return J&&j.appendChild(J),j.addEventListener("click",async D=>{D.stopPropagation(),await Pb(Ib(t)),j.innerHTML="";let _=ae("check","12px","currentColor",1.5);_&&j.appendChild(_),setTimeout(()=>{j.innerHTML="";let ce=ae("clipboard","12px","currentColor",1.5);ce&&j.appendChild(ce)},1500)}),f.appendChild(v),f.appendChild(P),T&&f.appendChild(T),f.appendChild(H),$&&f.appendChild($),f.appendChild(C),f.appendChild(j),w.appendChild(f),p&&w.appendChild(Bb(t,a,l)),w}}function $p(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,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:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return f();function f(){let v=u.classNames,x=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");fr(x,v?.panel);let P=[],W="",T="",I=null,H=[],q={},U=0,$=Ta(),C=0,j=0,J=!1,D=null,_=!1,ce=0,he=new Set,Me=new Map,Ce="",te="",ge=null,Y,le,Z,be,ve=null,fe=null,Te=null;function Ae(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=m("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(fr(z,v?.headerBar),a){fe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),fe.style.cursor="help",ve=m("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"),ve.textContent="-- tok/s",Te=m("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"),Te.style.display="none",Te.style.pointerEvents="none";let Qe=fe,io=Te,lo=()=>{if(!io.textContent)return;let ws=Qe.getBoundingClientRect(),Qt=B.getBoundingClientRect();io.style.left=`${ws.left-Qt.left}px`,io.style.top=`${ws.bottom-Qt.top+4}px`,io.style.display="block"},Ka=()=>{io.style.display="none"};fe.addEventListener("mouseenter",lo),fe.addEventListener("mouseleave",Ka),fe.appendChild(ve)}let re=m("div","persona-flex-1");Y=m("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 et=m("option","");et.value="",et.textContent="All events (0)",Y.appendChild(et),le=m("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 lt=ae("clipboard-copy","12px","currentColor",1.5);lt&&le.appendChild(lt);let V=m("span","persona-event-copy-all persona-text-xs");V.textContent="Copy All",le.appendChild(V),fe&&z.appendChild(fe),z.appendChild(re),z.appendChild(Y),z.appendChild(le);let $e=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");fr($e,v?.searchBar);let xe=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),Be=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");xe&&Be.appendChild(xe),Z=m("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"),fr(Z,v?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",be=m("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"),be.type="button",be.style.display="none";let Le=ae("x","12px","currentColor",2);return Le&&be.appendChild(Le),$e.appendChild(Be),$e.appendChild(Z),$e.appendChild(be),B.appendChild(z),B.appendChild($e),Te&&B.appendChild(Te),B}let ze,Ne=s.find(B=>B.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?ze=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ae(),eventCount:e.getSize(),filteredCount:0,onFilterChange:z=>{W=z,Ie(),ye()},onSearchChange:z=>{T=z,Ie(),ye()}})??Ae():ze=Ae();let Pe=m("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");Pe.style.display="none";function We(){if(!a||!ve||!fe)return;let B=a(),z=Rb(B);ve.textContent=z;let re=Wb(B);Te&&(Te.textContent=re,re||(Te.style.display="none")),fe.setAttribute("aria-label",re?`Throughput: ${z}, ${re}`:`Throughput: ${z}`)}let at=m("div","persona-flex-1 persona-min-h-0 persona-relative"),Oe=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Oe.style.height="100%";let Xe=m("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");fr(Xe,v?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let sn=ae(d,"14px","currentColor",2);sn&&Xe.appendChild(sn);let Et=m("span","");Et.textContent=c,Xe.appendChild(Et);let ft=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ft.style.display="none",at.appendChild(Oe),at.appendChild(ft),at.appendChild(Xe),x.setAttribute("tabindex","0"),x.appendChild(ze),x.appendChild(Pe),x.appendChild(at);function Ee(){let B=e.getAll(),z={};for(let $e of B)z[$e.type]=(z[$e.type]||0)+1;let re=Object.keys(z).sort(),et=re.length!==H.length||!re.every(($e,xe)=>$e===H[xe]),Re=!et&&re.some($e=>z[$e]!==q[$e]),lt=B.length!==Object.values(q).reduce(($e,xe)=>$e+xe,0);if(!et&&!Re&&!lt||(H=re,q=z,!Y))return;let V=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,et){for(;Y.options.length>1;)Y.remove(1);for(let $e of re){let xe=m("option","");xe.value=$e,xe.textContent=`${$e} (${z[$e]||0})`,Y.appendChild(xe)}V&&re.includes(V)?Y.value=V:V&&(Y.value="",W="")}else for(let $e=1;$e<Y.options.length;$e++){let xe=Y.options[$e];xe.textContent=`${xe.value} (${z[xe.value]||0})`}}function me(){let B=e.getAll();if(W&&(B=B.filter(z=>z.type===W)),T){let z=T.toLowerCase();B=B.filter(re=>re.type.toLowerCase().includes(z)||re.payload.toLowerCase().includes(z))}return B}function it(){return W!==""||T!==""}function Ie(){U=0,C=0,$.resume(),Xe.style.display="none"}function ue(B){he.has(B)?he.delete(B):he.add(B),ge=B;let z=Oe.scrollTop,re=$.isFollowing();_=!0,$.pause(),ye(),Oe.scrollTop=z,re&&$.resume(),_=!1}function ie(){return so(Oe,50)}function ye(){j=Date.now(),J=!1,We(),Ee();let B=e.getEvictedCount();B>0?(Pe.textContent=`${B.toLocaleString()} older events truncated`,Pe.style.display=""):Pe.style.display="none",P=me();let z=P.length,re=e.getSize()>0;z===0&&re&&it()?(ft.textContent=T?`No events matching '${T}'`:"No events matching filter",ft.style.display="",Oe.style.display="none"):(ft.style.display="none",Oe.style.display=""),le&&(le.title=it()?`Copy Filtered (${z})`:"Copy All"),p&&!$.isFollowing()&&z>U&&(C+=z-U,Et.textContent=c?`${c}${C>0?` (${C})`:""}`:"",Xe.style.display=""),U=z;let et=e.getAll(),Re=et.length>0?et[0].timestamp:0,lt=new Set(P.map(xe=>xe.id));for(let xe of he)lt.has(xe)||he.delete(xe);let V=W!==Ce||T!==te,$e=Me.size===0&&P.length>0;if(V||$e||P.length===0){Oe.innerHTML="",Me.clear();let xe=document.createDocumentFragment();for(let Be=0;Be<P.length;Be++){let Le=dl(P[Be],Be,Re,u,he,ue,s,r);Me.set(P[Be].id,Le),xe.appendChild(Le)}Oe.appendChild(xe),Ce=W,te=T,ge=null}else{if(ge!==null){let Be=Me.get(ge);if(Be&&Be.parentNode===Oe){let Le=P.findIndex(Qe=>Qe.id===ge);if(Le>=0){let Qe=dl(P[Le],Le,Re,u,he,ue,s,r);Oe.insertBefore(Qe,Be),Be.remove(),Me.set(ge,Qe)}}ge=null}let xe=new Set(P.map(Be=>Be.id));for(let[Be,Le]of Me)xe.has(Be)||(Le.remove(),Me.delete(Be));for(let Be=0;Be<P.length;Be++){let Le=P[Be];if(!Me.has(Le.id)){let Qe=dl(Le,Be,Re,u,he,ue,s,r);Me.set(Le.id,Qe),Oe.appendChild(Qe)}}}$.isFollowing()&&(Oe.scrollTop=Oe.scrollHeight)}function bt(){if(Date.now()-j>=Tb){D!==null&&(cancelAnimationFrame(D),D=null),ye();return}J||(J=!0,D=requestAnimationFrame(()=>{D=null,ye()}))}let N=(B,z)=>{if(!le)return;le.innerHTML="";let re=ae(B,"12px","currentColor",1.5);re&&le.appendChild(re);let et=m("span","persona-text-xs");et.textContent="Copy All",le.appendChild(et),setTimeout(()=>{le.innerHTML="";let Re=ae("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let lt=m("span","persona-text-xs");lt.textContent="Copy All",le.appendChild(lt),le.disabled=!1},z)},ne=async()=>{if(le){le.disabled=!0;try{let B;it()?B=P:n?(B=await n(),B.length===0&&(B=e.getAll())):B=e.getAll();let z=B.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),N("check",1500)}catch{N("x",1500)}}},De=()=>{Y&&(W=Y.value,Ie(),ye())},ke=()=>{!Z||!be||(be.style.display=Z.value?"":"none",I&&clearTimeout(I),I=setTimeout(()=>{T=Z.value,Ie(),ye()},150))},M=()=>{!Z||!be||(Z.value="",T="",be.style.display="none",I&&clearTimeout(I),Ie(),ye())},X=()=>{if(_)return;let B=Oe.scrollTop,{action:z,nextLastScrollTop:re}=Ma({following:$.isFollowing(),currentScrollTop:B,lastScrollTop:ce,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ce=re,z==="resume"?($.resume(),C=0,Xe.style.display="none"):z==="pause"&&($.pause(),p&&(Et.textContent=c,Xe.style.display=""))},y=B=>{let z=Ea({following:$.isFollowing(),deltaY:B.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});z==="pause"?($.pause(),p&&(Et.textContent=c,Xe.style.display="")):z==="resume"&&($.resume(),C=0,Xe.style.display="none")},A=()=>{p&&(Oe.scrollTop=Oe.scrollHeight,$.resume(),C=0,Xe.style.display="none")},E=B=>{let z=B.target;if(!z||z.closest("button"))return;let re=z.closest("[data-event-id]");if(!re)return;let et=re.getAttribute("data-event-id");et&&ue(et)},R=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(M(),Z.blur(),x.focus()):o&&o())};le&&le.addEventListener("click",ne),Y&&Y.addEventListener("change",De),Z&&Z.addEventListener("input",ke),be&&be.addEventListener("click",M),Oe.addEventListener("scroll",X),Oe.addEventListener("wheel",y,{passive:!0}),Oe.addEventListener("click",E),Xe.addEventListener("click",A),x.addEventListener("keydown",R);function K(){I&&clearTimeout(I),D!==null&&(cancelAnimationFrame(D),D=null),J=!1,Me.clear(),le&&le.removeEventListener("click",ne),Y&&Y.removeEventListener("change",De),Z&&Z.removeEventListener("input",ke),be&&be.removeEventListener("click",M),Oe.removeEventListener("scroll",X),Oe.removeEventListener("wheel",y),Oe.removeEventListener("click",E),Xe.removeEventListener("click",A),x.removeEventListener("keydown",R)}return{element:x,update:bt,destroy:K}}}function Up(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.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&&e.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return t.addEventListener("keydown",d),t.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,v)=>{f.setAttribute("role","tab");let x=v===w;f.setAttribute("aria-selected",x?"true":"false"),f.tabIndex=x||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(){t.removeEventListener("keydown",d),t.removeEventListener("focusin",c)}}}function zp(t,e){let n=t.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=N=>({start:N===!1?!1:typeof N=="object"&&N?N.start!==!1:!0,end:N===!1?!1:typeof N=="object"&&N?N.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?m("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(),e.onDismiss?.()});let v=m("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=m("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=m("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let W=Wt({icon:"x",label:a});W.addEventListener("click",()=>{f(),e.onDismiss?.()});let T="rendered",I=va({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:N=>{T=N==="source"?"source":"rendered",ie()}}),H=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),q=n?.documentToolbarShowCopyLabel===!0,U=n?.documentToolbarShowCopyChevron===!0,$=n?.documentToolbarCopyMenuItems,C=!!(U&&$&&$.length>0),j=null,J,D=null,_=null;if(r&&(q||U)&&!C){if(J=q?Bo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),U){let N=ae("chevron-down",14,"currentColor",2);N&&J.appendChild(N)}}else r&&C?(j=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),J=q?Bo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Wt({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"}}),j.append(J,D)):r?J=Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(J=Wt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&J.classList.add("persona-hidden"));let ce=r?Wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wt({icon:"refresh-cw",label:"Refresh"}),he=r?Wt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Wt({icon:"x",label:a}),Me=Wt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Me.classList.add("persona-hidden");let Ce=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),te=t.features?.artifacts?.toolbarActions??[],ge=()=>{let N=Pe.find(M=>M.id===We)??Pe[Pe.length-1],ne=N?.id??null,De=N?.artifactType==="markdown"?N.markdown??"":"",ke=N?JSON.stringify({component:N.component,props:N.props},null,2):"";return{markdown:De,jsonPayload:ke,id:ne}},Y=async()=>{let N=Pe.find(ne=>ne.id===We)??Pe[Pe.length-1];try{await navigator.clipboard.writeText(rs(N))}catch{}};if(J.addEventListener("click",async()=>{let N=n?.onDocumentToolbarCopyMenuSelect;if(N&&C){let{markdown:ne,jsonPayload:De,id:ke}=ge();try{await N({actionId:"primary",artifactId:ke,markdown:ne,jsonPayload:De})}catch{}return}await Y()}),D&&$?.length){let N=()=>v.closest("[data-persona-root]")??document.body,ne=()=>{_=lr({items:$.map(De=>({id:De.id,label:De.label})),onSelect:async De=>{let{markdown:ke,jsonPayload:M,id:X}=ge(),y=n?.onDocumentToolbarCopyMenuSelect;try{y?await y({actionId:De,artifactId:X,markdown:ke,jsonPayload:M}):De==="markdown"||De==="md"?await navigator.clipboard.writeText(ke):De==="json"||De==="source"?await navigator.clipboard.writeText(M):await navigator.clipboard.writeText(ke||M)}catch{}},anchor:j??D,position:"bottom-right",portal:N()})};v.isConnected?ne():requestAnimationFrame(ne),D.addEventListener("click",De=>{De.stopPropagation(),_?.toggle()})}ce.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ie()}),he.addEventListener("click",()=>{f(),e.onDismiss?.()});let le=m("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(),j?H.append(j,ce,he):H.append(J,ce,he),H.insertBefore(Ce,he),H.insertBefore(Me,he),x.append(I.element,le,H);else{let N=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");N.append(J,Ce,Me,W),x.appendChild(P),x.appendChild(N)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let Z=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let be=t.features?.artifacts?.renderTabBar,ve=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=Up(Z,{onSelect:N=>e.onSelect(Pe[N].id)}),Te=N=>{let ne=N.scrollWidth-N.clientWidth,De=ne>1,ke=Math.abs(N.scrollLeft);N.classList.toggle("persona-artifact-tab-fade-start",c&&De&&ke>1),N.classList.toggle("persona-artifact-tab-fade-end",u&&De&&ke<ne-1)},Ae=0,ze=()=>{if(Ae)return;let N=()=>{Ae=0,Te(Z)};Ae=typeof requestAnimationFrame=="function"?requestAnimationFrame(N):setTimeout(N,0)};Z.addEventListener("scroll",()=>ze(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(Z)).observe(Z);let Ne=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let N of[Z,ve])N.style.paddingLeft=l,N.style.paddingRight=l;Ne.style.padding=l}v.appendChild(x),v.appendChild(Z),v.appendChild(ve),v.appendChild(Ne);let Pe=[],We=null,at=!1,Oe=!0,Xe=!1,sn=null,Et="",ft=null,Ee=!1,me=N=>N.artifactType==="markdown"&&!!N.file||r?T:"rendered",it=N=>{r||(N&&!Ee?(x.insertBefore(I.element,P),Ee=!0):!N&&Ee&&(I.element.remove(),Ee=!1))},Ie=()=>We&&Pe.find(N=>N.id===We)||Pe[Pe.length-1],ue=()=>{let N=ns(Ie());if(!N){Ce.replaceChildren();return}let ne=te.filter(De=>De.visible===void 0||De.visible(N)).map(De=>cr(De,{documentChrome:r,onClick:()=>{let ke=ns(Ie());if(ke)try{Promise.resolve(De.onClick(ke)).catch(()=>{})}catch{}}}));Ce.replaceChildren(...ne)},ie=()=>{ue();let N=r&&Pe.length<=1,ne=!!be;if(Z.classList.toggle("persona-hidden",N||ne),ve.classList.toggle("persona-hidden",N||!ne),ne&&be){let M=Pe.map(X=>X.id).join("|")+" "+(We??"");if(M!==Et){Et=M;let X=be({records:Pe,selectedId:We,onSelect:e.onSelect});ve.firstElementChild!==X&&ve.replaceChildren(X)}}else{fe.beforeRender(),Z.replaceChildren();let M=[],X=-1;for(let[y,A]of Pe.entries()){let E=m("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");E.type="button";let R=A.artifactType==="markdown"?A.file:void 0,K=R?Tn(R.path):A.title||A.id.slice(0,8),B=R?.path||A.title||K;E.textContent=K,E.title=B,E.setAttribute("aria-label",B),A.id===We&&(E.classList.add("persona-bg-persona-container","persona-border-persona-border"),X=y),E.addEventListener("click",()=>e.onSelect(A.id)),Z.appendChild(E),M.push(E)}if(fe.render(M,X),X>=0&&We!==sn){sn=We;let y=M[X];typeof y.scrollIntoView=="function"&&y.scrollIntoView({block:"nearest",inline:"nearest"})}Te(Z)}let De=We&&Pe.find(M=>M.id===We)||Pe[Pe.length-1];if(!De){Ne.replaceChildren(),ft=null,it(!1);return}let ke=De.artifactType==="markdown"?De.file:void 0;if(it(!!ke),r){let M=ke?to(ke):De.artifactType==="markdown"?"MD":De.component??"Component",X=(De.title||"Document").trim(),y=ke?Tn(ke.path):X.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${y} \xB7 ${M}`}else P.textContent=ke?Tn(ke.path):s;ft?(ft.el.parentElement!==Ne&&Ne.replaceChildren(ft.el),ft.update(De)):(ft=Ca(De,{config:t,resolveViewMode:me}),Ne.replaceChildren(ft.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},ye=()=>{let N=Pe.length>0;if(v.classList.toggle("persona-hidden",!N),w){let ke=((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;N&&ke&&at?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},bt=()=>{Xe=!1,ie(),ye()};return{element:v,backdrop:w,update(N){Pe=N.artifacts,We=N.selectedId??N.artifacts[N.artifacts.length-1]?.id??null,Pe.length>0&&(at=!0),Xe=!0,Oe&&bt()},setMobileOpen(N){at=N,!N&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):ye()},setExpanded(N){let ne=ae(N?"minimize":"maximize",16,"currentColor",2);ne&&Me.replaceChildren(ne);let De=N?"Collapse artifacts panel":"Expand artifacts panel";Me.setAttribute("aria-label",De),Me.title=De},setExpandToggleVisible(N){Me.classList.toggle("persona-hidden",!N)},setCopyButtonVisible(N){r||J.classList.toggle("persona-hidden",!N)},setCustomActions(N){te=N,ue()},setTabFade(N){let ne=d(N);ne.start===c&&ne.end===u||(c=ne.start,u=ne.end,Te(Z))},setRenderTabBar(N){N!==be&&(be=N,Et="",ie())},setVisible(N){N!==Oe&&(Oe=N,N&&Xe&&bt())}}}function Xt(t){return t?.features?.artifacts?.enabled===!0}function jp(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function Hb(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var qp=["panel","seamless","detached"];function pl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&qp.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function ul(t){return!t||!Xt(t)?!1:pl(t)==="detached"}function hs(t,e){if(!Xt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Hb(t),jp(t,e);return}let n=e.features?.artifacts?.layout,o=pl(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),jp(t,e)}function ys(t,e){for(let l of qp)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(e))return;let n=e.features?.artifacts?.layout,o=pl(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function Vp(t,e){return!e||!Xt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function Db(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Nb(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Fb(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ob(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function fl(t,e){let o=(e.getComputedStyle(t).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 Kp(t,e,n,o,r,s){let a=Db(r,200),l=Ob(e,n,o,200);l=Math.max(a,l);let p=Nb(s);return p!==null&&(l=Math.min(l,p)),Fb(t,a,l)}var Gp={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"}},gl=(t,e,n,o)=>{let r=t.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=Gp[a]??Gp.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=m("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=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${e.id}-${a}-${v.name}`;let P=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=v.label,x.appendChild(P);let W=v.type??"text",T;W==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=W),T.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",T.id=`${e.id}-${a}-${v.name}`,T.name=v.name,T.placeholder=v.placeholder??"",v.required&&(T.required=!0),x.appendChild(T),c.appendChild(x)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("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 x=n.formEndpoint??"/form",P=new FormData(c),W={};P.forEach((T,I)=>{W[I]=T}),W.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let T=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let I=await T.json();w.textContent=I.message??"Thanks! We'll be in touch soon.",I.success&&I.nextPrompt&&await o.sendMessage(String(I.nextPrompt))}catch(T){w.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ml=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},hl=new ml;var Xp=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var _b=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},$b=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},bl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=_b(t),n=$b(e);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}},yl=t=>typeof t=="string"?t:t==null?"":String(t),bs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:yl(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=yl(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:yl(n.text)}}},Qp=t=>Array.isArray(t)?t.map(e=>String(e)):[],vl=t=>{let e=new Set(Qp(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Qp(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.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?t.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let d of t.handlers)if(d)try{let c=()=>{t.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.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 Ub=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},zb=t=>t.map(e=>({...e,streaming:!1})),jb=t=>t.map(e=>({...e,status:"complete"})),Jp=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Ub(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?zb(n.messages):void 0,artifacts:n.artifacts?jb(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as QA,STR as JA,OBJ as YA}from"partial-json";function Yp(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Fn.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.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(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Zp(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function wl(t){let e=Zp(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function eu(t){let e=Zp(t);if(!e)return null;try{let n=JSON.parse(e);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:e}}}catch{}return null}var qb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function tu(t){let{onSubmit:e,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=qb}=t,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 x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,f.appendChild(x),w.appendChild(f);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 W=[];for(let U=1;U<=5;U++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${U} star${U>1?"s":""}: ${d[U-1]}`),$.title=d[U-1],$.dataset.rating=String(U),$.innerHTML=`
|
|
31
37
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
32
38
|
<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>
|
|
33
39
|
</svg>
|
|
34
|
-
`,P.addEventListener("click",()=>{g=C,B.forEach((U,_)=>{let I=_<C;U.classList.toggle("selected",I),U.setAttribute("aria-checked",_===C-1?"true":"false")})}),B.push(P),T.appendChild(P)}h.appendChild(T);let S=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),C.appendChild(S),h.appendChild(C)}let L=document.createElement("div");L.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),u.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await e(g,C),u.remove()}catch(C){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),L.appendChild(M),L.appendChild(k),h.appendChild(L),u.appendChild(h),u}function tg(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,v.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,v.appendChild(T),m.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 S=document.createElement("div");S.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=u,S.appendChild(L),S.appendChild(M);let k=document.createElement("div");k.className="persona-feedback-numbers";let C=[];for(let $=0;$<=10;$++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${$} out of 10`),N.textContent=String($),N.dataset.rating=String($),$<=6?N.classList.add("persona-feedback-detractor"):$<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{h=$,C.forEach((te,Ee)=>{te.classList.toggle("selected",Ee===$),te.setAttribute("aria-checked",Ee===$?"true":"false")})}),C.push(N),k.appendChild(N)}B.appendChild(S),B.appendChild(k),m.appendChild(B);let P=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),$.appendChild(P),m.appendChild($)}let U=document.createElement("div");U.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{t==null||t(),g.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(h===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let $=(P==null?void 0:P.value.trim())||void 0;await e(h,$),g.remove()}catch($){I.disabled=!1,I.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),U.appendChild(_),U.appendChild(I),m.appendChild(U),g.appendChild(m),g}var xs="persona-chat-history",Kv=30*1e3,Gv={"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 Qv(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=Gv[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function si(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Xv(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function Jv(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var il=n=>!n||typeof n!="object"?{}:{...n},ng=n=>n.map(e=>({...e,streaming:!1})),rg=(n,e,t)=>{let r=n!=null&&n.markdown?ya(n.markdown):null,o=ba(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.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=>{var u,g,h;let a=(u=s.text)!=null?u:"",i=(g=s.message.rawContent)!=null?g:null;if(e){let m=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&t&&t())}let d=No()!==null,c;if(n!=null&&n.postprocessMessage){let m=n.postprocessMessage({...s,text:a,raw:(h=i!=null?i:s.text)!=null?h:""});c=o?o(m):m}else if(r){let m=s.streaming?su(a):a,v=r(m);c=o&&d?o(v):v}else c=mo(a);return c}};function og(n){var i,d,c,u;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(u=n==null?void 0:n.iconStrokeWidth)!=null?u:.5,a=he(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let g=b("span","persona-drop-overlay-label");g.textContent=n.label,e.appendChild(g)}return e}var sg=(n,e,t)=>{var Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,wc,xc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,zc,qc,jc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Qu(e),o=rl.getForInstance(r.plugins),{plugin:s,teardown:a}=Wm();r.components&&Vo.registerAll(r.components);let i=Km(),c=r.persistState===!1?null:(Xl=r.storageAdapter)!=null?Xl:Qm(),u={},g=null,h=!1,m=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:f,open:y}=p;return y&&(h=!0),f}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")g=l.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return m(f)});else{let p=l!=null?l:{messages:[],metadata:{}},f=m(p);f.metadata&&(u=il(f.metadata)),(Jl=f.messages)!=null&&Jl.length&&(r={...r,initialMessages:f.messages}),(Yl=f.artifacts)!=null&&Yl.length&&(r={...r,initialArtifacts:f.artifacts,initialSelectedArtifactId:(Zl=f.selectedArtifactId)!=null?Zl:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(ec=l.messages)!=null&&ec.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>u,w=l=>{var f;u=(f=l({...u}))!=null?f:{},Pn()},T=r.actionParsers&&r.actionParsers.length?r.actionParsers:[sl],B=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ca.message,ca.messageAndClick],S=al({parsers:T,handlers:B,getSessionMetadata:v,updateSessionMetadata:w,emit:i.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let L=(nc=(tc=r.launcher)==null?void 0:tc.enabled)!=null?nc:!0,M=(oc=(rc=r.launcher)==null?void 0:rc.autoExpand)!=null?oc:!1,k=(sc=r.autoFocusInput)!=null?sc:!1,C=M,P=L,U=(ic=(ac=r.layout)==null?void 0:ac.header)==null?void 0:ic.layout,_=!1,I=()=>ra(r),$=()=>L||I(),N=I()?!1:L?M:!0,te=!1,Ee=null,de=()=>{te=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{te&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),te=!1)},1e4)},Y=rg(r,S,de),Le=(cc=(lc=r.features)==null?void 0:lc.showReasoning)!=null?cc:!0,Pe=(pc=(dc=r.features)==null?void 0:dc.showToolCalls)!=null?pc:!0,ae=(mc=(uc=r.features)==null?void 0:uc.showEventStreamToggle)!=null?mc:!1,fe=(fc=(gc=r.features)==null?void 0:gc.scrollToBottom)!=null?fc:{},ne=(yc=(hc=r.features)==null?void 0:hc.scrollBehavior)!=null?yc:{},ce=`${(vc=typeof r.persistState=="object"?(bc=r.persistState)==null?void 0:bc.keyPrefix:void 0)!=null?vc:"persona-"}event-stream`,Ce=ae?new ia(ce):null,_e=(Cc=(xc=(wc=r.features)==null?void 0:wc.eventStream)==null?void 0:xc.maxEvents)!=null?Cc:2e3,V=ae?new aa(_e,Ce):null,X=ae?new la:null,Ae=null,J=!1,ie=null,Se=0;Ce==null||Ce.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Je={onCopy:l=>{var p,f;i.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(f=(p=r.messageActions)==null?void 0:p.onCopy)==null||f.call(p,l)},onFeedback:l=>{var p,f;i.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(f=(p=r.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,l)}},et=(Ac=r.statusIndicator)!=null?Ac:{},Wt=l=>{var p,f,y,A,W,z;return l==="idle"?(p=et.idleText)!=null?p:tn.idle:l==="connecting"?(f=et.connectingText)!=null?f:tn.connecting:l==="connected"?(y=et.connectedText)!=null?y:tn.connected:l==="error"?(A=et.errorText)!=null?A:tn.error:l==="paused"?(W=et.pausedText)!=null?W:tn.paused:l==="resuming"?(z=et.resumingText)!=null?z:tn.resuming:tn[l]};function ft(l,p,f,y){if(y==="idle"&&f.idleLink){l.textContent="";let A=document.createElement("a");A.href=f.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=p,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=p}let rt=wm({config:r,showClose:$()}),{wrapper:ue,panel:Q,pillRoot:it}=rt.shell,je=rt.panelElements,{container:Te,body:we,messagesWrapper:Ye,suggestions:qt,textarea:ye,sendButton:pe,sendButtonWrapper:wn,composerForm:Ct,statusText:gn,introTitle:fr,introSubtitle:hr,closeButton:Ue,iconHolder:E,headerTitle:me,headerSubtitle:Me,header:ke,footer:Re,actionsRow:tt,leftActions:Qe,rightActions:ht}=je,ge=je.setSendButtonMode,H=je.micButton,be=je.micButtonWrapper,le=je.attachmentButton,gt=je.attachmentButtonWrapper,Ke=je.attachmentInput,Lt=je.attachmentPreviewsContainer;Te.classList.add("persona-relative"),we.classList.add("persona-relative");let Et=12,vt=()=>{var l;return(l=fe.label)!=null?l:""},Rt=()=>{var l;return(l=fe.iconName)!=null?l:"arrow-down"},Qt=()=>fe.enabled!==!1,Ft=()=>{var l;return(l=ne.mode)!=null?l:"anchor-top"},Zt=()=>Ft()==="follow"||Ft()==="anchor-top"&&to,yr=()=>{var l;return(l=ne.anchorTopOffset)!=null?l:16},Wr=()=>{var l;return(l=ne.restorePosition)!=null?l:"bottom"},nr=()=>ne.pauseOnInteraction===!0,rr=()=>ne.showActivityWhilePinned!==!1,Vr=()=>ne.announce===!0,jt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");jt.type="button",jt.style.display="none",jt.setAttribute("data-persona-scroll-to-bottom","true");let or=b("span","persona-flex persona-items-center"),Rr=b("span",""),Hn=b("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",jt.append(or,Rr,Hn),Te.appendChild(jt);let kn=b("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",we.appendChild(kn);let Bn=b("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.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"}),Te.appendChild(Bn);let sr=null,br=null,Kr=l=>{!Vr()||!l||(br=l,sr===null&&(sr=setTimeout(()=>{sr=null,br&&Vr()&&(Bn.textContent=br),br=null},400)))},jn=()=>{let p=Re.style.display==="none"?0:Re.offsetHeight;jt.style.bottom=`${p+Et}px`};jn();let Gr=()=>{let l=!!vt();jt.setAttribute("aria-label",vt()||"Jump to latest"),jt.title=vt(),jt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),or.innerHTML="";let p=he(Rt(),"14px","currentColor",2);p?(or.appendChild(p),or.style.display=""):or.style.display="none",Rr.textContent=vt(),Rr.style.display=l?"":"none"};Gr();let At=null,vr=null,wr=o.find(l=>l.renderHeader);if(wr!=null&&wr.renderHeader){let l=wr.renderHeader({config:r,defaultRenderer:()=>{let p=Uo({config:r,showClose:$()});return oa(Te,p,r),p.header},onClose:()=>_t(!1,"user")});if(l){let p=Te.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),ke=l,rt.header.element=l)}}let Hr=()=>{var p,f,y,A;if(!V)return;if(J=!0,!Ae&&V&&(Ae=Nm({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>ar(),config:r,plugins:o,getThroughput:()=>{var W;return(W=X==null?void 0:X.getMetric())!=null?W:{status:"idle"}}})),Ae&&(we.style.display="none",(p=Re.parentNode)==null||p.insertBefore(Ae.element,Re),Ae.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${En.actionIconColor}`;let W=(A=(y=(f=r.features)==null?void 0:f.eventStream)==null?void 0:y.classNames)==null?void 0:A.toggleButtonActive;W&&W.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!J)return;let W=Date.now();W-Se>=200&&(Ae==null||Ae.update(),Se=W),ie=requestAnimationFrame(l)};Se=0,ie=requestAnimationFrame(l),On(),i.emit("eventStream:opened",{timestamp:Date.now()})},ar=()=>{var l,p,f;if(J){if(J=!1,Ae&&Ae.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let y=(f=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;y&&y.split(/\s+/).forEach(A=>A&&yt.classList.remove(A))}ie!==null&&(cancelAnimationFrame(ie),ie=null),On(),i.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ae){let l=(Tc=(Sc=r.features)==null?void 0:Sc.eventStream)==null?void 0:Tc.classNames,p="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"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=b("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=En.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let f=he("activity","18px","currentColor",1.5);f&&yt.appendChild(f);let y=je.clearChatButtonWrapper,A=je.closeButtonWrapper,W=y||A;W&&W.parentNode===ke?ke.insertBefore(yt,W):ke.appendChild(yt),yt.addEventListener("click",()=>{J?ar():Hr()})}let wo=l=>{var A,W,z,O,D;let p=r.attachments;if(!(p!=null&&p.enabled))return;let f=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!f){f=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(f,se):l.insertBefore(f,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let se=b("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=p.allowedTypes)!=null?z:qr).join(","),se.multiple=((O=p.maxFiles)!=null?O:4)>1,se.style.display="none",se.setAttribute("aria-label",(D=p.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(se)}},xr=o.find(l=>l.renderComposer);if(xr!=null&&xr.renderComposer){let l=r.composer,p=xr.renderComposer({config:r,defaultRenderer:()=>Za({config:r}).footer,onSubmit:f=>{var z;if(!F||F.isStreaming())return;let y=f.trim(),A=(z=At==null?void 0:At.hasAttachments())!=null?z:!1;if(!y&&!A)return;Tl();let W;A&&(W=[],W.push(...At.getContentParts()),y&&W.push(Wi(y))),F.sendMessage(y,{contentParts:W}),A&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:f=>{r.composer={...r.composer,selectedModelId:f},r.agent&&(r.agent={...r.agent,model:f})},onVoiceToggle:((Mc=r.voiceRecognition)==null?void 0:Mc.enabled)===!0?()=>{vr==null||vr()}:void 0});p&&(rt.replaceComposer(p),Re=rt.composer.footer)}let xo=l=>{let p=(...oe)=>{for(let Z of oe){let ve=l.querySelector(Z);if(ve)return ve}return null},f=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");f&&(Ct=f),y&&(ye=y),A&&(pe=A),W&&(H=W,be=W.parentElement),z&&(gn=z);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(qt=O);let D=p("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(le=D,gt=D.parentElement),Ke=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(tt=se)};wo(Re),xo(Re);let Ln=(Ic=(Ec=r.layout)==null?void 0:Ec.contentMaxWidth)!=null?Ic:I()?(Pc=(Lc=(kc=r.launcher)==null?void 0:kc.composerBar)==null?void 0:Lc.contentMaxWidth)!=null?Pc:"720px":void 0;if(Ln&&(Ye.style.maxWidth=Ln,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),Ln&&Ct&&!I()&&(Ct.style.maxWidth=Ln,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Ln&&qt&&!I()&&(qt.style.maxWidth=Ln,qt.style.marginLeft="auto",qt.style.marginRight="auto"),Ln&&Lt&&!I()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(Wc=r.attachments)!=null&&Wc.enabled&&Ke&&Lt){At=Xs.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Ke.addEventListener("change",f=>{let y=f.target;At==null||At.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=og(l);Te.appendChild(p)}(()=>{var y,A;let l=(A=(y=r.layout)==null?void 0:y.slots)!=null?A:{},p=W=>{switch(W){case"body-top":return Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return gn;default:return null}},f=(W,z)=>{var O;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")ke.insertBefore(z,ke.firstChild);else if(W==="header-right")ke.appendChild(z);else{let D=ke.querySelector(".persona-flex-col");D?(O=D.parentNode)==null||O.insertBefore(z,D.nextSibling):ke.appendChild(z)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(z):we.insertBefore(z,we.firstChild);break}case"body-bottom":we.appendChild(z);break;case"footer-top":qt.replaceWith(z);break;case"footer-bottom":gn.replaceWith(z);break;default:break}};for(let[W,z]of Object.entries(l))if(z)try{let O=z({config:r,defaultContent:()=>p(W)});O&&f(W,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,O)}})();let Qr=l=>{var z,O;let f=l.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let W=f.getAttribute("data-bubble-type");if(W==="reasoning")bs.has(A)?bs.delete(A):bs.add(A),Am(A,y);else if(W==="tool")vs.has(A)?vs.delete(A):vs.add(A),Sm(A,y,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,se=((z=D==null?void 0:D.detailsDisplay)!=null?z:"collapsed")==="expanded",oe=(O=zo.get(A))!=null?O:se;zo.set(A,!oe),km(A,y,r)}Tr.delete(A)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Qr(l))}),Ye.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Qr(l))}),Ye.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let f=Ye.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let A=y.toString(),W=tm(A);!W||W===A||(p.setData("text/plain",W),l.preventDefault())});let Br=new Map,Xr=null,Jr="idle",Co={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ao=(l,p)=>{let{icon:f,label:y}=Co[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let A=he(f,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Yr=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var W;let f=p.closest("[data-actions-for]"),y=(W=f==null?void 0:f.getAttribute("data-actions-for"))!=null?W:null;Ao(p,y&&y===Xr?Jr:"idle")})};Ye.addEventListener("click",l=>{var z;let f=l.target.closest(".persona-message-action-btn[data-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let A=y.getAttribute("data-actions-for");if(!A)return;let W=f.getAttribute("data-action");if(W==="copy"){let D=F.getMessages().find(se=>se.id===A);if(D&&Je.onCopy){let se=D.content||"";navigator.clipboard.writeText(se).then(()=>{f.classList.add("persona-message-action-success");let oe=he("check",14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let Z=he("copy",14,"currentColor",2);Z&&(f.innerHTML="",f.appendChild(Z))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Je.onCopy(D)}}else if(W==="read-aloud")F.toggleReadAloud(A);else if(W==="upvote"||W==="downvote"){let D=((z=Br.get(A))!=null?z:null)===W,se=W==="upvote"?"thumbs-up":"thumbs-down";if(D){Br.delete(A),f.classList.remove("persona-message-action-active");let oe=he(se,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe))}else{let oe=W==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${oe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=he(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Br.set(A,W),f.classList.add("persona-message-action-active");let ve=he(se,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ve)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Fe=F.getMessages().find($e=>$e.id===A);Fe&&Je.onFeedback&&Je.onFeedback({type:W,messageId:Fe.id,message:Fe})}}}),Ye.addEventListener("click",l=>{let f=l.target.closest("button[data-approval-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let W=f.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",D=F.getMessages().find(oe=>oe.id===A);if(!(D!=null&&D.approval))return;let se=y.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?F.resolveWebMcpApproval(A,z):F.resolveApproval(D.approval,z)});let wt=null,Dn=null,Nn={artifacts:[],selectedId:null},xn=!1,St={current:null};Ye.addEventListener("click",l=>{var Z,ve,Ne,Fe,$e;let f=l.target.closest("[data-download-artifact]");if(!f)return;l.preventDefault(),l.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||((Ne=(ve=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Ne.call(ve,{type:"download",artifactId:y}))===!0)return;let W=F.getArtifactById(y),z=W==null?void 0:W.markdown,O=(W==null?void 0:W.title)||"artifact";if(!z){let ze=f.closest("[data-open-artifact]"),ut=ze==null?void 0:ze.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ie=F.getMessages().find(qe=>qe.id===st);if(Ie!=null&&Ie.rawContent)try{let qe=JSON.parse(Ie.rawContent);z=(Fe=qe==null?void 0:qe.props)==null?void 0:Fe.markdown,O=(($e=qe==null?void 0:qe.props)==null?void 0:$e.title)||O}catch{}}}if(!z)return;let D=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(D),oe=document.createElement("a");oe.href=se,oe.download=`${O}.md`,oe.click(),URL.revokeObjectURL(se)}),Ye.addEventListener("click",l=>{var W,z,O;let f=l.target.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||((O=(z=(W=r.features)==null?void 0:W.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:O.call(z,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),xn=!1,F.selectArtifact(y),Cr())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Vn=je.composerOverlay,Kn=(l,p,f)=>{var O,D,se,oe;let y=p.trim();if(!y||!St.current)return;let A=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",W=f.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:y,answers:f.structured,values:(D=f.values)!=null?D:f.source==="multi"?y.split(", "):[y],isFreeText:W,source:f.source},bubbles:!0,composed:!0})),ds(Vn,A);let z=St.current.getMessages().find(Z=>{var ve;return((ve=Z.toolCall)==null?void 0:ve.id)===A});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(z,(oe=f.structured)!=null?oe:y):St.current.sendMessage(y)},Fn=l=>{var A;let p=St.current;if(!p)return;let f=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",y=p.getMessages().find(W=>{var z;return((z=W.toolCall)==null?void 0:z.id)===f});y&&p.persistAskUserQuestionProgress(y,{answers:xa(l,y),currentIndex:er(l)})},Zr=l=>Object.entries(l).map(([p,f])=>`${p}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),xe=l=>{var A,W,z;if(((W=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let p=er(l),f=cs(l);if(p>=f-1)return;let y=(z=St.current)==null?void 0:z.getMessages().find(O=>{var D;return((D=O.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});y&&(Aa(l,y,r,p+1),Fn(l))};Vn.addEventListener("click",l=>{var W,z,O,D,se,oe,Z,ve,Ne,Fe,$e,ze,ut,st;let f=l.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let A=f.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let He=(W=y.getAttribute("data-tool-call-id"))!=null?W:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),ds(Vn,He);let Ie=(z=St.current)==null?void 0:z.getMessages().find(qe=>{var Ge;return((Ge=qe.toolCall)==null?void 0:Ge.id)===He});(O=Ie==null?void 0:Ie.agentMetadata)!=null&&O.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Ie),(se=St.current)==null||se.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(A==="pick"){let He=f.getAttribute("data-option-label");if(!He)return;let Ie=y.getAttribute("data-multi-select")==="true",qe=go(y);if(qe&&Ie){let Ge=Oo(y)[er(y)],bt=new Set(Array.isArray(Ge)?Ge:[]);bt.has(He)?bt.delete(He):bt.add(He),fo(y,Array.from(bt)),Fn(y);return}if(qe){fo(y,He),Fn(y),xe(y);return}if(Ie){let Ge=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Ge?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Ge);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Mi(y).length===0);return}Kn(y,He,{source:"pick",values:[He]});return}if(A==="submit-multi"){let He=Mi(y);if(He.length===0)return;Kn(y,He.join(", "),{source:"multi",values:He});return}if(A==="open-free-text"){let He=y.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Ie=He.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(A==="focus-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(A==="submit-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(oe=He==null?void 0:He.value)!=null?oe:"";if(!Ie.trim())return;if(go(y)){fo(y,Ie.trim()),Fn(y),xe(y);return}Kn(y,Ie,{source:"free-text"});return}if(A==="next"||A==="back"){if(!St.current)return;let He=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Ie=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(Ne=(ve=qe==null?void 0:qe.value)==null?void 0:ve.trim())!=null?Ne:"";if(Ge){let Be=Oo(y)[er(y)];(typeof Be!="string"||Be!==Ge)&&fo(y,Ge)}let bt=A==="next"?1:-1,R=er(y)+bt;Aa(y,Ie,r,R),Fn(y);return}if(A==="submit-all"){if(!St.current)return;let He=(Fe=y.getAttribute("data-tool-call-id"))!=null?Fe:"",Ie=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(ze=($e=qe==null?void 0:qe.value)==null?void 0:$e.trim())!=null?ze:"";Ge&&fo(y,Ge);let bt=xa(y,Ie);St.current.persistAskUserQuestionProgress(Ie,{answers:bt,currentIndex:er(y)});let R=Zr(bt);Kn(y,R||"(submitted)",{source:"submit-all",structured:bt});return}if(A==="skip"){if(!St.current)return;let He=(ut=y.getAttribute("data-tool-call-id"))!=null?ut:"",Ie=St.current.getMessages().find(We=>{var Xe;return((Xe=We.toolCall)==null?void 0:Xe.id)===He});if(!Ie)return;let qe=go(y),Ge=er(y),bt=cs(y),R=Ge>=bt-1;if(!qe){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),ds(Vn,He),(st=Ie.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Ie),St.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}fo(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),R){let We=xa(y,Ie),Xe=Zr(We);Kn(y,Xe||"(skipped)",{source:"submit-all",structured:We});return}Aa(y,Ie,r,Ge+1),Fn(y);return}}),Vn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let f=l.target;if(!((W=f.matches)!=null&&W.call(f,'[data-ask-free-text-input="true"]')))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let A=f.value;if(A.trim()){if(go(y)){fo(y,A.trim()),Fn(y),xe(y);return}Kn(y,A,{source:"free-text"})}});let Dr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let f=Vn.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),W=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",Dr);let Gn=null,Ot=null,Qn=null,Nr=null,As=()=>{};function Go(){Nr==null||Nr(),Nr=null}let Ss=()=>{var z;if(!Gn||!Ot)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),f=((z=n.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||f){Ot.style.removeProperty("position"),Ot.style.removeProperty("left"),Ot.style.removeProperty("top"),Ot.style.removeProperty("bottom"),Ot.style.removeProperty("width"),Ot.style.removeProperty("z-index");return}let y=Gn.firstElementChild;if(!y||y===Ot)return;let A=10;Ot.style.position="absolute",Ot.style.top="0",Ot.style.bottom="0",Ot.style.width=`${A}px`,Ot.style.zIndex="5";let W=y.offsetWidth-A/2;Ot.style.left=`${Math.max(0,W)}px`},So=()=>{},Cr=()=>{var f,y,A,W,z;if(!wt||!tr(r))return;ri(n,r),oi(n,r),So();let l=(W=(A=(y=(f=r.features)==null?void 0:f.artifacts)==null?void 0:y.layout)==null?void 0:A.narrowHostMaxWidth)!=null?W:520,p=Q.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),wt.update(Nn),xn?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(z=wt.backdrop)==null||z.classList.add("persona-hidden")):Nn.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),As()};if(tr(r)){Q.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Te),wt=_m(r,{onSelect:f=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(f)},onDismiss:()=>{xn=!0,Cr()}}),wt.element.classList.add("persona-hidden"),Gn=p,p.appendChild(l),p.appendChild(wt.element),wt.backdrop&&Q.appendChild(wt.backdrop),Q.appendChild(p),As=()=>{var y,A,W,z;if(!Gn||!wt)return;if(!(((W=(A=(y=r.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:W.resizable)===!0)){Qn==null||Qn(),Qn=null,Go(),Ot&&(Ot.remove(),Ot=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!Ot){let O=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let D=n.ownerDocument,se=(z=D.defaultView)!=null?z:window,oe=Z=>{var ut,st;if(!wt||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Go();let ve=Z.clientX,Ne=wt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,$e=He=>{let Ie=Gn.getBoundingClientRect().width,qe=n.classList.contains("persona-artifact-appearance-seamless"),Ge=qe?0:qm(Gn,se),bt=qe?0:O.getBoundingClientRect().width||6,R=Ne-(He.clientX-ve),Be=jm(R,Ie,Ge,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);wt.element.style.width=`${Be}px`,wt.element.style.maxWidth="none",Ss()},ze=()=>{D.removeEventListener("pointermove",$e),D.removeEventListener("pointerup",ze),D.removeEventListener("pointercancel",ze),Nr=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};Nr=ze,D.addEventListener("pointermove",$e),D.addEventListener("pointerup",ze),D.addEventListener("pointercancel",ze);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",oe),Ot=O,Gn.insertBefore(O,wt.element),Qn=()=>{O.removeEventListener("pointerdown",oe)}}if(Ot){let O=Nn.artifacts.length>0&&!xn;Ot.classList.toggle("persona-hidden",!O),Ss()}},So=()=>{var se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie,qe,Ge;if(!L||!wt||((oe=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?oe:!1)||mn(r)&&mr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,A=(Ne=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Ne:!0,W=($e=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?$e:640;if(A&&y.innerWidth<=W||!zm(r,L))return;let z=(st=(ut=(ze=r.launcher)==null?void 0:ze.width)!=null?ut:r.launcherWidth)!=null?st:jr,O=(Ge=(qe=(Ie=(He=r.features)==null?void 0:He.artifacts)==null?void 0:Ie.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!xn?(Q.style.width=O,Q.style.maxWidth=O):(Q.style.width=z,Q.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Cr()}),Dn.observe(Q))}else Q.appendChild(Te),I()&&it&&(je.peekBanner&&it.appendChild(je.peekBanner),it.appendChild(Re));n.appendChild(ue),it&&n.appendChild(it);let eo=()=>{var Be,We,Xe,Pt,Oe,Kt,xt,sn,Wn,Bt,pn,_n,Ve,It,$n,Lo,Po,Io,Wo,rs,os,Gt,Ro,co,po,$r,Ho,Ze;if(I()){Q.style.width="100%",Q.style.maxWidth="100%";let Nt=(We=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?We:{},Dt=ue.dataset.state==="expanded",Vt=(Xe=Nt.expandedSize)!=null?Xe:"anchored";if(!(Dt&&Vt!=="fullscreen")){Te.style.background="",Te.style.border="",Te.style.borderRadius="",Te.style.overflow="",Te.style.boxShadow="";return}let mt=(Oe=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:Oe.panel,Ut=Ha(r),un=(dn,Zn)=>{var uo;return dn==null||dn===""?Zn:(uo=gs(Ut,dn))!=null?uo:dn},Un="1px solid var(--persona-border)",Lr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",cn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Te.style.background="var(--persona-surface, #ffffff)",Te.style.border=un(mt==null?void 0:mt.border,Un),Te.style.borderRadius=un(mt==null?void 0:mt.borderRadius,cn),Te.style.boxShadow=un(mt==null?void 0:mt.shadow,Lr),Te.style.overflow="hidden";return}let l=mn(r),p=(xt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?xt:!1,f=l||p||((Wn=(sn=r.launcher)==null?void 0:sn.fullHeight)!=null?Wn:!1),y=((Bt=r.launcher)==null?void 0:Bt.enabled)===!1,A=(_n=(pn=r.theme)==null?void 0:pn.components)==null?void 0:_n.panel,W=Ha(r),z=(Nt,Dt)=>{var Vt;return Nt==null||Nt===""?Dt:(Vt=gs(W,Nt))!=null?Vt:Nt},O=(Ve=n.ownerDocument.defaultView)!=null?Ve:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,se=(Po=(Lo=r.launcher)==null?void 0:Lo.mobileBreakpoint)!=null?Po:640,oe=O.innerWidth<=se,Z=D&&oe&&L,ve=(Wo=(Io=r.launcher)==null?void 0:Io.position)!=null?Wo:"bottom-left",Ne=ve==="bottom-left"||ve==="top-left",Fe=(os=(rs=r.launcher)==null?void 0:rs.zIndex)!=null?os:bn,$e=p||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":p?Ne?"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))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(ze="none",$e="none");let ut=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=z(A==null?void 0:A.border,$e),He=z(A==null?void 0:A.shadow,ze),Ie=z(A==null?void 0:A.borderRadius,ut),qe=we.scrollTop;n.style.cssText="",ue.style.cssText="",Q.style.cssText="",Te.style.cssText="",we.style.cssText="",Re.style.cssText="",J&&(we.style.display="none");let Ge=()=>{var Dt;if(qe<=0)return;((Dt=we.ownerDocument.defaultView)!=null?Dt:window).requestAnimationFrame(()=>{if(we.scrollTop===qe)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(qe,Vt))})};if(Z){ue.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"),ue.style.cssText=`
|
|
40
|
+
`,$.addEventListener("click",()=>{u=U,W.forEach((C,j)=>{let J=j<U;C.classList.toggle("selected",J),C.setAttribute("aria-checked",j===U-1?"true":"false")})}),W.push($),P.appendChild($)}w.appendChild(P);let T=null;if(p){let U=document.createElement("div");U.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),U.appendChild(T),w.appendChild(U)}let I=document.createElement("div");I.className="persona-feedback-actions";let H=document.createElement("button");H.type="button",H.className="persona-feedback-btn persona-feedback-btn-skip",H.textContent=l,H.addEventListener("click",()=>{n?.(),c.remove()});let q=document.createElement("button");return q.type="button",q.className="persona-feedback-btn persona-feedback-btn-submit",q.textContent=a,q.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}q.disabled=!0,q.textContent="Submitting...";try{let U=T?.value.trim()||void 0;await e(u,U),c.remove()}catch(U){q.disabled=!1,q.textContent=a,console.error("[CSAT Feedback] Failed to submit:",U)}}),I.appendChild(H),I.appendChild(q),w.appendChild(I),c.appendChild(w),c}function nu(t){let{onSubmit:e,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"}=t,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 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),f.appendChild(v);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=d;let H=document.createElement("span");H.className="persona-feedback-label-high",H.textContent=c,T.appendChild(I),T.appendChild(H);let q=document.createElement("div");q.className="persona-feedback-numbers";let U=[];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,U.forEach((ce,he)=>{ce.classList.toggle("selected",he===D),ce.setAttribute("aria-checked",he===D?"true":"false")})}),U.push(_),q.appendChild(_)}W.appendChild(T),W.appendChild(q),f.appendChild(W);let $=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),D.appendChild($),f.appendChild(D)}let C=document.createElement("div");C.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),u.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(w===null){q.classList.add("persona-feedback-shake"),setTimeout(()=>q.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let D=$?.value.trim()||void 0;await e(w,D),u.remove()}catch(D){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),C.appendChild(j),C.appendChild(J),f.appendChild(C),u.appendChild(f),u}var gr="persona-chat-history",Vb=30*1e3,Kb=641,Gb={"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 Xb(t){if(!t)return[];let e=[],n=Array.from(t.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){e.push(r);continue}let s=Gb[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function qa(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Qb(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function Jb(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var xl=t=>!t||typeof t!="object"?{}:{...t},ou=t=>t.map(e=>({...e,streaming:!1})),ru=(t,e,n)=>{let o=t?.markdown?Gs(t.markdown):null,r=Xs(t?.sanitize);return t?.postprocessMessage&&r&&t?.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(e){let c=e.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=Wn()!==null,d;if(t?.postprocessMessage){let c=t.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?jc(a):a,u=o(c);d=r&&p?r(u):u}else d=Jn(a);return d}};function su(t){let e=m("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=m("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var au=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Hd(e),r=hl.getForInstance(o.plugins),{plugin:s,teardown:a}=Dp();o.components&&Fn.registerAll(o.components);let l=Xp(),d=o.persistState===!1?null:o.storageAdapter??Jp(),c={},u=null,w=!1,f=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:b}=g;return b&&(w=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(g=>f(g??{messages:[],metadata:{}}));else{let h=f(i??{messages:[],metadata:{}});h.metadata&&(c=xl(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let v=()=>c,x=i=>{c=i({...c})??{},ci()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[bl],W=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick],T=vl({parsers:P,handlers:W,getSessionMetadata:v,updateSessionMetadata:x,emit:l.emit,documentRef:typeof document<"u"?document:null});T.syncFromMetadata();let I=o.launcher?.enabled??!0,H=o.launcher?.autoExpand??!1,q=o.autoFocusInput??!1,U=H,$=I,C=o.layout?.header?.layout,j=!1,J=()=>ds(o),D=()=>I||J(),_=J()?!1:I?H:!0,ce=!1,he=null,Me=()=>{ce=!0,he&&clearTimeout(he),he=setTimeout(()=>{ce&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ce=!1)},1e4)},Ce=ru(o,T,Me),te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,le=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},ve=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=Y?new gs(ve):null,Te=o.features?.eventStream?.maxEvents??2e3,Ae=Y?new fs(Te,fe):null,ze=Y?new ms:null,Ne=null,Pe=!1,We=null,at=0;fe?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Oe={onCopy:i=>{l.emit("message:copy",i),F?.isClientTokenMode()&&F.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),F?.isClientTokenMode()&&F.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Xe=o.statusIndicator??{},sn=i=>i==="idle"?Xe.idleText??Rt.idle:i==="connecting"?Xe.connectingText??Rt.connecting:i==="connected"?Xe.connectedText??Rt.connected:i==="error"?Xe.errorText??Rt.error:i==="paused"?Xe.pausedText??Rt.paused:i==="resuming"?Xe.resumingText??Rt.resuming:Rt[i];function Et(i,g,h,b){if(b==="idle"&&h.idleLink){i.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=g,S.style.color="inherit",S.style.textDecoration="none",i.appendChild(S)}else i.textContent=g}let ft=Sp({config:o,showClose:D()}),{wrapper:Ee,panel:me,pillRoot:it}=ft.shell,Ie=ft.panelElements,{container:ue,body:ie,messagesWrapper:ye,suggestions:bt,textarea:N,sendButton:ne,sendButtonWrapper:De,composerForm:ke,statusText:M,introTitle:X,introSubtitle:y,closeButton:A,iconHolder:E,headerTitle:R,headerSubtitle:K,header:B,footer:z,actionsRow:re,leftActions:et,rightActions:Re}=Ie,lt=Ie.setSendButtonMode,V=Ie.micButton,$e=Ie.micButtonWrapper,xe=Ie.attachmentButton,Be=Ie.attachmentButtonWrapper,Le=Ie.attachmentInput,Qe=Ie.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ie.classList.add("persona-relative");let io=12,lo=()=>le.label??"",Ka=()=>le.iconName??"arrow-down",ws=()=>le.enabled!==!1,Qt=()=>Z.mode??"anchor-top",On=()=>Qt()==="follow"||Qt()==="anchor-top"&&Sr,kl=()=>Z.anchorTopOffset??16,bu=()=>Z.restorePosition??"bottom",Ll=()=>Z.pauseOnInteraction===!0,Pl=()=>Z.showActivityWhilePinned!==!1,Il=()=>Z.announce===!0,Pt=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let hr=m("span","persona-flex persona-items-center"),Ga=m("span",""),co=m("span","");co.setAttribute("data-persona-scroll-to-bottom-count",""),co.style.display="none",Pt.append(hr,Ga,co),ue.appendChild(Pt);let _n=m("div","persona-stream-anchor-spacer");_n.setAttribute("aria-hidden","true"),_n.setAttribute("data-persona-anchor-spacer",""),_n.style.flexShrink="0",_n.style.pointerEvents="none",_n.style.height="0px",ie.appendChild(_n);let po=m("div","persona-sr-only");po.setAttribute("aria-live","polite"),po.setAttribute("aria-atomic","true"),po.setAttribute("role","status"),po.setAttribute("data-persona-live-region",""),Object.assign(po.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ue.appendChild(po);let yr=null,xs=null,Rl=i=>{!Il()||!i||(xs=i,yr===null&&(yr=setTimeout(()=>{yr=null,xs&&Il()&&(po.textContent=xs),xs=null},400)))},Oo=()=>{let g=z.style.display==="none"?0:z.offsetHeight;Pt.style.bottom=`${g+io}px`};Oo();let Wl=()=>{let i=!!lo();Pt.setAttribute("aria-label",lo()||"Jump to latest"),Pt.title=lo(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),hr.innerHTML="";let g=ae(Ka(),"14px","currentColor",2);g?(hr.appendChild(g),hr.style.display=""):hr.style.display="none",Ga.textContent=lo(),Ga.style.display=i?"":"none"};Wl();let Tt=null,Bl=null,Hl=r.find(i=>i.renderHeader);if(Hl?.renderHeader){let i=Hl.renderHeader({config:o,defaultRenderer:()=>{let g=Ho({config:o,showClose:D()});return ps(ue,g,o),g.header},onClose:()=>mt(!1,"user")});if(i){let g=ue.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),B=i,ft.header.element=i)}}let Xa=()=>{if(!Ae)return;if(Pe=!0,!Ne&&Ae&&(Ne=$p({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>br(),config:o,plugins:r,getThroughput:()=>ze?.getMetric()??{status:"idle"}})),Ne&&(ie.style.display="none",z.parentNode?.insertBefore(Ne.element,z),Ne.update()),rt){rt.style.boxShadow=`inset 0 0 0 1.5px ${Gt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&rt.classList.add(h))}let i=()=>{if(!Pe)return;let g=Date.now();g-at>=200&&(Ne?.update(),at=g),We=requestAnimationFrame(i)};at=0,We=requestAnimationFrame(i),en(),l.emit("eventStream:opened",{timestamp:Date.now()})},br=()=>{if(Pe){if(Pe=!1,Ne&&Ne.element.remove(),ie.style.display="",rt){rt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&rt.classList.remove(g))}We!==null&&(cancelAnimationFrame(We),We=null),en(),l.emit("eventStream:closed",{timestamp:Date.now()})}},rt=null;if(Y){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:"");rt=m("button",g),rt.style.width="28px",rt.style.height="28px",rt.style.color=Gt.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let h=ae("activity","18px","currentColor",1.5);h&&rt.appendChild(h);let b=Ie.clearChatButtonWrapper,S=Ie.closeButtonWrapper,k=b||S;k&&k.parentNode===B?B.insertBefore(rt,k):B.appendChild(rt),rt.addEventListener("click",()=>{Pe?br():Xa()})}let vu=i=>{let g=o.attachments;if(!g?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let S=i.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(h,S):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let S=m("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(g.allowedTypes??Dn).join(","),S.multiple=(g.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(S)}},Dl=r.find(i=>i.renderComposer);if(Dl?.renderComposer){let i=o.composer,g=Dl.renderComposer({config:o,defaultRenderer:()=>$a({config:o}).footer,onSubmit:h=>{if(!F||F.isStreaming())return;let b=h.trim(),S=Tt?.hasAttachments()??!1;if(!b&&!S)return;pc();let k;S&&(k=[],k.push(...Tt.getContentParts()),b&&k.push(Fi(b))),F.sendMessage(b,{contentParts:k}),S&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Le?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Bl?.()}:void 0});g&&(ft.replaceComposer(g),z=ft.composer.footer)}let wu=i=>{let g=(...de)=>{for(let oe of de){let we=i.querySelector(oe);if(we)return we}return null},h=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),S=i.querySelector("[data-persona-composer-submit]"),k=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");h&&(ke=h),b&&(N=b),S&&(ne=S),k&&(V=k,$e=k.parentElement),Q&&(M=Q);let O=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(bt=O);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(xe=G,Be=G.parentElement),Le=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Qe=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(re=se)};vu(z),wu(z);let $n=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if($n&&(ye.style.maxWidth=$n,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),$n&&ke&&!J()&&(ke.style.maxWidth=$n,ke.style.marginLeft="auto",ke.style.marginRight="auto"),$n&&bt&&!J()&&(bt.style.maxWidth=$n,bt.style.marginLeft="auto",bt.style.marginRight="auto"),$n&&Qe&&!J()&&(Qe.style.maxWidth=$n,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),o.attachments?.enabled&&Le&&Qe){Tt=Yr.fromConfig(o.attachments),Tt.setPreviewsContainer(Qe),Le.addEventListener("change",h=>{let b=h.target;Tt?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=su(i);ue.appendChild(g)}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return bt;case"composer":return ke;case"footer-bottom":return M;default:return null}},h=(b,S)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")B.insertBefore(S,B.firstChild);else if(b==="header-right")B.appendChild(S);else{let k=B.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(S,k.nextSibling):B.appendChild(S)}break;case"body-top":{let k=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");k?k.replaceWith(S):ie.insertBefore(S,ie.firstChild);break}case"body-bottom":ie.appendChild(S);break;case"footer-top":bt.replaceWith(S);break;case"footer-bottom":M.replaceWith(S);break;default:break}};for(let[b,S]of Object.entries(i))if(S)try{let k=S({config:o,defaultContent:()=>g(b)});k&&h(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})();let Nl=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let k=h.getAttribute("data-bubble-type");if(k==="reasoning")pr.has(S)?pr.delete(S):pr.add(S),Ep(S,b);else if(k==="tool")ur.has(S)?ur.delete(S):ur.add(S),kp(S,b,o);else if(k==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Do.get(S)??O;Do.set(S,!G),Rp(S,b,o)}mo.delete(S)};ye.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nl(i))}),ye.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nl(i))}),ye.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let h=ye.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),k=ap(S);!k||k===S||(g.setData("text/plain",k),i.preventDefault())});let Qa=new Map,Fl=null,Ol="idle",xu={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Cu=(i,g)=>{let{icon:h,label:b}=xu[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 S=ae(h,14,"currentColor",2);S&&(i.innerHTML="",i.appendChild(S))},_l=()=>{ye.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Cu(g,b&&b===Fl?Ol:"idle")})};ye.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let k=h.getAttribute("data-action");if(k==="copy"){let O=F.getMessages().find(G=>G.id===S);if(O&&Oe.onCopy){let G=O.content||"";navigator.clipboard.writeText(G).then(()=>{h.classList.add("persona-message-action-success");let se=ae("check",14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let de=ae("copy",14,"currentColor",2);de&&(h.innerHTML="",h.appendChild(de))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),Oe.onCopy(O)}}else if(k==="read-aloud")F.toggleReadAloud(S);else if(k==="upvote"||k==="downvote"){let O=(Qa.get(S)??null)===k,G=k==="upvote"?"thumbs-up":"thumbs-down";if(O){Qa.delete(S),h.classList.remove("persona-message-action-active");let se=ae(G,14,"currentColor",2);se&&(h.innerHTML="",h.appendChild(se))}else{let se=k==="upvote"?"downvote":"upvote",de=b.querySelector(`[data-action="${se}"]`);if(de){de.classList.remove("persona-message-action-active");let st=ae(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);st&&(de.innerHTML="",de.appendChild(st))}Qa.set(S,k),h.classList.add("persona-message-action-active");let oe=ae(G,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(oe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ve=F.getMessages().find(ht=>ht.id===S);Ve&&Oe.onFeedback&&Oe.onFeedback({type:k,messageId:Ve.id,message:Ve})}}}),ye.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let k=h.getAttribute("data-approval-action");if(!k)return;let Q=k==="approve"?"approved":"denied",G=F.getMessages().find(de=>de.id===S);if(!G?.approval)return;let se=b.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?F.resolveWebMcpApproval(S,Q):F.resolveApproval(G.approval,Q)});let Je=null,vr=null,wr=()=>{},xr="none",Cs=null,fn={artifacts:[],selectedId:null},En=!1,gn=!1,Cr=!1,_o=!1,$l=()=>_o||fn.artifacts.some(i=>Eo(o.features?.artifacts,i.artifactType)==="panel"),As=()=>fn.artifacts.length>0&&!En&&$l(),gt={current:null},Ja=(i,g)=>{let h=F.getArtifactById(g),b=h?.markdown,S=h?.title||"artifact",k=h?.file,Q=h?.artifactType??"markdown";if(!b){let se=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let oe=F.getMessages().find(we=>we.id===se);if(oe?.rawContent)try{let we=JSON.parse(oe.rawContent);b=we?.props?.markdown,S=we?.props?.title||S,we?.props?.file&&typeof we.props.file=="object"&&(k=we.props.file),!h&&typeof we?.props?.artifactType=="string"&&(Q=we.props.artifactType)}catch{}}}return{markdown:b,title:S,file:k,artifactType:Q}};ye.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:Q,file:O}=Ja(h,b);if(!k)return;let{filename:G,mime:se,content:de}=Ud({title:Q,markdown:k,file:O}),oe=new Blob([de],{type:se}),we=URL.createObjectURL(oe),Ve=document.createElement("a");Ve.href=we,Ve.download=G,Ve.click(),URL.revokeObjectURL(we)}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-artifact-custom-action");if(!b)return;let S=h.closest("[data-artifact-inline]"),k=S?null:h.closest("[data-open-artifact]"),Q=S?S.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,G=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===b);if(!G)return;let{markdown:se,title:de,file:oe,artifactType:we}=Ja(h,Q??""),Ve={artifactId:Q,title:de,artifactType:we,markdown:se,file:oe};try{Promise.resolve(G.onClick(Ve)).catch(()=>{})}catch{}}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-copy-artifact");if(!b)return;let S=F.getArtifactById(b),k="";if(S)k=rs(S);else{let{markdown:Q,file:O,artifactType:G}=Ja(h,b);G==="markdown"&&(k=rs({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...O?{file:O}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let Q=ae("check",16,"currentColor",2);Q&&(h.replaceChildren(Q),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&h.replaceChildren(O)},1500))}).catch(()=>{})}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let b=h.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(En=!1,_o=!0,gn=!0,Cr=!0,F.selectArtifact(b),kn())}),ye.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),En=!1,_o=!0,F.selectArtifact(b),kn())}),ye.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 $o=Ie.composerOverlay,Uo=(i,g,h)=>{let b=g.trim();if(!b||!gt.current)return;let S=i.getAttribute("data-tool-call-id")??"",k=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:h.values??(h.source==="multi"?b.split(", "):[b]),isFreeText:k,source:h.source},bubbles:!0,composed:!0})),tr($o,S);let Q=gt.current.getMessages().find(O=>O.toolCall?.id===S);Q?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(Q,h.structured??b):gt.current.sendMessage(b)},uo=i=>{let g=gt.current;if(!g)return;let h=i.getAttribute("data-tool-call-id")??"",b=g.getMessages().find(S=>S.toolCall?.id===h);b&&g.persistAskUserQuestionProgress(b,{answers:Zs(i,b),currentIndex:pn(i)})},Ul=i=>Object.entries(i).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ya=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=pn(i),h=er(i);if(g>=h-1)return;let b=gt.current?.getMessages().find(S=>S.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ta(i,b,o,g+1),uo(i))};$o.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),S==="dismiss"){let k=b.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),tr($o,k);let Q=gt.current?.getMessages().find(O=>O.toolCall?.id===k);Q?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(Q),gt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(S==="pick"){let k=h.getAttribute("data-option-label");if(!k)return;let Q=b.getAttribute("data-multi-select")==="true",O=Yn(b);if(O&&Q){let G=Po(b)[pn(b)],se=new Set(Array.isArray(G)?G:[]);se.has(k)?se.delete(k):se.add(k),Zn(b,Array.from(se)),uo(b);return}if(O){Zn(b,k),uo(b),Ya(b);return}if(Q){let G=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",G?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!G);let se=b.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=Wi(b).length===0);return}Uo(b,k,{source:"pick",values:[k]});return}if(S==="submit-multi"){let k=Wi(b);if(k.length===0)return;Uo(b,k.join(", "),{source:"multi",values:k});return}if(S==="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(S==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let Q=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(Yn(b)){Zn(b,Q.trim()),uo(b),Ya(b);return}Uo(b,Q,{source:"free-text"});return}if(S==="next"||S==="back"){if(!gt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(oe=>oe.toolCall?.id===k);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let oe=Po(b)[pn(b)];(typeof oe!="string"||oe!==G)&&Zn(b,G)}let se=S==="next"?1:-1,de=pn(b)+se;ta(b,Q,o,de),uo(b);return}if(S==="submit-all"){if(!gt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(oe=>oe.toolCall?.id===k);if(!Q)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&Zn(b,G);let se=Zs(b,Q);gt.current.persistAskUserQuestionProgress(Q,{answers:se,currentIndex:pn(b)});let de=Ul(se);Uo(b,de||"(submitted)",{source:"submit-all",structured:se});return}if(S==="skip"){if(!gt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=gt.current.getMessages().find(we=>we.toolCall?.id===k);if(!Q)return;let O=Yn(b),G=pn(b),se=er(b),de=G>=se-1;if(!O){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),tr($o,k),Q.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(Q),gt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}Zn(b,"");let oe=b.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),de){let we=Zs(b,Q),Ve=Ul(we);Uo(b,Ve||"(skipped)",{source:"submit-all",structured:we});return}ta(b,Q,o,G+1),uo(b);return}}),$o.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let S=h.value;if(S.trim()){if(Yn(b)){Zn(b,S.trim()),uo(b),Ya(b);return}Uo(b,S,{source:"free-text"})}});let zl=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 h=$o.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),k=h.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",zl);let Un=null,vt=null,Ar=null,Ss=null,Za=()=>{},jl=!1,Ts="",Ms="";function ei(){Ss?.(),Ss=null}let ql=()=>{if(!Un||!vt)return;let i=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||h){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let b=Un.firstElementChild;if(!b||b===vt)return;let S=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${S}px`,vt.style.zIndex="5";let k=fl(Un,g),Q=b.offsetWidth+k/2-S/2;vt.style.left=`${Math.max(0,Q)}px`},Es=()=>{},Au=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>h?!1:I||Ft(o)},ks=()=>!Xt(o)||!As()||t.classList.contains("persona-artifact-narrow-host")||Au()||(t.ownerDocument.defaultView??window).innerWidth<Kb?"none":ul(o)?"detached":"welded",kn=()=>{if(!Je||!Xt(o))return;hs(t,o),ys(t,o),Es();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let h=As();Je.setVisible(h),Je.update(fn),En?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),gn=!1,Cr=!1):fn.artifacts.length>0&&$l()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),gn=!1,Cr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(b),Je.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Je.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Je.setTabFade(o.features?.artifacts?.layout?.tabFade),Je.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Cr&&(gn=!1),gn!==jl){let k=Je.element;gn?(Ts=k.style.width,Ms=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Ts&&(k.style.width=Ts),Ms&&(k.style.maxWidth=Ms),Ts="",Ms=""),jl=gn}t.classList.toggle("persona-artifact-expanded",gn),Je.setExpanded(gn);let S=ks();S!==xr&&(xr=S,wr()),Za()};if(Xt(o)){me.style.position="relative";let i=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Je=zp(o,{onSelect:h=>gt.current?.selectArtifact(h),onDismiss:()=>{En=!0,kn()},onToggleExpand:()=>{let h=!gn,b=fn.selectedId??fn.artifacts[fn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:h})!==!0&&(gn=h,h||(Cr=!1),kn())}}),Je.element.classList.add("persona-hidden"),Un=g,g.appendChild(i),g.appendChild(Je.element),Je.backdrop&&me.appendChild(Je.backdrop),me.appendChild(g),Za=()=>{if(!Un||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ar?.(),Ar=null,ei(),vt&&(vt.remove(),vt=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!vt){let b=m("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=t.ownerDocument,k=S.defaultView??window,Q=O=>{if(!Je||O.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;O.preventDefault(),ei();let G=O.clientX,se=Je.element.getBoundingClientRect().width,de=o.features?.artifacts?.layout,oe=Ve=>{let ht=Un.getBoundingClientRect().width,st=t.classList.contains("persona-artifact-welded-split"),jt=fl(Un,k),Bt=st?0:b.getBoundingClientRect().width||6,L=se-(Ve.clientX-G),Fe=Kp(L,ht,jt,Bt,de?.resizableMinWidth,de?.resizableMaxWidth);Je.element.style.width=`${Fe}px`,Je.element.style.maxWidth="none",ql()},we=()=>{S.removeEventListener("pointermove",oe),S.removeEventListener("pointerup",we),S.removeEventListener("pointercancel",we),Ss=null;try{b.releasePointerCapture(O.pointerId)}catch{}};Ss=we,S.addEventListener("pointermove",oe),S.addEventListener("pointerup",we),S.addEventListener("pointercancel",we);try{b.setPointerCapture(O.pointerId)}catch{}};b.addEventListener("pointerdown",Q),vt=b,Un.insertBefore(b,Je.element),Ar=()=>{b.removeEventListener("pointerdown",Q)}}if(vt){let b=As();vt.classList.toggle("persona-hidden",!b),ql()}},Es=()=>{if(!I||!Je||(o.launcher?.sidebarMode??!1)||Ft(o)&&un(o).reveal==="emerge")return;let b=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(S&&b.innerWidth<=k||!Vp(o,I))return;let Q=o.launcher?.width??o.launcherWidth??Nn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";As()?(me.style.width=O,me.style.maxWidth=O):(me.style.width=Q,me.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(vr=new ResizeObserver(()=>{kn()}),vr.observe(me))}else me.appendChild(ue);J()&&it&&(Ie.peekBanner&&it.appendChild(Ie.peekBanner),it.appendChild(z)),t.appendChild(Ee),it&&t.appendChild(it);let Ls=()=>{if(J()){me.style.width="100%",me.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},Jt=Ee.dataset.state==="expanded",zs=Lt.expandedSize??"anchored";if(!(Jt&&zs!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Hr=o.theme?.components?.panel,js=sr(o),Qo=(Rn,Ao)=>Rn==null||Rn===""?Ao:Kt(js,Rn)??Rn,Dr="1px solid var(--persona-border)",Si="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Co="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Qo(Hr?.border,Dr),ue.style.borderRadius=Qo(Hr?.borderRadius,Co),ue.style.boxShadow=Qo(Hr?.shadow,Si),ue.style.overflow="hidden";return}let i=Ft(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,Q=sr(o),O=(Lt,Jt)=>Lt==null||Lt===""?Jt:Kt(Q,Lt)??Lt,G=t.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,de=o.launcher?.mobileBreakpoint??640,oe=G.innerWidth<=de,we=se&&oe&&I,Ve=i&&se&&oe,ht=o.launcher?.position??"bottom-left",st=ht==="bottom-left"||ht==="top-left",jt=o.launcher?.zIndex??Ut,Bt="var(--persona-panel-border, 1px solid var(--persona-border))",L="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Fe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Se=S&&!we&&!Ve;Se?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let _e=Se?Bt:g||we?"none":Bt,St=Se?L:we?"none":g?st?"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":L;i&&!we&&!Se&&(St="none",_e="none");let pt=Se?Fe:g||we?"0":Fe,xt=O(k?.border,_e),yt=O(k?.shadow,St),_t=O(k?.borderRadius,pt),wo=ks(),ut=wo==="detached",pe=wo==="welded";t.classList.toggle("persona-artifact-detached-split",ut),t.classList.toggle("persona-artifact-welded-split",pe);let Ct="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)))))",ot=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&ul(o)&&b&&!i;t.classList.toggle("persona-artifact-chat-flush",ot);let je=ut||ot?"none":yt,Ye=ut?Bt:pe?"none":xt,kt=ut?Fe:_t;ot&&(Ye="none",kt="0");let He=k?.borderRadius!=null&&k.borderRadius!=="",Ze=ot&&!He?"0":_t,tn=ie.scrollTop;t.style.cssText="",Ee.style.cssText="",me.style.cssText="",ue.style.cssText="",ie.style.cssText="",z.style.cssText="",Pe&&(ie.style.display="none");let xo=()=>{if(tn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===tn)return;let Jt=ie.scrollHeight-ie.clientHeight;Jt<=0||(ie.scrollTop=Math.min(tn,Jt))})};if(we){Ee.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"),Ee.style.cssText=`
|
|
35
41
|
position: fixed !important;
|
|
36
42
|
inset: 0 !important;
|
|
37
43
|
width: 100% !important;
|
|
@@ -41,9 +47,9 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
41
47
|
padding: 0 !important;
|
|
42
48
|
display: flex !important;
|
|
43
49
|
flex-direction: column !important;
|
|
44
|
-
z-index: ${
|
|
50
|
+
z-index: ${jt} !important;
|
|
45
51
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
46
|
-
`,
|
|
52
|
+
`,me.style.cssText=`
|
|
47
53
|
position: relative !important;
|
|
48
54
|
display: flex !important;
|
|
49
55
|
flex-direction: column !important;
|
|
@@ -56,7 +62,7 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
56
62
|
padding: 0 !important;
|
|
57
63
|
box-shadow: none !important;
|
|
58
64
|
border-radius: 0 !important;
|
|
59
|
-
`,
|
|
65
|
+
`,ue.style.cssText=`
|
|
60
66
|
display: flex !important;
|
|
61
67
|
flex-direction: column !important;
|
|
62
68
|
flex: 1 1 0% !important;
|
|
@@ -67,20 +73,33 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
67
73
|
overflow: hidden !important;
|
|
68
74
|
border-radius: 0 !important;
|
|
69
75
|
border: none !important;
|
|
70
|
-
`,
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
76
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",z.style.flexShrink="0",j=!0,xo();return}let Us=o?.launcher?.width??o?.launcherWidth??Nn;if(!g&&!i)b&&h?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=Us,me.style.maxWidth=Us);else if(i)if(un(o).reveal==="emerge"&&!S){let Jt=un(o).width;me.style.width=Jt,me.style.maxWidth=Jt}else me.style.width="100%",me.style.maxWidth="100%";if(Es(),me.style.boxShadow=je,me.style.borderRadius=Ze,ut?me.style.border="none":pe&&(me.style.border=xt),ue.style.border=Ye,ue.style.borderRadius=kt,ue.style.boxShadow=ut&&!ot?Ct:"",ot&&(ue.style.background="transparent",ie.style.background="transparent",z.style.background="transparent",z.style.borderTop="none"),pe){let Lt=o.features?.artifacts?.layout;Cs=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||_t}else Cs=null;if(i&&!we&&!Se&&!ut&&!pe&&k?.border===void 0&&(ue.style.border="none",un(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!we&&pe&&k?.border===void 0&&(un(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",b&&(t.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",b&&(Ee.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.height="100%",ut||(me.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",z.style.flexShrink="0"),b&&(Se||ut||ot)&&!i&&(ot||(Ee.style.padding="var(--persona-panel-inset)"),Ee.style.background="var(--persona-panel-canvas-bg)"),Ee.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"),!g&&!b&&!i&&(wn[ht]??wn["bottom-right"]).split(" ").forEach(Jt=>Ee.classList.add(Jt)),g){let Lt=o.launcher?.sidebarWidth??"420px";S?Ee.style.cssText=`
|
|
77
|
+
position: fixed !important;
|
|
78
|
+
top: var(--persona-panel-inset) !important;
|
|
79
|
+
bottom: var(--persona-panel-inset) !important;
|
|
80
|
+
width: ${Lt} !important;
|
|
81
|
+
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
82
|
+
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
83
|
+
margin: 0 !important;
|
|
84
|
+
padding: 0 !important;
|
|
85
|
+
display: flex !important;
|
|
86
|
+
flex-direction: column !important;
|
|
87
|
+
z-index: ${jt} !important;
|
|
88
|
+
${st?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
89
|
+
`:Ee.style.cssText=`
|
|
90
|
+
position: fixed !important;
|
|
91
|
+
top: 0 !important;
|
|
92
|
+
bottom: 0 !important;
|
|
93
|
+
width: ${Lt} !important;
|
|
94
|
+
height: 100vh !important;
|
|
95
|
+
max-height: 100vh !important;
|
|
96
|
+
margin: 0 !important;
|
|
97
|
+
padding: 0 !important;
|
|
98
|
+
display: flex !important;
|
|
99
|
+
flex-direction: column !important;
|
|
100
|
+
z-index: ${jt} !important;
|
|
101
|
+
${st?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
102
|
+
`,me.style.cssText=`
|
|
84
103
|
position: relative !important;
|
|
85
104
|
display: flex !important;
|
|
86
105
|
flex-direction: column !important;
|
|
@@ -91,9 +110,10 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
91
110
|
min-height: 0 !important;
|
|
92
111
|
margin: 0 !important;
|
|
93
112
|
padding: 0 !important;
|
|
94
|
-
box-shadow: ${
|
|
95
|
-
border-radius: ${
|
|
96
|
-
|
|
113
|
+
box-shadow: ${je} !important;
|
|
114
|
+
border-radius: ${Ze} !important;
|
|
115
|
+
${ut?"border: none !important;":pe?`border: ${xt} !important;`:""}
|
|
116
|
+
`,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),ue.style.cssText=`
|
|
97
117
|
display: flex !important;
|
|
98
118
|
flex-direction: column !important;
|
|
99
119
|
flex: 1 1 0% !important;
|
|
@@ -102,15 +122,18 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
102
122
|
min-height: 0 !important;
|
|
103
123
|
max-height: 100% !important;
|
|
104
124
|
overflow: hidden !important;
|
|
105
|
-
border-radius: ${
|
|
106
|
-
border: ${
|
|
107
|
-
|
|
125
|
+
border-radius: ${kt} !important;
|
|
126
|
+
border: ${Ye} !important;
|
|
127
|
+
${ut&&!ot?`box-shadow: ${Ct} !important;`:""}
|
|
128
|
+
${ot?"background: transparent !important;":""}
|
|
129
|
+
`,z.style.cssText=`
|
|
108
130
|
flex-shrink: 0 !important;
|
|
109
131
|
border-top: none !important;
|
|
110
132
|
padding: 8px 16px 12px 16px !important;
|
|
111
|
-
`}if(!y&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Dt=p?"":"padding-top: 1.25em !important;",Vt=p?"":`z-index: ${(Ze=(Ho=r.launcher)==null?void 0:Ho.zIndex)!=null?Ze:bn} !important;`;ue.style.cssText+=Nt+Dt+Vt}Ge()};eo(),fs(n,r),ri(n,r),oi(n,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",Dr)}),lt.push(()=>{sr!==null&&clearTimeout(sr)});let nn=null,rn=null;lt.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),Dn&<.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Qn==null||Qn(),Qn=null,Go(),Ot&&(Ot.remove(),Ot=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),ae&<.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),Ae==null||Ae.destroy(),Ae=null,V==null||V.destroy(),V=null,Ce=null});let Ar=null,Ts=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=em(()=>{fs(n,r)}))};Ts(),lt.push(()=>{Ar&&(Ar(),Ar=null)}),lt.push(a);let Fr=(Rc=r.features)==null?void 0:Rc.streamAnimation;if(Fr!=null&&Fr.type&&Fr.type!=="none"){let l=hs(Fr.type,Fr.plugins);l&&(za(l,n),lt.push(()=>mm(n)))}let To=Rm(qt),Sr=null,F,Qo=l=>{var y,A;if(!F)return;let p=l!=null?l:F.getMessages(),f=((A=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:A.enabled)!==!1?Tu(p):null;f?To.render(f,F,ye,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(W=>W.role==="user")?To.render([],F,ye,p):To.render(r.suggestionChips,F,ye,p,r.suggestionChipsConfig)},ir=!1,Tr=om(),Or=new Map,Mr=new Map,lr=new Map,Xo=0,pa=No()!==null,fn=Na(),Cn=0,cr=null,An=!1,Mo=!1,dr=0,hn=null,Er=null,Jo=!1,Eo=!1,Yo=null,to=!0,no=!1,ot=null,x=4,j=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},De=(Bc=(Hc=r.voiceRecognition)==null?void 0:Hc.autoResume)!=null?Bc:!1,nt=l=>{i.emit("voice:state",{active:K.active,source:l,timestamp:Date.now()})},ct=()=>{w(l=>({...l,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},ii=()=>{var y,A;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=il(u.voiceState),p=!!l.active,f=Number((A=l.timestamp)!=null?A:0);K.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-f<Kv&&setTimeout(()=>{var W,z;K.active||(K.manuallyDeactivated=!1,((z=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:z.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),nt("restore"),F.isVoiceActive()&&ts()}):ma("restore"))},1e3)},ro=()=>F?ng(F.getMessages()).filter(l=>!l.__skipPersist):[];function Pn(l){if(!(c!=null&&c.save))return;let f={messages:l?ng(l):F?ro():[],metadata:u,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};try{let y=c.save(f);y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let Xt=null,oo=()=>ue.querySelector("#persona-scroll-container")||we,Xn=()=>{Xt!==null&&(cancelAnimationFrame(Xt),Xt=null),An=!1},Sn=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),Mo=!1,Xn()},In=()=>ir&&li()&&(Ft()!=="anchor-top"||rr()),Tn=()=>{let l=vt()||"Jump to latest",p=In();jt.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),dr>0?(Hn.textContent=String(dr),Hn.style.display="",jt.setAttribute("aria-label",`${l} (${dr} new)`)):(Hn.textContent="",Hn.style.display="none",jt.setAttribute("aria-label",p?`${l} (response streaming below)`:l))},gl=()=>{dr!==0&&(dr=0,Tn())},li=()=>Zt()?!fn.isFollowing():!yo(we,j),On=()=>{if(!Qt()||J){jt.parentNode&&jt.remove(),jt.style.display="none";return}jt.parentNode!==Te&&Te.appendChild(jt),jn();let p=Ir(we)>0&&li();p?Tn():gl(),jt.style.display=p?"":"none"},Ms=()=>{fn.pause()&&(Sn(),On())},so=()=>{fn.resume(),gl(),On()},ao=(l=!1)=>{Zt()&&fn.isFollowing()&&(!l&&!ir||(cr!==null&&(cancelAnimationFrame(cr),cr=null),Mo=!0,cr=requestAnimationFrame(()=>{cr=null,Mo=!1,fn.isFollowing()&&hg(oo(),l?220:140)})))},fl=(l,p,f,y=()=>!0)=>{let A=l.scrollTop,W=p(),z=W-A;if(Xn(),Math.abs(z)<1){An=!0,l.scrollTop=W,Cn=l.scrollTop,An=!1;return}let O=performance.now();An=!0;let D=oe=>1-Math.pow(1-oe,3),se=oe=>{if(!y()){Xn();return}let Z=p();Z!==W&&(W=Z,z=W-A);let ve=oe-O,Ne=Math.min(ve/f,1),Fe=D(Ne),$e=A+z*Fe;l.scrollTop=$e,Cn=l.scrollTop,Ne<1?Xt=requestAnimationFrame(se):(l.scrollTop=W,Cn=l.scrollTop,Xt=null,An=!1)};Xt=requestAnimationFrame(se)},hg=(l,p=500)=>{let f=Ir(l)-l.scrollTop;if(Math.abs(f)<1){Cn=l.scrollTop;return}if(Math.abs(f)>=q){Xn(),An=!0,l.scrollTop=Ir(l),Cn=l.scrollTop,An=!1;return}fl(l,()=>Ir(l),p,()=>fn.isFollowing())},hl=()=>{let l=oo();An=!0,l.scrollTop=Ir(l),Cn=l.scrollTop,An=!1,On()},yl=l=>{let p=0,f=l;for(;f&&f!==we;)p+=f.offsetTop,f=f.offsetParent;return p},bl=()=>{var W;if(Wr()!=="last-user-turn")return!1;let l=(W=F==null?void 0:F.getMessages())!=null?W:[];if(l.length<2)return!1;let p=[...l].reverse().find(z=>z.role==="user");if(!p)return!1;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=we.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let A=Math.min(Math.max(0,yl(y)-yr()),Ir(we));return An=!0,we.scrollTop=A,Cn=we.scrollTop,An=!1,Ft()==="follow"&&!yo(we,j)&&fn.pause(),On(),!0},vl=l=>{kn.style.height=`${Math.max(0,Math.round(l))}px`,hn&&(hn.spacerHeight=Math.max(0,l))},Es=()=>{Er!==null&&(cancelAnimationFrame(Er),Er=null),Xn(),hn=null,kn.style.height="0px"},yg=l=>{Er!==null&&cancelAnimationFrame(Er),Er=requestAnimationFrame(()=>{var D;Er=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=we.querySelector(`[data-message-id="${p}"]`);if(!f)return;let y=yl(f),A=(D=hn==null?void 0:hn.spacerHeight)!=null?D:0,W=we.scrollHeight-A,{targetScrollTop:z,spacerHeight:O}=cm({anchorOffsetTop:y,topOffset:yr(),viewportHeight:we.clientHeight,contentHeight:W});hn={initialSpacerHeight:O,contentHeightAtAnchor:W,spacerHeight:O},vl(O),fl(we,()=>z,220)})},bg=()=>{if(Zt()){if(!fn.isFollowing()||yo(we,1))return;ao(!ir);return}if(hn&&hn.initialSpacerHeight>0){let l=we.scrollHeight-hn.spacerHeight,p=dm({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:l});p!==hn.spacerHeight&&vl(p)}On()},vg=l=>{let p=Ft();p==="follow"?(so(),ao(!0)):p==="anchor-top"&&(to=!1,no=!0,yg(l))},wg=()=>{if(Ft()==="anchor-top"){if(no){to=!1;return}to=!0,Es(),so(),ao(!0)}},xg=l=>{let p=new Map;l.forEach(f=>{let y=G.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(i.emit("assistant:message",f),!Eo&&(Ft()!=="anchor-top"||rr())&&li()&&(dr+=1,Tn(),On(),Kr(dr===1?"1 new message below.":`${dr} new messages below.`))),f.role==="assistant"&&(y!=null&&y.streaming)&&f.streaming===!1&&i.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&i.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):i.emit("approval:requested",{approval:f.approval,message:f}))}),G.clear(),p.forEach((f,y)=>{G.set(y,f)})},Cg=(l,p,f)=>{var st,He,Ie,qe,Ge,bt;let y=document.createElement("div"),W=(()=>{var Be;let R=o.find(We=>We.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),z=(R,Be)=>Be==null?!1:typeof Be=="string"?(R.textContent=Be,!0):(R.appendChild(Be),!0),O=new Set,D=new Set,se=o.some(R=>R.renderAskUserQuestion),oe=[],Z=[],ve=r.enableComponentStreaming!==!1,Ne=r.approval!==!1,Fe=[];if(p.forEach(R=>{var pn,_n,Ve,It,$n,Lo,Po,Io,Wo,rs,os,Gt,Ro,co,po,$r,Ho;O.add(R.id);let Be=se&&Fo(R),We=Ne&&R.variant==="approval"&&!!R.approval,Xe=!Be&&R.role==="assistant"&&!R.variant&&ve&&Ym(R);if(!We&&lr.has(R.id)){let Ze=l.querySelector(`#wrapper-${R.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),lr.delete(R.id)}if(!Xe&&Mr.has(R.id)){let Ze=l.querySelector(`#wrapper-${R.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Mr.delete(R.id)}let Pt=Fo(R)?`:${(pn=R.agentMetadata)!=null&&pn.askUserQuestionAnswered?"a":"u"}:${(_n=R.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",Oe=rm(R,Xo)+Pt,Kt=Be||We||Xe?null:sm(Tr,R.id,Oe);if(Kt){y.appendChild(Kt.cloneNode(!0)),Fo(R)&&((Ve=R.toolCall)!=null&&Ve.id)&&((It=R.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=R.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(R.toolCall.id),Ca(R,r,je.composerOverlay));return}let xt=null,sn=o.find(Ze=>!!(R.variant==="reasoning"&&Ze.renderReasoning||R.variant==="tool"&&Ze.renderToolCall||!R.variant&&Ze.renderMessage)),Wn=(Lo=r.layout)==null?void 0:Lo.messages;if(Fo(R)&&((Po=R.agentMetadata)==null?void 0:Po.askUserQuestionAnswered)===!0){Or.delete(R.id);let Ze=l.querySelector(`#wrapper-${R.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(ki(R)&&((Wo=(Io=r.features)==null?void 0:Io.suggestReplies)==null?void 0:Wo.enabled)!==!1)return;if(Fo(R)&&((os=(rs=r.features)==null?void 0:rs.askUserQuestion)==null?void 0:os.enabled)!==!1){let Ze=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(Ze&&St.current){let Nt=Or.get(R.id),Dt=Nt!==Oe,Vt=null;if(Dt){let{payload:Ut,complete:un}=ls(R),Un=R.id,Lr=()=>{var cn;return(cn=St.current)==null?void 0:cn.getMessages().find(dn=>dn.id===Un)};Vt=Ze.renderAskUserQuestion({message:R,payload:Ut,complete:un,resolve:cn=>{var Zn;let dn=Lr();dn&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(dn,cn))},dismiss:()=>{var dn,Zn,uo;let cn=Lr();(dn=cn==null?void 0:cn.agentMetadata)!=null&&dn.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(cn),(uo=St.current)==null||uo.resolveAskUserQuestion(cn,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Dt&&Vt===null&&!$t){((Gt=R.agentMetadata)==null?void 0:Gt.awaitingLocalTool)===!0&&!((Ro=R.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(D.add(R.toolCall.id),Ca(R,r,je.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${R.id}`,mt.setAttribute("data-wrapper-id",R.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),y.appendChild(mt),oe.push({messageId:R.id,fingerprint:Oe,bubble:Vt});return}else{((co=R.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!((po=R.agentMetadata)!=null&&po.askUserQuestionAnswered)&&(D.add(R.toolCall.id),Ca(R,r,je.composerOverlay));return}}else if(We){let Ze=($r=o.find($t=>typeof $t.renderApproval=="function"))!=null?$r:s,Dt=lr.get(R.id)!==Oe,Vt=null;if(Dt&&(Ze!=null&&Ze.renderApproval)){let $t=R.id,mt=(Ut,un)=>{var Lr,cn,dn;let Un=(Lr=St.current)==null?void 0:Lr.getMessages().find(Zn=>Zn.id===$t);Un!=null&&Un.approval&&(Un.approval.toolType==="webmcp"?(cn=St.current)==null||cn.resolveWebMcpApproval(Un.id,Ut):(dn=St.current)==null||dn.resolveApproval(Un.approval,Ut,un))};Vt=Ze.renderApproval({message:R,defaultRenderer:()=>ti(R,r),config:r,approve:Ut=>mt("approved",Ut),deny:Ut=>mt("denied",Ut)})}if(Dt&&Vt===null){let $t=l.querySelector(`#wrapper-${R.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),lr.delete(R.id),xt=ti(R,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${R.id}`,$t.setAttribute("data-wrapper-id",R.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),y.appendChild($t),Fe.push({messageId:R.id,fingerprint:Oe,bubble:Vt});return}}else if(sn)if(R.variant==="reasoning"&&R.reasoning&&sn.renderReasoning){if(!Le)return;xt=sn.renderReasoning({message:R,defaultRenderer:()=>Gi(R,r),config:r})}else if(R.variant==="tool"&&R.toolCall&&sn.renderToolCall){if(!Pe)return;xt=sn.renderToolCall({message:R,defaultRenderer:()=>Xi(R,r),config:r})}else sn.renderMessage&&(xt=sn.renderMessage({message:R,defaultRenderer:()=>{let Ze=Ki(R,f,Wn,r.messageActions,Je,{loadingIndicatorRenderer:W,widgetConfig:r});return R.role!=="user"&&tl(Ze,R,r,F),Ze},config:r}));if(!xt&&Xe){let Ze=Zm(R);if(Ze){let Nt=Mr.get(R.id),Dt=Nt!==Oe,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Dt){let mt=Xm(Ze,{config:r,message:R,transform:f});if(mt)if(Vt){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let un=document.createElement("div");un.className="persona-mb-3 persona-text-sm persona-leading-relaxed",un.innerHTML=f({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(un)}Ut.appendChild(mt),$t=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${R.id}`,Ut.setAttribute("data-message-id",R.id),Ut.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let un=document.createElement("div");un.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",un.innerHTML=f({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ut.appendChild(un)}Ut.appendChild(mt),$t=Ut}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${R.id}`,mt.setAttribute("data-wrapper-id",R.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),y.appendChild(mt),Z.push({messageId:R.id,fingerprint:Oe,bubble:$t});return}}}if(!xt)if(R.variant==="reasoning"&&R.reasoning){if(!Le)return;xt=Gi(R,r)}else if(R.variant==="tool"&&R.toolCall){if(!Pe)return;xt=Xi(R,r)}else if(R.variant==="approval"&&R.approval){if(r.approval===!1)return;xt=ti(R,r)}else{let Ze=(Ho=r.layout)==null?void 0:Ho.messages;Ze!=null&&Ze.renderUserMessage&&R.role==="user"?xt=Ze.renderUserMessage({message:R,config:r,streaming:!!R.streaming}):Ze!=null&&Ze.renderAssistantMessage&&R.role==="assistant"?xt=Ze.renderAssistantMessage({message:R,config:r,streaming:!!R.streaming}):xt=Ki(R,f,Ze,r.messageActions,Je,{loadingIndicatorRenderer:W,widgetConfig:r}),R.role!=="user"&&xt&&tl(xt,R,r,F)}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${R.id}`,Bt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Bt.classList.add("persona-justify-end"),(xt==null?void 0:xt.getAttribute("data-persona-component-directive"))==="true"&&Bt.classList.add("persona-w-full"),Bt.appendChild(xt),am(Tr,R.id,Oe,Bt),y.appendChild(Bt)}),je.composerOverlay&&je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let We=Be.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&ds(je.composerOverlay,We)}),(He=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&He.grouped){let R=[],Be=[];p.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){Be.push(We);return}Be.length>1&&R.push(Be),Be=[]}),Be.length>1&&R.push(Be),R.forEach((We,Xe)=>{var pn,_n;let Pt=We.map(Ve=>Array.from(y.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ve.id)).filter(Ve=>!!Ve);if(Pt.length<2)return;let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id=`wrapper-tool-group-${Xe}-${We[0].id}`,Oe.setAttribute("data-wrapper-id",`tool-group-${Xe}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${We.length} tools`,Wn=(_n=(pn=r.toolCall)==null?void 0:pn.renderGroupedSummary)==null?void 0:_n.call(pn,{messages:We,toolCalls:We.map(Ve=>Ve.toolCall).filter(Ve=>!!Ve),defaultSummary:sn,config:r});z(xt,Wn)||(xt.textContent=sn);let Bt=document.createElement("div");Bt.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(xt,Bt),Oe.appendChild(Kt),Pt[0].before(Oe),Pt.forEach((Ve,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ve),Bt.appendChild($n)})})}im(Tr,O);let $e=p.some(R=>R.role==="assistant"&&R.streaming),ze=p[p.length-1],ut=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(ir&&p.some(R=>R.role==="user")&&!$e&&!ut){let R={config:r,streaming:!0,location:"standalone",defaultRenderer:sa},Be=o.find(Xe=>Xe.renderLoadingIndicator),We=null;if(Be!=null&&Be.renderLoadingIndicator&&(We=Be.renderLoadingIndicator(R)),We===null&&((Ie=r.loadingIndicator)!=null&&Ie.render)&&(We=r.loadingIndicator.render(R)),We===null&&(We=sa()),We){let Xe=document.createElement("div"),Pt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;Xe.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Xe.setAttribute("data-typing-indicator","true"),Xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Xe.appendChild(We);let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id="wrapper-typing-indicator",Oe.setAttribute("data-wrapper-id","typing-indicator"),Oe.appendChild(Xe),y.appendChild(Oe)}}if(!ir&&p.length>0){let R=p[p.length-1],Be={config:r,lastMessage:R,messageCount:p.length},We=o.find(Pt=>Pt.renderIdleIndicator),Xe=null;if(We!=null&&We.renderIdleIndicator&&(Xe=We.renderIdleIndicator(Be)),Xe===null&&((Ge=r.loadingIndicator)!=null&&Ge.renderIdle)&&(Xe=r.loadingIndicator.renderIdle(Be)),Xe){let Pt=document.createElement("div"),Oe=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.className=Oe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Xe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),y.appendChild(Kt)}}if(Ba(l,y),oe.length>0)for(let{messageId:R,fingerprint:Be,bubble:We}of oe){let Xe=l.querySelector(`#wrapper-${R}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),Or.set(R,Be))}if(Or.size>0)for(let R of Or.keys())O.has(R)||Or.delete(R);if(Z.length>0)for(let{messageId:R,fingerprint:Be,bubble:We}of Z){let Xe=l.querySelector(`#wrapper-${R}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),Mr.set(R,Be))}if(Mr.size>0)for(let R of Mr.keys())O.has(R)||Mr.delete(R);if(Fe.length>0)for(let{messageId:R,fingerprint:Be,bubble:We}of Fe){let Xe=l.querySelector(`#wrapper-${R}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),lr.set(R,Be))}if(lr.size>0)for(let R of lr.keys())O.has(R)||lr.delete(R)},ks=(l,p,f)=>{Cg(l,p,f),Yr()},Ls=null,Ag=()=>{var f;if(Ls)return;let l=y=>{let A=y.composedPath();A.includes(ue)||it&&A.includes(it)||_t(!1,"user")};Ls=l,((f=n.ownerDocument)!=null?f:document).addEventListener("pointerdown",l,!0)},wl=()=>{var p;if(!Ls)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",Ls,!0),Ls=null};lt.push(()=>wl());let Ps=null,Sg=()=>{var f;if(Ps)return;let l=y=>{y.key==="Escape"&&(y.isComposing||_t(!1,"user"))};Ps=l,((f=n.ownerDocument)!=null?f:document).addEventListener("keydown",l,!0)},xl=()=>{var p;if(!Ps)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",Ps,!0),Ps=null};lt.push(()=>xl());let Is=!1,Cl=new Set,Tg=()=>{var p,f,y,A;let l=(y=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.peek)==null?void 0:y.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},Zo=()=>{var ut,st,He,Ie;if(!I())return;let l=je.peekBanner,p=je.peekTextNode;if(!l||!p)return;if(N){l.classList.remove("persona-pill-peek--visible");return}let f=(ut=F==null?void 0:F.getMessages())!=null?ut:[],y;for(let qe=f.length-1;qe>=0;qe--){let Ge=f[qe];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let A=y.content,W=!!y.streaming,z=Tg(),O=_a(z),D=O.type!=="none"?hs(O.type,z==null?void 0:z.plugins):null,se=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,y))===!0,oe=D!==null&&(W||se);oe&&D&&!Cl.has(D.name)&&(za(D,n),Cl.add(D.name));let Z=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(He=p.dataset.personaPeekStreamClass)!=null?He:null;ve&&ve!==Z&&(p.classList.remove(ve),delete p.dataset.personaPeekStreamClass),Z&&ve!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),oe?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=oe?$a(A,O.buffer,D,y,W):A;if(oe&&O.placeholder==="skeleton"&&W&&(!Ne||!Ne.trim())){let qe=document.createElement("div"),Ge=ea();Ge.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ge),Ba(p,qe)}else{let qe=Math.max(0,Ne.length-100),Ge=Ne.length>100?Ne.slice(-100):Ne,bt=mo(Ge);if(!oe||!D){let R=Ne.length>100?`\u2026${Ge}`:Ge;p.textContent!==R&&(p.textContent=R)}else{let R=bt;(D.wrap==="char"||D.wrap==="word")&&(R=Zs(bt,D.wrap,`peek-${y.id}`,{skipTags:D.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=R,D.useCaret&&Ge.length>0){let We=Ua(),Xe=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Xe[Xe.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):Be.appendChild(We)}Ba(p,Be),(Ie=D.onAfterRender)==null||Ie.call(D,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let ze=ir||Is;l.classList.toggle("persona-pill-peek--visible",ze)};if(I()){let l=je.peekBanner;if(l){let y=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",y),lt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{Is||(Is=!0,Zo())},f=()=>{Is&&(Is=!1,Zo())};Q.addEventListener("pointerenter",p),Q.addEventListener("pointerleave",f),lt.push(()=>{Q.removeEventListener("pointerenter",p),Q.removeEventListener("pointerleave",f)}),it&&(it.addEventListener("pointerenter",p),it.addEventListener("pointerleave",f),lt.push(()=>{it.removeEventListener("pointerenter",p),it.removeEventListener("pointerleave",f)}))}let Mg=l=>{var ve,Ne,Fe,$e,ze,ut,st,He;let p=(Ne=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Ne:{},f=(Fe=p.expandedSize)!=null?Fe:"anchored",y=($e=p.bottomOffset)!=null?$e:"16px",A=p.collapsedMaxWidth,W=(ze=p.expandedMaxWidth)!=null?ze:"880px",z=(ut=p.expandedTopOffset)!=null?ut:"5vh",O=(st=p.modalMaxWidth)!=null?st:"880px",D=(He=p.modalMaxHeight)!=null?He:"min(90vh, 800px)",se="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Z=ue.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",it){let Ie=it.style;Ie.bottom=y,Ie.width=A!=null?A:""}if(l&&f!=="fullscreen"){if(f==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=O,Z.maxWidth=se,Z.maxHeight=D,Z.height=D;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${oe})`,Z.top=z,Z.width=W,Z.maxWidth=se}},Ws=()=>{var D,se,oe,Z,ve,Ne,Fe,$e;if(!$())return;if(I()){let ut=(oe=((se=(D=r.launcher)==null?void 0:D.composerBar)!=null?se:{}).expandedSize)!=null?oe:"anchored",st=N?"expanded":"collapsed";ue.dataset.state=st,ue.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ue.style.removeProperty("display"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Mg(N),Te.style.display=N?"flex":"none",eo(),N?(Ag(),Sg()):(wl(),xl()),Zo();return}let l=mn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,f=(Ne=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Ne:640,y=($e=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?$e:!0,A=p.innerWidth<=f,W=y&&A&&L,z=mr(r).reveal;N?(ue.style.removeProperty("display"),ue.style.display=l?"flex":"",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":on&&(on.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!W?(ue.style.removeProperty("display"),ue.style.display="flex",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.setProperty("display","none","important"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.display="",ue.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=l?"none":"":on&&(on.style.display=l?"none":""))},_t=(l,p="user")=>{var W,z;if(!$()||N===l)return;let f=N;N=l,Ws();let y=(()=>{var Fe,$e,ze,ut,st,He,Ie,qe,Ge,bt;let O=($e=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?$e:!1,D=(ze=n.ownerDocument.defaultView)!=null?ze:window,se=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Ie=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?Ie:640,Z=D.innerWidth<=oe,ve=mn(r)&&se&&Z,Ne=I()&&((bt=(Ge=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ge.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return O||se&&Z&&L||ve||Ne})();if(N&&y){if(!nn){let O=n.getRootNode(),D=O instanceof ShadowRoot?O.host:n.closest(".persona-host");D&&(nn=_i(D,(z=(W=r.launcher)==null?void 0:W.zIndex)!=null?z:bn))}rn||(rn=$i(n.ownerDocument))}else N||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);N&&(Rs(),bl()||(Ft()==="follow"?ao(!0):hl()));let A={open:N,source:p,timestamp:Date.now()};N&&!f?i.emit("widget:opened",A):!N&&f&&i.emit("widget:closed",A),i.emit("widget:state",{open:N,launcherEnabled:L,voiceActive:K.active,streaming:F.isStreaming()})},ci=l=>{ge(l?"stop":"send"),H&&(H.disabled=l),To.buttons.forEach(p=>{p.disabled=l}),Re.dataset.personaComposerStreaming=l?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},di=()=>{K.active||ye&&ye.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>di(),200)});let Al=()=>{var f,y,A,W,z,O,D,se,oe,Z,ve;fr.textContent=(y=(f=r.copy)==null?void 0:f.welcomeTitle)!=null?y:"Hello \u{1F44B}",hr.textContent=(W=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ye.placeholder=(O=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?O:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Ne=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&oe)&&!(F!=null&&F.isStreaming())&&(pe.textContent=(ve=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ve:"Send"),ye.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ye.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{w(p=>({...p,sessionId:l}))}});let ko=null,Eg=()=>{ko==null&&(ko=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(ko),ko=null;return}let p=Date.now();l.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=Sa(p-y))})},100))};F=new Wa(r,{onMessagesChanged(l){var A,W;ks(Ye,l,Y),Eg(),Qo(l),ao(!ir),xg(l);let p=[...l].reverse().find(z=>z.role==="user"),f=[...l].reverse().find(z=>z.role==="assistant");l.length===0&&(Es(),to=!0,no=!1),!Jo||Eo?(Jo=!0,Yo=(A=p==null?void 0:p.id)!=null?A:null,ot=(W=f==null?void 0:f.id)!=null?W:null):p&&p.id!==Yo?(Yo=p.id,vg(p.id)):f&&f.id!==ot&&wg(),f&&(ot=f.id);let y=K.lastUserMessageId;p&&p.id!==y&&(K.lastUserMessageId=p.id,i.emit("user:message",p)),K.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Pn(l),Zo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};ft(gn,(A=>{var W,z,O,D,se,oe;return A==="idle"?(W=p.idleText)!=null?W:tn.idle:A==="connecting"?(z=p.connectingText)!=null?z:tn.connecting:A==="connected"?(O=p.connectedText)!=null?O:tn.connected:A==="error"?(D=p.errorText)!=null?D:tn.error:A==="paused"?(se=p.pausedText)!=null?se:tn.paused:A==="resuming"?(oe=p.resumingText)!=null?oe:tn.resuming:tn[A]})(l),p,l)},onStreamingChanged(l){ir=l,ci(l),F&&ks(Ye,F.getMessages(),Y),l||ao(!0),On(),Kr(l?"Responding\u2026":"Response complete."),Zo()},onVoiceStatusChanged(l){var p,f;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype")switch(l){case"listening":_r(),ts();break;case"processing":_r(),Wg();break;case"speaking":_r(),Rg();break;default:l==="idle"&&F.isBargeInActive()?(_r(),ts(),H==null||H.setAttribute("aria-label","End voice session")):(K.active=!1,_r(),nt("system"),ct());break}},onArtifactsState(l){Nn=l,Cr(),Pn()},onReconnect(l){var y;let{executionId:p,lastEventId:f}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:p,after:f}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:p,after:f,attempt:(y=l.attempt)!=null?y:1}):i.emit("stream:resumed",{executionId:p,after:f})}}),St.current=F,lt.push(()=>F.cancel());let pi=null;if(F.onReadAloudChange((l,p)=>{var A;Xr=l,Jr=p,Yr();let f=l!=null?l:pi;l&&(pi=l);let y=f&&(A=F.getMessages().find(W=>W.id===f))!=null?A:null;i.emit("message:read-aloud",{messageId:f,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(pi=null)}),Jo=!0,((Nc=(Dc=r.voiceRecognition)==null?void 0:Dc.provider)==null?void 0:Nc.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&F.setSSEEventCallback((l,p)=>{var f;(f=r.onSSEEvent)==null||f.call(r,l,p),X==null||X.processEvent(l,p),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})});let Sl=()=>{r.resume&&typeof r.reconnectStream=="function"&&F.resumeFromHandle(r.resume)};g?g.then(l=>{var p,f,y;if(l){if(l.metadata&&(u=il(l.metadata),S.syncFromMetadata()),(p=l.messages)!=null&&p.length){Eo=!0;try{F.hydrateMessages(l.messages)}finally{Eo=!1}}(f=l.artifacts)!=null&&f.length&&F.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Sl()):Sl();let Tl=()=>{var p,f,y;!I()||N||!((y=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.expandOnSubmit)==null||y)||_t(!0,"auto")},Ml=l=>{var A;if(l.preventDefault(),F.isStreaming()){F.cancel(),X==null||X.reset(),Ae==null||Ae.update();return}let p=ye.value.trim(),f=(A=At==null?void 0:At.hasAttachments())!=null?A:!1;if(!p&&!f)return;Tl();let y;f&&(y=[],y.push(...At.getContentParts()),p&&y.push(Wi(p))),ye.value="",ye.style.height="auto",ua(),F.sendMessage(p,{contentParts:y}),f&&At.clearAttachments()},kg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},ui={...Da},mi=!1,ua=()=>{ui={...Da}},Lg=()=>F.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Pg=l=>{if(!ye)return;mi=!0,ye.value=l,ye.dispatchEvent(new Event("input",{bubbles:!0})),mi=!1;let p=ye.value.length;ye.setSelectionRange(p,p)},El=()=>{mi||ua()},kl=l=>{if(ye){if(kg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=ye.selectionStart===0&&ye.selectionEnd===0,f=nm({direction:l.key==="ArrowUp"?"up":"down",history:Lg(),currentValue:ye.value,atStart:p,state:ui});if(ui=f.state,f.handled){l.preventDefault(),f.value!==void 0&&Pg(f.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}ua(),l.preventDefault(),pe.click()}}},Ll=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(Te)&&(F.cancel(),X==null||X.reset(),Ae==null||Ae.update(),ua(),l.preventDefault(),l.stopImmediatePropagation())},Pl=async l=>{var f;if(((f=r.attachments)==null?void 0:f.enabled)!==!0||!At)return;let p=Qv(l.clipboardData);p.length!==0&&(l.preventDefault(),await At.handleFiles(p))},Jn=null,kr=!1,es=null,pt=null,Il=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ma=(l="user")=>{var W,z,O,D,se,oe,Z;if(kr||F.isStreaming())return;let p=Il();if(!p)return;Jn=new p;let y=(z=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?z:2e3;Jn.continuous=!0,Jn.interimResults=!0,Jn.lang="en-US";let A=ye.value;Jn.onresult=ve=>{let Ne="",Fe="";for(let ze=0;ze<ve.results.length;ze++){let ut=ve.results[ze],st=ut[0].transcript;ut.isFinal?Ne+=st+" ":Fe=st}let $e=A+Ne+Fe;ye.value=$e,es&&clearTimeout(es),(Ne||Fe)&&(es=window.setTimeout(()=>{let ze=ye.value.trim();ze&&Jn&&kr&&(io(),ye.value="",ye.style.height="auto",F.sendMessage(ze,{viaVoice:!0}))},y))},Jn.onerror=ve=>{ve.error!=="no-speech"&&io()},Jn.onend=()=>{if(kr){let ve=ye.value.trim();ve&&ve!==A.trim()&&(ye.value="",ye.style.height="auto",F.sendMessage(ve,{viaVoice:!0})),io()}};try{if(Jn.start(),kr=!0,K.active=!0,l!=="system"&&(K.manuallyDeactivated=!1),nt(l),ct(),H){let ve=(O=r.voiceRecognition)!=null?O:{};pt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Z=(oe=ve.iconSize)!=null?oe:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Ne=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,$e=ve.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let ze=H.querySelector("svg");ze&&ze.setAttribute("stroke",Fe)}$e&&(H.style.borderColor=$e),H.setAttribute("aria-label","Stop voice recognition")}}catch{io("system")}},io=(l="user")=>{if(kr){if(kr=!1,es&&(clearTimeout(es),es=null),Jn){try{Jn.stop()}catch{}Jn=null}if(K.active=!1,nt(l),ct(),H){if(H.classList.remove("persona-voice-recording"),pt){H.style.backgroundColor=pt.backgroundColor,H.style.color=pt.color,H.style.borderColor=pt.borderColor;let p=H.querySelector("svg");p&&p.setAttribute("stroke",pt.color||"currentColor"),pt=null}H.setAttribute("aria-label","Start voice recognition")}}},Ig=(l,p)=>{var st,He,Ie,qe,Ge,bt,R,Be,We;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",A=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(f||y||A))return null;let z=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let D=(Ie=l==null?void 0:l.iconName)!=null?Ie:"mic",se=(qe=p==null?void 0:p.size)!=null?qe:"40px",oe=(Ge=l==null?void 0:l.iconSize)!=null?Ge:se,Z=parseFloat(oe)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,Ne=(R=l==null?void 0:l.iconColor)!=null?R:p==null?void 0:p.textColor;O.style.width=oe,O.style.height=oe,O.style.minWidth=oe,O.style.minHeight=oe,O.style.fontSize="18px",O.style.lineHeight="1",Ne?O.style.color=Ne:O.style.color="var(--persona-text, #111827)";let $e=he(D,Z,Ne||"currentColor",1.5);$e?O.appendChild($e):O.textContent="\u{1F3A4}",ve?O.style.backgroundColor=ve:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),z.appendChild(O);let ze=(Be=l==null?void 0:l.tooltipText)!=null?Be:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&ze){let Xe=b("div","persona-send-button-tooltip");Xe.textContent=ze,z.appendChild(Xe)}return{micButton:O,micButtonWrapper:z}},gi=()=>{var p,f,y,A,W;if(!H||pt)return;let l=(p=r.voiceRecognition)!=null?p:{};pt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(f=l.iconName)!=null?f:"mic",iconSize:parseFloat((W=(A=l.iconSize)!=null?A:(y=r.sendButton)==null?void 0:y.size)!=null?W:"40")||24}},fi=(l,p)=>{var W,z,O,D,se;if(!H)return;let f=H.querySelector("svg");f&&f.remove();let y=(se=pt==null?void 0:pt.iconSize)!=null?se:parseFloat((D=(O=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?O:(z=r.sendButton)==null?void 0:z.size)!=null?D:"40")||24,A=he(l,y,p,1.5);A&&H.appendChild(A)},ga=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ts=()=>{var A;if(!H)return;gi();let l=(A=r.voiceRecognition)!=null?A:{},p=l.recordingBackgroundColor,f=l.recordingIconColor,y=l.recordingBorderColor;if(ga(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=f!=null?f:"var(--persona-voice-recording-indicator, #ffffff)",f){let W=H.querySelector("svg");W&&W.setAttribute("stroke",f)}y&&(H.style.borderColor=y),H.setAttribute("aria-label","Stop voice recognition")},Wg=()=>{var O,D,se,oe,Z,ve,Ne,Fe;if(!H)return;gi();let l=(O=r.voiceRecognition)!=null?O:{},p=F.getVoiceInterruptionMode(),f=(D=l.processingIconName)!=null?D:"loader",y=(oe=(se=l.processingIconColor)!=null?se:pt==null?void 0:pt.color)!=null?oe:"",A=(ve=(Z=l.processingBackgroundColor)!=null?Z:pt==null?void 0:pt.backgroundColor)!=null?ve:"",W=(Fe=(Ne=l.processingBorderColor)!=null?Ne:pt==null?void 0:pt.borderColor)!=null?Fe:"";ga(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=A,H.style.borderColor=W;let z=y||"currentColor";H.style.color=z,fi(f,z),H.setAttribute("aria-label","Processing voice input"),p==="none"&&(H.style.cursor="default")},Rg=()=>{var se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie;if(!H)return;gi();let l=(se=r.voiceRecognition)!=null?se:{},p=F.getVoiceInterruptionMode(),f=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(oe=l.speakingIconName)!=null?oe:f,A=(Fe=l.speakingIconColor)!=null?Fe:p==="barge-in"?(ve=(Z=l.recordingIconColor)!=null?Z:pt==null?void 0:pt.color)!=null?ve:"":(Ne=pt==null?void 0:pt.color)!=null?Ne:"",W=(ut=l.speakingBackgroundColor)!=null?ut:p==="barge-in"?($e=l.recordingBackgroundColor)!=null?$e:"var(--persona-voice-recording-bg, #ef4444)":(ze=pt==null?void 0:pt.backgroundColor)!=null?ze:"",z=(Ie=l.speakingBorderColor)!=null?Ie:p==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(He=pt==null?void 0:pt.borderColor)!=null?He:"";ga(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=W,H.style.borderColor=z;let O=A||"currentColor";H.style.color=O,fi(y,O);let D=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",D),p==="none"&&(H.style.cursor="default"),p==="barge-in"&&H.classList.add("persona-voice-recording")},_r=()=>{var l,p,f;H&&(ga(),pt&&(H.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",H.style.color=(p=pt.color)!=null?p:"",H.style.borderColor=(f=pt.borderColor)!=null?f:"",fi(pt.iconName,pt.color||"currentColor"),pt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},fa=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let f=F.getVoiceStatus(),y=F.getVoiceInterruptionMode();if(y==="none"&&(f==="processing"||f==="speaking"))return;if(y==="cancel"&&(f==="processing"||f==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),nt("user"),_r()});return}F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),K.manuallyDeactivated=!F.isVoiceActive(),ct(),nt("user"),F.isVoiceActive()?ts():_r()});return}if(kr){let f=ye.value.trim();K.manuallyDeactivated=!0,ct(),io("user"),f&&(ye.value="",ye.style.height="auto",F.sendMessage(f))}else K.manuallyDeactivated=!1,ct(),ma("user")};vr=fa,H&&(H.addEventListener("click",fa),lt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),_r()):io("system"),H&&H.removeEventListener("click",fa)}));let Hg=i.on("assistant:complete",()=>{De&&(K.active||K.manuallyDeactivated||De==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!K.active&&!K.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),nt("auto"),F.isVoiceActive()&&ts()}):ma("auto"))},600))});lt.push(Hg);let Bg=i.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});lt.push(Bg);let Wl=()=>{_t(!N,"user")},Yt=null,on=null;if(L&&!I()){let{instance:l,element:p}=qi({config:r,plugins:o,onToggle:Wl});Yt=l,l||(on=p)}Yt?n.appendChild(Yt.element):on&&n.appendChild(on),Ws(),Qo(),Al(),ci(F.isStreaming()),bl()||(Ft()==="follow"?ao(!0):hl()),ii(),k&&(!L||I()?setTimeout(()=>di(),0):N&&setTimeout(()=>di(),200));let Rs=()=>{var D,se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie,qe,Ge,bt,R,Be,We,Xe,Pt,Oe;if(I()){jn(),Ws();return}let l=mn(r),p=(se=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?se:!1,f=l||p||((Z=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Z:!1),y=(ve=n.ownerDocument.defaultView)!=null?ve:window,A=(Fe=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Fe:!0,W=(ze=($e=r.launcher)==null?void 0:$e.mobileBreakpoint)!=null?ze:640,z=y.innerWidth<=W,O=A&&z&&L;try{if(O){eo(),fs(n,r);return}if(_&&(_=!1,eo(),fs(n,r)),!L&&!l){Q.style.height="",Q.style.width="";return}if(!p&&!l){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,xt=Kt!=null?Kt:jr;Q.style.width=xt,Q.style.maxWidth=xt}if(So(),!f){let Kt=y.innerHeight,xt=64,sn=(Ie=(He=r.launcher)==null?void 0:He.heightOffset)!=null?Ie:0,Wn=Math.max(200,Kt-xt),Bt=Math.min(640,Wn),pn=Math.max(200,Bt-sn);Q.style.height=`${pn}px`}}finally{if(jn(),Ws(),N&&L){let xt=((qe=n.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((bt=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?bt:640),sn=(Be=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?Be:!1,Wn=(Xe=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Xe:!0,Bt=mn(r)&&Wn&&xt,pn=sn||Wn&&xt&&L||Bt;if(pn&&!rn){let _n=n.getRootNode(),Ve=_n instanceof ShadowRoot?_n.host:n.closest(".persona-host");Ve&&!nn&&(nn=_i(Ve,(Oe=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?Oe:bn)),rn=$i(n.ownerDocument)}else pn||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Rs();let Rl=(Fc=n.ownerDocument.defaultView)!=null?Fc:window;if(Rl.addEventListener("resize",Rs),lt.push(()=>Rl.removeEventListener("resize",Rs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{jn()});l.observe(Re),lt.push(()=>l.disconnect())}Cn=we.scrollTop;let Hl=Ir(we),Dg=()=>{let l=we.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},hi=()=>lm(Dg(),we),Bl=()=>{let l=we.scrollTop,p=Ir(we),f=p<Hl;if(Hl=p,!Zt()){Cn=l,On();return}let{action:y,nextLastScrollTop:A}=Fa({following:fn.isFollowing(),currentScrollTop:l,lastScrollTop:Cn,nearBottom:yo(we,j),userScrollThreshold:x,isAutoScrolling:An||Mo||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Cn=A,y==="resume"){hi()||so();return}y==="pause"&&Ms()};if(we.addEventListener("scroll",Bl,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Bl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{bg()});l.observe(Ye),l.observe(we),lt.push(()=>l.disconnect())}let Dl=()=>{Zt()&&fn.isFollowing()&&hi()&&Ms()},Nl=we.ownerDocument;Nl.addEventListener("selectionchange",Dl),lt.push(()=>{Nl.removeEventListener("selectionchange",Dl)});let Ng=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Fl=l=>{nr()&&Zt()&&fn.isFollowing()&&Ng.has(l.key)&&Ms()},Ol=l=>{if(!nr()||!Zt()||!fn.isFollowing())return;let p=l.target;p&&p.closest("a, button, [tabindex], input, textarea, select")&&Ms()};we.addEventListener("keydown",Fl),we.addEventListener("focusin",Ol),lt.push(()=>{we.removeEventListener("keydown",Fl),we.removeEventListener("focusin",Ol)});let _l=l=>{if(!Zt())return;let p=Oa({following:fn.isFollowing(),deltaY:l.deltaY,nearBottom:yo(we,j),resumeWhenNearBottom:!0});p==="pause"?Ms():p==="resume"&&!hi()&&so()};we.addEventListener("wheel",_l,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",_l)),jt.addEventListener("click",()=>{Es(),we.scrollTop=we.scrollHeight,Cn=we.scrollTop,so(),ao(!0),On()}),lt.push(()=>jt.remove()),lt.push(()=>{Sn(),Es()});let $l=()=>{Ue&&(Sr&&(Ue.removeEventListener("click",Sr),Sr=null),$()?(Ue.style.display="",Sr=()=>{_t(!1,"user")},Ue.addEventListener("click",Sr)):Ue.style.display="none")};$l(),(()=>{let{clearChatButton:l}=je;l&&l.addEventListener("click",()=>{F.clearMessages(),Tr.clear(),so(),ds(je.composerOverlay);try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),c!=null&&c.clear)try{let f=c.clear();f instanceof Promise&&f.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}u={},S.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),Ae==null||Ae.update()})})(),Ct&&Ct.addEventListener("submit",Ml),ye==null||ye.addEventListener("keydown",kl),ye==null||ye.addEventListener("input",El),ye==null||ye.addEventListener("paste",Pl);let Ul=(Oc=n.ownerDocument)!=null?Oc:document;Ul.addEventListener("keydown",Ll,!0);let zl="persona-attachment-drop-active",Hs=0,yi=()=>{Hs=0,Te.classList.remove(zl)},ns=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},ql=l=>{!si(l.dataTransfer)||!ns()||(Hs++,Hs===1&&Te.classList.add(zl))},jl=l=>{!si(l.dataTransfer)||!ns()||(Hs--,Hs<=0&&yi())},Vl=l=>{!si(l.dataTransfer)||!ns()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Kl=l=>{var f;if(!si(l.dataTransfer)||!ns())return;l.preventDefault(),l.stopPropagation(),yi();let p=Array.from((f=l.dataTransfer.files)!=null?f:[]);p.length!==0&&At.handleFiles(p)},lo=!0;Te.addEventListener("dragenter",ql,lo),Te.addEventListener("dragleave",jl,lo),n.addEventListener("dragover",Vl,lo),n.addEventListener("drop",Kl,lo);let ha=n.ownerDocument,Gl=l=>{ns()&&l.preventDefault()},Ql=l=>{ns()&&l.preventDefault()};ha.addEventListener("dragover",Gl),ha.addEventListener("drop",Ql),lt.push(()=>{Ct&&Ct.removeEventListener("submit",Ml),ye==null||ye.removeEventListener("keydown",kl),ye==null||ye.removeEventListener("input",El),ye==null||ye.removeEventListener("paste",Pl),Ul.removeEventListener("keydown",Ll,!0)}),lt.push(()=>{Te.removeEventListener("dragenter",ql,lo),Te.removeEventListener("dragleave",jl,lo),n.removeEventListener("dragover",Vl,lo),n.removeEventListener("drop",Kl,lo),ha.removeEventListener("dragover",Gl),ha.removeEventListener("drop",Ql),yi()}),lt.push(()=>{F.cancel()}),Yt?lt.push(()=>{Yt==null||Yt.destroy()}):on&<.push(()=>{on==null||on.remove()});let en={update(l){var Un,Lr,cn,dn,Zn,uo,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,wd,xd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,zd,qd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,wp,xp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,Up,zp,qp,jp,Vp,Kp,Gp,Qp,Xp,Jp,Yp;let p=r.toolCall,f=r.messageActions,y=(Un=r.layout)==null?void 0:Un.messages,A=r.colorScheme,W=r.loadingIndicator,z=r.iterationDisplay,O=(Lr=r.features)==null?void 0:Lr.showReasoning,D=(cn=r.features)==null?void 0:cn.showToolCalls,se=(dn=r.features)==null?void 0:dn.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Z=(Vc=(uo=r.features)==null?void 0:uo.streamAnimation)==null?void 0:Vc.type;r={...r,...l},eo(),fs(n,r),ri(n,r),oi(n,r),Cr(),r.colorScheme!==A&&Ts();let ve=rl.getForInstance(r.plugins);o.length=0,o.push(...ve),L=(Gc=(Kc=r.launcher)==null?void 0:Kc.enabled)!=null?Gc:!0,M=(Xc=(Qc=r.launcher)==null?void 0:Qc.autoExpand)!=null?Xc:!1,Le=(Yc=(Jc=r.features)==null?void 0:Jc.showReasoning)!=null?Yc:!0,Pe=(ed=(Zc=r.features)==null?void 0:Zc.showToolCalls)!=null?ed:!0,fe=(nd=(td=r.features)==null?void 0:td.scrollToBottom)!=null?nd:{};let Ne=Ft();ne=(od=(rd=r.features)==null?void 0:rd.scrollBehavior)!=null?od:{},Ne!==Ft()&&(Es(),so()),Gr(),On();let Fe=ae;if(ae=(ad=(sd=r.features)==null?void 0:sd.showEventStreamToggle)!=null?ad:!1,ae&&!Fe){if(V||(Ce=new ia(ce),V=new aa(_e,Ce),X=X!=null?X:new la,Ce.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),F.setSSEEventCallback((ee,Tt)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ee,Tt),X==null||X.processEvent(ee,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let ee=(ld=(id=r.features)==null?void 0:id.eventStream)==null?void 0:ld.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=b("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=En.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let zt=he("activity","18px","currentColor",1.5);zt&&yt.appendChild(zt);let at=je.clearChatButtonWrapper,kt=je.closeButtonWrapper,an=at||kt;an&&an.parentNode===ke?ke.insertBefore(yt,an):ke.appendChild(yt),yt.addEventListener("click",()=>{J?ar():Hr()})}}else!ae&&Fe&&(ar(),yt&&(yt.remove(),yt=null),V==null||V.clear(),Ce==null||Ce.destroy(),V=null,Ce=null,X==null||X.reset(),X=null);if(((cd=r.launcher)==null?void 0:cd.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((dd=r.launcher)==null?void 0:dd.enabled)===!1&&on&&(on.remove(),on=null),((pd=r.launcher)==null?void 0:pd.enabled)!==!1&&!Yt&&!on){let{instance:ee,element:Tt}=qi({config:r,plugins:o,onToggle:Wl});Yt=ee,ee||(on=Tt),n.appendChild(Tt)}Yt&&Yt.update(r),me&&((ud=r.launcher)==null?void 0:ud.title)!==void 0&&(me.textContent=r.launcher.title),Me&&((md=r.launcher)==null?void 0:md.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let $e=(gd=r.layout)==null?void 0:gd.header;if(($e==null?void 0:$e.layout)!==U&&ke){let ee=$e?Va(r,$e,{showClose:$(),onClose:()=>_t(!1,"user")}):Uo({config:r,showClose:$(),onClose:()=>_t(!1,"user")});rt.replaceHeader(ee),ke=rt.header.element,E=rt.header.iconHolder,me=rt.header.headerTitle,Me=rt.header.headerSubtitle,Ue=rt.header.closeButton,U=$e==null?void 0:$e.layout}else if($e&&(E&&(E.style.display=$e.showIcon===!1?"none":""),me&&(me.style.display=$e.showTitle===!1?"none":""),Me&&(Me.style.display=$e.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=$e.showCloseButton===!1?"none":""),je.clearChatButtonWrapper)){let ee=$e.showClearChat;if(ee!==void 0){je.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=je;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((fd=r.layout)==null?void 0:fd.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((hd=r.layout)==null?void 0:hd.showFooter)!==!1;Re&&(Re.style.display=st?"":"none"),jn(),On(),L!==P?L?_t(M,"auto"):(N=!0,Ws()):M!==C&&_t(M,"auto"),C=M,P=L,Rs(),$l();let qe=JSON.stringify(l.toolCall)!==JSON.stringify(p),Ge=JSON.stringify(r.messageActions)!==JSON.stringify(f),bt=JSON.stringify((yd=r.layout)==null?void 0:yd.messages)!==JSON.stringify(y),R=((bd=r.loadingIndicator)==null?void 0:bd.render)!==(W==null?void 0:W.render)||((vd=r.loadingIndicator)==null?void 0:vd.renderIdle)!==(W==null?void 0:W.renderIdle)||((wd=r.loadingIndicator)==null?void 0:wd.showBubble)!==(W==null?void 0:W.showBubble),Be=r.iterationDisplay!==z,We=((Cd=(xd=r.features)==null?void 0:xd.showReasoning)!=null?Cd:!0)!==(O!=null?O:!0)||((Sd=(Ad=r.features)==null?void 0:Ad.showToolCalls)!=null?Sd:!0)!==(D!=null?D:!0)||JSON.stringify((Td=r.features)==null?void 0:Td.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((Md=r.features)==null?void 0:Md.reasoningDisplay)!==JSON.stringify(oe);(qe||Ge||bt||R||Be||We)&&F&&(Xo++,ks(Ye,F.getMessages(),Y));let Pt=(kd=(Ed=r.features)==null?void 0:Ed.streamAnimation)==null?void 0:kd.type;if(Pt!==Z&&Pt&&Pt!=="none"){let ee=hs(Pt,(Pd=(Ld=r.features)==null?void 0:Ld.streamAnimation)==null?void 0:Pd.plugins);ee&&za(ee,n)}let Oe=(Id=r.launcher)!=null?Id:{},Kt=(Wd=Oe.headerIconHidden)!=null?Wd:!1,xt=(Hd=(Rd=r.layout)==null?void 0:Rd.header)==null?void 0:Hd.showIcon,sn=Kt||xt===!1,Wn=Oe.headerIconName,Bt=(Bd=Oe.headerIconSize)!=null?Bd:"48px";if(E){let ee=Te.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(sn)E.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(E.style.display="",E.style.height=Bt,E.style.width=Bt,ee&&Tt&&(ee.contains(E)?E.nextSibling!==Tt&&(E.remove(),ee.insertBefore(E,Tt)):ee.insertBefore(E,Tt)),Wn){let at=parseFloat(Bt)||24,kt=he(Wn,at*.6,"currentColor",1);kt?E.replaceChildren(kt):E.textContent=(Dd=Oe.agentIconText)!=null?Dd:"\u{1F4AC}"}else if(Oe.iconUrl){let at=E.querySelector("img");if(at)at.src=Oe.iconUrl,at.style.height=Bt,at.style.width=Bt;else{let kt=document.createElement("img");kt.src=Oe.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Bt,kt.style.width=Bt,E.replaceChildren(kt)}}else{let at=E.querySelector("svg"),kt=E.querySelector("img");(at||kt)&&E.replaceChildren(),E.textContent=(Nd=Oe.agentIconText)!=null?Nd:"\u{1F4AC}"}let zt=E.querySelector("img");zt&&(zt.style.height=Bt,zt.style.width=Bt)}}let pn=(Od=(Fd=r.layout)==null?void 0:Fd.header)==null?void 0:Od.showTitle,_n=($d=(_d=r.layout)==null?void 0:_d.header)==null?void 0:$d.showSubtitle;if(me&&(me.style.display=pn===!1?"none":""),Me&&(Me.style.display=_n===!1?"none":""),Ue){((zd=(Ud=r.layout)==null?void 0:Ud.header)==null?void 0:zd.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(qd=Oe.closeButtonSize)!=null?qd:"32px",zt=(jd=Oe.closeButtonPlacement)!=null?jd:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=je,kt=zt==="top-right",an=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==an)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Te.style.position="relative",Te.appendChild(at);else{let dt=(Kd=(Vd=Oe.clearChat)==null?void 0:Vd.placement)!=null?Kd:"inline",ln=(Qd=(Gd=Oe.clearChat)==null?void 0:Gd.enabled)!=null?Qd:!0;at.className=ln&&dt==="inline"?"":"persona-ml-auto";let Rn=Te.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(at)}if(Ue.style.color=Oe.closeButtonColor||En.actionIconColor,Oe.closeButtonBackgroundColor?(Ue.style.backgroundColor=Oe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Oe.closeButtonBorderWidth||Oe.closeButtonBorderColor){let dt=Oe.closeButtonBorderWidth||"0px",ln=Oe.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${ln}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Oe.closeButtonBorderRadius?(Ue.style.borderRadius=Oe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Oe.closeButtonPaddingX?(Ue.style.paddingLeft=Oe.closeButtonPaddingX,Ue.style.paddingRight=Oe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Oe.closeButtonPaddingY?(Ue.style.paddingTop=Oe.closeButtonPaddingY,Ue.style.paddingBottom=Oe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let yn=(Xd=Oe.closeButtonIconName)!=null?Xd:"x",pr=(Jd=Oe.closeButtonIconText)!=null?Jd:"\xD7";Ue.innerHTML="";let Mn=he(yn,"28px","currentColor",1);Mn?Ue.appendChild(Mn):Ue.textContent=pr;let Jt=(Yd=Oe.closeButtonTooltipText)!=null?Yd:"Close chat",zn=(Zd=Oe.closeButtonShowTooltip)!=null?Zd:!0;if(Ue.setAttribute("aria-label",Jt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),zn&&Jt)){let dt=null,ln=()=>{if(dt||!Ue)return;let Bo=Ue.ownerDocument,Bs=Bo.body;if(!Bs)return;dt=Pr(Bo,"div","persona-clear-chat-tooltip"),dt.textContent=Jt;let Ds=Pr(Bo,"div");Ds.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Ds);let Do=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(bo),dt.style.left=`${Do.left+Do.width/2}px`,dt.style.top=`${Do.top-8}px`,dt.style.transform="translate(-50%, -100%)",Bs.appendChild(dt)},Rn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",ln),at.addEventListener("mouseleave",Rn),Ue.addEventListener("focus",ln),Ue.addEventListener("blur",Rn),at._cleanupTooltip=()=>{Rn(),at&&(at.removeEventListener("mouseenter",ln),at.removeEventListener("mouseleave",Rn)),Ue&&(Ue.removeEventListener("focus",ln),Ue.removeEventListener("blur",Rn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:It}=je;if(Ve){let ee=(ep=Oe.clearChat)!=null?ep:{},Tt=(tp=ee.enabled)!=null?tp:!0,zt=(rp=(np=r.layout)==null?void 0:np.header)==null?void 0:rp.showClearChat,at=zt!==void 0?zt:Tt,kt=(op=ee.placement)!=null?op:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:an}=je;!I()&&an&&!an.classList.contains("persona-absolute")&&(at?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let yn=kt==="top-right",pr=It.classList.contains("persona-absolute");if(!I()&&yn!==pr&&at){if(It.remove(),yn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Te.style.position="relative",Te.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Jt=Te.querySelector(".persona-border-b-persona-divider"),zn=je.closeButtonWrapper;Jt&&zn&&zn.parentElement===Jt?Jt.insertBefore(It,zn):Jt&&Jt.appendChild(It)}let Mn=je.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(yn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(at){if(!I()){let dt=(sp=ee.size)!=null?sp:"32px";Ve.style.height=dt,Ve.style.width=dt}let an=(ap=ee.iconName)!=null?ap:"refresh-cw",yn=(ip=ee.iconColor)!=null?ip:"";Ve.style.color=yn||En.actionIconColor,Ve.innerHTML="";let pr=I()?"14px":"20px",Mn=he(an,pr,"currentColor",2);if(Mn&&Ve.appendChild(Mn),ee.backgroundColor?(Ve.style.backgroundColor=ee.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let dt=ee.borderWidth||"0px",ln=ee.borderColor||"transparent";Ve.style.border=`${dt} solid ${ln}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ee.borderRadius?(Ve.style.borderRadius=ee.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ee.paddingX?(Ve.style.paddingLeft=ee.paddingX,Ve.style.paddingRight=ee.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ee.paddingY?(Ve.style.paddingTop=ee.paddingY,Ve.style.paddingBottom=ee.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Jt=(lp=ee.tooltipText)!=null?lp:"Clear chat",zn=(cp=ee.showTooltip)!=null?cp:!0;if(Ve.setAttribute("aria-label",Jt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),zn&&Jt)){let dt=null,ln=()=>{if(dt||!Ve)return;let Bo=Ve.ownerDocument,Bs=Bo.body;if(!Bs)return;dt=Pr(Bo,"div","persona-clear-chat-tooltip"),dt.textContent=Jt;let Ds=Pr(Bo,"div");Ds.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Ds);let Do=Ve.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(bo),dt.style.left=`${Do.left+Do.width/2}px`,dt.style.top=`${Do.top-8}px`,dt.style.transform="translate(-50%, -100%)",Bs.appendChild(dt)},Rn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",ln),It.addEventListener("mouseleave",Rn),Ve.addEventListener("focus",ln),Ve.addEventListener("blur",Rn),It._cleanupTooltip=()=>{Rn(),It&&(It.removeEventListener("mouseenter",ln),It.removeEventListener("mouseleave",Rn)),Ve&&(Ve.removeEventListener("focus",ln),Ve.removeEventListener("blur",Rn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[sl],Lo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ca.message,ca.messageAndClick];S=al({parsers:$n,handlers:Lo,getSessionMetadata:v,updateSessionMetadata:w,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Y=rg(r,S,de),F.updateConfig(r),ks(Ye,F.getMessages(),Y),Qo(),Al(),ci(F.isStreaming());let Po=((dp=r.voiceRecognition)==null?void 0:dp.enabled)===!0,Io=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Wo=((up=(pp=r.voiceRecognition)==null?void 0:pp.provider)==null?void 0:up.type)==="runtype";if(Po&&(Io||Wo))if(!H||!be){let ee=Ig(r.voiceRecognition,r.sendButton);ee&&(H=ee.micButton,be=ee.micButtonWrapper,ht.insertBefore(be,wn),H.addEventListener("click",fa),H.disabled=F.isStreaming())}else{let ee=(mp=r.voiceRecognition)!=null?mp:{},Tt=(gp=r.sendButton)!=null?gp:{},zt=(fp=ee.iconName)!=null?fp:"mic",at=(hp=Tt.size)!=null?hp:"40px",kt=(yp=ee.iconSize)!=null?yp:at,an=parseFloat(kt)||24;H.style.width=kt,H.style.height=kt,H.style.minWidth=kt,H.style.minHeight=kt;let yn=(vp=(bp=ee.iconColor)!=null?bp:Tt.textColor)!=null?vp:"currentColor";H.innerHTML="";let pr=he(zt,an,yn,2);pr?H.appendChild(pr):H.textContent="\u{1F3A4}";let Mn=(wp=ee.backgroundColor)!=null?wp:Tt.backgroundColor;Mn?H.style.backgroundColor=Mn:H.style.backgroundColor="",yn?H.style.color=yn:H.style.color="var(--persona-text, #111827)",ee.borderWidth?(H.style.borderWidth=ee.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),ee.borderColor?H.style.borderColor=ee.borderColor:H.style.borderColor="",ee.paddingX?(H.style.paddingLeft=ee.paddingX,H.style.paddingRight=ee.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),ee.paddingY?(H.style.paddingTop=ee.paddingY,H.style.paddingBottom=ee.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Jt=be==null?void 0:be.querySelector(".persona-send-button-tooltip"),zn=(xp=ee.tooltipText)!=null?xp:"Start voice recognition";if(((Cp=ee.showTooltip)!=null?Cp:!1)&&zn)if(Jt)Jt.textContent=zn,Jt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=zn,be==null||be.insertBefore(ln,H)}else Jt&&(Jt.style.display="none");be.style.display="",H.disabled=F.isStreaming()}else H&&be&&(be.style.display="none",((Sp=(Ap=r.voiceRecognition)==null?void 0:Ap.provider)==null?void 0:Sp.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():kr&&io());if(((Tp=r.attachments)==null?void 0:Tp.enabled)===!0)if(!gt||!le){let ee=(Mp=r.attachments)!=null?Mp:{},zt=(kp=((Ep=r.sendButton)!=null?Ep:{}).size)!=null?kp:"40px";Lt||(Lt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,ye)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((Lp=ee.allowedTypes)!=null?Lp:qr).join(","),Ke.multiple=((Pp=ee.maxFiles)!=null?Pp:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Ct.insertBefore(Ke,ye)),gt=b("div","persona-send-button-wrapper"),le=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(Ip=ee.buttonTooltipText)!=null?Ip:"Attach file");let at=(Wp=ee.buttonIconName)!=null?Wp:"paperclip",kt=zt,an=parseFloat(kt)||40,yn=Math.round(an*.6);le.style.width=kt,le.style.height=kt,le.style.minWidth=kt,le.style.minHeight=kt,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let pr=he(at,yn,"currentColor",1.5);pr?le.appendChild(pr):le.textContent="\u{1F4CE}",le.addEventListener("click",zn=>{zn.preventDefault(),Ke==null||Ke.click()}),gt.appendChild(le);let Mn=(Rp=ee.buttonTooltipText)!=null?Rp:"Attach file",Jt=b("div","persona-send-button-tooltip");Jt.textContent=Mn,gt.appendChild(Jt),Qe.append(gt),!At&&Ke&&Lt&&(At=Xs.fromConfig(ee),At.setPreviewsContainer(Lt),Ke.addEventListener("change",async()=>{At&&(Ke!=null&&Ke.files)&&(await At.handleFileSelect(Ke.files),Ke.value="")})),Te.querySelector(".persona-attachment-drop-overlay")||Te.appendChild(og(ee.dropOverlay))}else{gt.style.display="";let ee=(Hp=r.attachments)!=null?Hp:{};Ke&&(Ke.accept=((Bp=ee.allowedTypes)!=null?Bp:qr).join(","),Ke.multiple=((Dp=ee.maxFiles)!=null?Dp:4)>1),At&&At.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else gt&&(gt.style.display="none"),At&&At.clearAttachments(),(Np=Te.querySelector(".persona-attachment-drop-overlay"))==null||Np.remove();let Gt=(Fp=r.sendButton)!=null?Fp:{},Ro=(Op=Gt.useIcon)!=null?Op:!1,co=(_p=Gt.iconText)!=null?_p:"\u2191",po=Gt.iconName,$r=($p=Gt.tooltipText)!=null?$p:"Send message",Ho=(Up=Gt.showTooltip)!=null?Up:!1,Ze=(zp=Gt.size)!=null?zp:"40px",Nt=Gt.backgroundColor,Dt=Gt.textColor;if(Ro){if(pe.style.width=Ze,pe.style.height=Ze,pe.style.minWidth=Ze,pe.style.minHeight=Ze,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Dt?pe.style.color=Dt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",po){let ee=parseFloat(Ze)||24,Tt=(Dt==null?void 0:Dt.trim())||"currentColor",zt=he(po,ee,Tt,2);zt?pe.appendChild(zt):pe.textContent=co}else pe.textContent=co;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(jp=(qp=r.copy)==null?void 0:qp.sendButtonLabel)!=null?jp:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Dt?pe.style.color=Dt:pe.classList.add("persona-text-white");Gt.borderWidth?(pe.style.borderWidth=Gt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Gt.borderColor?pe.style.borderColor=Gt.borderColor:pe.style.borderColor="",Gt.paddingX?(pe.style.paddingLeft=Gt.paddingX,pe.style.paddingRight=Gt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Gt.paddingY?(pe.style.paddingTop=Gt.paddingY,pe.style.paddingBottom=Gt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Ho&&$r)if(Vt)Vt.textContent=$r,Vt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=$r,wn==null||wn.insertBefore(ee,pe)}else Vt&&(Vt.style.display="none");let $t=(Xp=(Vp=r.layout)==null?void 0:Vp.contentMaxWidth)!=null?Xp:I()?(Qp=(Gp=(Kp=r.launcher)==null?void 0:Kp.composerBar)==null?void 0:Gp.contentMaxWidth)!=null?Qp:"720px":void 0;$t?(Ye.style.maxWidth=$t,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(Jp=r.statusIndicator)!=null?Jp:{},Ut=(Yp=mt.visible)!=null?Yp:!0;if(gn.style.display=Ut?"":"none",F){let ee=F.getStatus();ft(gn,(zt=>{var at,kt,an,yn;return zt==="idle"?(at=mt.idleText)!=null?at:tn.idle:zt==="connecting"?(kt=mt.connectingText)!=null?kt:tn.connecting:zt==="connected"?(an=mt.connectedText)!=null?an:tn.connected:zt==="error"?(yn=mt.errorText)!=null?yn:tn.error:tn[zt]})(ee),mt,ee)}gn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let un=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";gn.classList.add(un)},open(){$()&&_t(!0,"api")},close(){$()&&_t(!1,"api")},toggle(){$()&&_t(!N,"api")},reconnect(){F.reconnectNow()},clearChat(){xn=!1,F.clearMessages(),Tr.clear(),so();try{localStorage.removeItem(xs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let p=c.clear();p instanceof Promise&&p.catch(f=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}u={},S.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),Ae==null||Ae.update()},setMessage(l){return!ye||F.isStreaming()?!1:(!N&&$()&&_t(!0,"system"),ye.value=l,ye.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let p=(l==null?void 0:l.trim())||ye.value.trim();return p?(!N&&$()&&_t(!0,"system"),ye.value="",ye.style.height="auto",F.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return F.isStreaming()?!1:((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?(F.isVoiceActive()||(!N&&$()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),nt("user"),F.isVoiceActive()&&ts()})),!0):kr?!0:Il()?(!N&&$()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),ma("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),nt("user"),_r()}),!0):!1:kr?(K.manuallyDeactivated=!0,ct(),io("user"),!0):!1},injectMessage(l){return!N&&$()&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!N&&$()&&_t(!0,"system");let p=F.injectAssistantMessage(l);return te&&(te=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),p},injectUserMessage(l){return!N&&$()&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!N&&$()&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!N&&$()&&_t(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!N&&$()&&_t(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!N&&$()&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,p){return F.connectStream(l,p)},__pushEventStreamEvent(l){V&&(X==null||X.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ae||!V||Hr()},hideEventStream(){J&&ar()},isEventStreamVisible(){return J},showArtifacts(){tr(r)&&(xn=!1,Cr(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){tr(r)&&(xn=!0,Cr())},upsertArtifact(l){return tr(r)?(xn=!1,F.upsertArtifact(l)):null},selectArtifact(l){tr(r)&&F.selectArtifact(l)},clearArtifacts(){tr(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return L&&!N&&!I()||!ye?!1:(ye.focus(),!0)},async resolveApproval(l,p,f){let A=F.getMessages().find(W=>{var z;return W.variant==="approval"&&((z=W.approval)==null?void 0:z.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){F.resolveWebMcpApproval(A.id,p);return}return F.resolveApproval(A.approval,p,f)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){w(l)},on(l,p){return i.on(l,p)},off(l,p){i.off(l,p)},isOpen(){return $()&&N},isVoiceActive(){return K.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:$()&&N,launcherEnabled:L,voiceActive:K.active,streaming:F.isStreaming()}},showCSATFeedback(l){!N&&$()&&_t(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let f=eg({onSubmit:async(y,A)=>{var W;F.isClientTokenMode()&&await F.submitCSATFeedback(y,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!N&&$()&&_t(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let f=tg({onSubmit:async(y,A)=>{var W;F.isClientTokenMode()&&await F.submitNPSFeedback(y,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,y,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return F.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return F.submitNPSFeedback(l,p)},destroy(){ko!=null&&(clearInterval(ko),ko=null),lt.forEach(l=>l()),ue.remove(),it==null||it.remove(),Yt==null||Yt.destroy(),on==null||on.remove(),Sr&&Ue.removeEventListener("click",Sr)}};if((((_c=t==null?void 0:t.debugTools)!=null?_c:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:f=>f?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=p,lt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.focusInput()};if(window.addEventListener("persona:focusInput",p),lt.push(()=>{window.removeEventListener("persona:focusInput",p)}),ae){let O=se=>{let oe=se.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&en.showEventStream()},D=se=>{let oe=se.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",D)})}let f=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.showArtifacts()},y=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.hideArtifacts()},A=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&en.upsertArtifact(D.artifact)},W=O=>{let D=O.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&en.selectArtifact(D.id)},z=O=>{let D=O.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),lt.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let Yn=Xv(r.persistState);if(Yn&&$()){let l=Jv(Yn.storage),p=`${Yn.keyPrefix}widget-open`,f=`${Yn.keyPrefix}widget-voice`,y=`${Yn.keyPrefix}widget-voice-mode`;if(l){let A=(($c=Yn.persist)==null?void 0:$c.openState)&&l.getItem(p)==="true",W=((Uc=Yn.persist)==null?void 0:Uc.voiceState)&&l.getItem(f)==="true",z=((zc=Yn.persist)==null?void 0:zc.voiceState)&&l.getItem(y)==="true";if(A&&setTimeout(()=>{en.open(),setTimeout(()=>{var O;if(W||z)en.startVoiceRecognition();else if((O=Yn.persist)!=null&&O.focusInput){let D=n.querySelector("textarea");D&&D.focus()}},100)},0),(qc=Yn.persist)!=null&&qc.openState&&(i.on("widget:opened",()=>{l.setItem(p,"true")}),i.on("widget:closed",()=>{l.setItem(p,"false")})),(jc=Yn.persist)!=null&&jc.voiceState&&(i.on("voice:state",O=>{l.setItem(f,O.active?"true":"false")}),i.on("user:message",O=>{l.setItem(y,O.viaVoice?"true":"false")})),Yn.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(f),l.removeItem(y)},D=()=>O();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return h&&$()&&setTimeout(()=>{en.open()},0),Zo(),pa||tu().then(()=>{F&&(Xo++,Tr.clear(),ks(Ye,F.getMessages(),Y))}).catch(()=>{}),en};var Yv=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},Zv=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},ew=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},tw=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||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."+(e.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 ${e.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.")},ag=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},pl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},ig=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",pl(n)},ll=n=>{n.style.transition=""},cl=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},dl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},ai=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},nw=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},rw=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},lg=(n,e,t,r,o,s,a)=>{var v,w,T,B,S,L;let i=mr(s),d=i.reveal==="push";nw(n,e,t,r,d),rw(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,u=(w=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?w:!0,g=(B=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?B:640,h=c!=null?c.innerWidth<=g:!1;if(u&&h&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),cl(e),ll(r),ig(r),dl(t),ai(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((L=(S=s==null?void 0:s.launcher)==null?void 0:S.zIndex)!=null?L:bn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),ig(r),Zv(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",cl(e),ll(r),dl(t),ai(o,r);let M=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":k;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=M,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",ll(r),pl(r),ai(o,r);let M=Yv(i.width,n.clientWidth),k=Math.max(0,n.clientWidth),C=i.animate?"margin-left 180ms ease":"none",P=i.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${k+M}px`,e.style.transition=C,e.style.marginLeft=`${P}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${k}px`,t.style.maxWidth=`${k}px`,t.style.minWidth=`${k}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",cl(e),pl(r),dl(t),ai(o,r);let M=i.reveal==="emerge";M?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${k}`,r.style.width=k,r.style.maxWidth=k,r.style.minWidth=k,r.style.minHeight="0",ew(r,i.maxHeight),r.style.overflow=M||P?"hidden":"visible",r.style.transition=C,M&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},ow=(n,e)=>{let t=n.ownerDocument.createElement("div");return ag(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){ag(t,r)},destroy(){t.remove()}}},sw=(n,e)=>{var L,M,k,C;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),g=(M=(L=e==null?void 0:e.launcher)==null?void 0:L.enabled)==null||M?(C=(k=e==null?void 0:e.launcher)==null?void 0:k.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,n),d.appendChild(n);let h=null,m=()=>{h==null||h.disconnect(),h=null},v=()=>{m(),mr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{lg(a,i,d,c,u,e,g)}),h.observe(a))},w=!1,T=()=>{lg(a,i,d,c,u,e,g),v(),g&&!w&&a.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,tw(a,mr(e)))},B=a.ownerDocument.defaultView,S=()=>{T()};return B==null||B.addEventListener("resize",S),mr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:u,shell:a,syncWidgetState(P){let U=P.launcherEnabled?P.open:!0;g!==U&&(g=U,T())},updateConfig(P){var U,_;e=P,((_=(U=e==null?void 0:e.launcher)==null?void 0:U.enabled)!=null?_:!0)===!1&&(g=!0),T()},destroy(){B==null||B.removeEventListener("resize",S),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},cg=(n,e)=>mn(e)?sw(n,e):ow(n,e);var da={desktop:{w:1280,h:800},mobile:{w:390,h:844}},dg=.15,pg=1.5,ul="persona-preview-shell-theme",aw={load:()=>null,save:()=>{},clear:()=>{}},iw=["How do I get started?","Pricing & plans","Talk to support"];function ml(n){return n.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function lw(n){return n==="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 ug(n){let e=lw(n);return`* { box-sizing: border-box; }
|
|
133
|
+
${ot?"background: transparent !important;":""}
|
|
134
|
+
`}if(!b&&!i){let Lt="max-height: -moz-available !important; max-height: stretch !important;",Jt=g?"":"padding-top: 1.25em !important;",zs=g?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Ee.style.cssText+=Lt+Jt+zs}xo()};Ls(),es(t,o),hs(t,o),ys(t,o),wr=()=>{Ls(),es(t,o),hs(t,o),ys(t,o),Cs?t.style.setProperty("--persona-artifact-welded-outer-radius",Cs):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",zl)}),qe.push(()=>{yr!==null&&clearTimeout(yr)});let xn=null,Cn=null;qe.push(()=>{xn?.(),xn=null,Cn?.(),Cn=null}),vr&&qe.push(()=>{vr?.disconnect(),vr=null}),qe.push(()=>{Ar?.(),Ar=null,ei(),vt&&(vt.remove(),vt=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth")}),Y&&qe.push(()=>{We!==null&&(cancelAnimationFrame(We),We=null),Ne?.destroy(),Ne=null,Ae?.destroy(),Ae=null,fe=null});let fo=null,Vl=()=>{fo&&(fo(),fo=null),o.colorScheme==="auto"&&(fo=ma(()=>{es(t,o)}))};Vl(),qe.push(()=>{fo&&(fo(),fo=null)}),qe.push(a);let Ps=o.features?.streamAnimation;if(Ps?.type&&Ps.type!=="none"){let i=dr(Ps.type,Ps.plugins);i&&(Ia(i,t),qe.push(()=>bp(t)))}let Is=Np(bt),go=null,F,ti=i=>{if(!F)return;let g=i??F.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?pd(g):null;h?Is.render(h,F,N,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?Is.render([],F,N,g):Is.render(o.suggestionChips,F,N,g,o.suggestionChipsConfig)},mn=!1,mo=cp(),zo=new Map,ho=new Map,zn=new Map,ni=0,Su=Wn()!==null,Zt=Ta(),an=0,jn=null,ln=!1,Rs=!1,qn=0,hn=null,yo=null,oi=!1,Ws=!1,ri=null,Sr=!0,si=!1,ai=null,Tu=4,Bs=24,Mu=80,ii=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Kl=o.voiceRecognition?.autoResume??!1,Ln=i=>{l.emit("voice:state",{active:Ge.active,source:i,timestamp:Date.now()})},yn=()=>{x(i=>({...i,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},Eu=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=xl(c.voiceState),g=!!i.active,h=Number(i.timestamp??0);Ge.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-h<Vb&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Ge.active=F.isVoiceActive(),Ln("restore"),F.isVoiceActive()&&Go()}):Fs("restore"))},1e3)},ku=()=>F?ou(F.getMessages()).filter(i=>!i.__skipPersist):[],Hs=null,Gl=(i,g)=>{typeof console<"u"&&console.error(i,g)},li=(i,g)=>{let h=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(O=>{Gl(g,O)})}catch(Q){return Gl(g,Q),null}},b=Hs,S=b?b.then(()=>h()??void 0):h();if(!S)return;let k=S.finally(()=>{Hs===k&&(Hs=null)});Hs=k};function ci(i){if(!d?.save)return;let h={messages:i?ou(i):F?ku():[],metadata:c,artifacts:fn.artifacts,selectedArtifactId:fn.selectedId};li(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let jo=null,Xl=()=>Ee.querySelector("#persona-scroll-container")||ie,Tr=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),ln=!1},Ql=()=>{jn!==null&&(cancelAnimationFrame(jn),jn=null),Rs=!1,Tr()},Lu=()=>mn&&pi()&&(Qt()!=="anchor-top"||Pl()),di=()=>{let i=lo()||"Jump to latest",g=Lu();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),qn>0?(co.textContent=String(qn),co.style.display="",Pt.setAttribute("aria-label",`${i} (${qn} new)`)):(co.textContent="",co.style.display="none",Pt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},Jl=()=>{qn!==0&&(qn=0,di())},pi=()=>On()?!Zt.isFollowing():!so(ie,Bs),en=()=>{if(!ws()||Pe){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ue&&ue.appendChild(Pt),Oo();let g=Mn(ie)>0&&pi();g?di():Jl(),Pt.style.display=g?"":"none"},Mr=()=>{Zt.pause()&&(Ql(),en())},Vn=()=>{Zt.resume(),Jl(),en()},Kn=(i=!1)=>{On()&&Zt.isFollowing()&&(!i&&!mn||(jn!==null&&(cancelAnimationFrame(jn),jn=null),Rs=!0,jn=requestAnimationFrame(()=>{jn=null,Rs=!1,Zt.isFollowing()&&Pu(Xl(),i?220:140)})))},Yl=(i,g,h,b=()=>!0)=>{let S=i.scrollTop,k=g(),Q=k-S;if(Tr(),Math.abs(Q)<1){ln=!0,i.scrollTop=k,an=i.scrollTop,ln=!1;return}let O=performance.now();ln=!0;let G=de=>1-Math.pow(1-de,3),se=de=>{if(!b()){Tr();return}let oe=g();oe!==k&&(k=oe,Q=k-S);let we=de-O,Ve=Math.min(we/h,1),ht=G(Ve),st=S+Q*ht;i.scrollTop=st,an=i.scrollTop,Ve<1?jo=requestAnimationFrame(se):(i.scrollTop=k,an=i.scrollTop,jo=null,ln=!1)};jo=requestAnimationFrame(se)},Pu=(i,g=500)=>{let h=Mn(i)-i.scrollTop;if(Math.abs(h)<1){an=i.scrollTop;return}if(Math.abs(h)>=Mu){Tr(),ln=!0,i.scrollTop=Mn(i),an=i.scrollTop,ln=!1;return}Yl(i,()=>Mn(i),g,()=>Zt.isFollowing())},Zl=()=>{let i=Xl();ln=!0,i.scrollTop=Mn(i),an=i.scrollTop,ln=!1,en()},ec=i=>{let g=0,h=i;for(;h&&h!==ie;)g+=h.offsetTop,h=h.offsetParent;return g},tc=()=>{if(bu()!=="last-user-turn")return!1;let i=F?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(k=>k.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ie.querySelector(`[data-message-id="${h}"]`);if(!b)return!1;let S=Math.min(Math.max(0,ec(b)-kl()),Mn(ie));return ln=!0,ie.scrollTop=S,an=ie.scrollTop,ln=!1,Qt()==="follow"&&!so(ie,Bs)&&Zt.pause(),en(),!0},nc=i=>{_n.style.height=`${Math.max(0,Math.round(i))}px`,hn&&(hn.spacerHeight=Math.max(0,i))},Er=()=>{yo!==null&&(cancelAnimationFrame(yo),yo=null),Tr(),hn=null,_n.style.height="0px"},Iu=i=>{yo!==null&&cancelAnimationFrame(yo),yo=requestAnimationFrame(()=>{yo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ie.querySelector(`[data-message-id="${g}"]`);if(!h)return;let b=ec(h),S=hn?.spacerHeight??0,k=ie.scrollHeight-S,{targetScrollTop:Q,spacerHeight:O}=gp({anchorOffsetTop:b,topOffset:kl(),viewportHeight:ie.clientHeight,contentHeight:k});hn={initialSpacerHeight:O,contentHeightAtAnchor:k,spacerHeight:O},nc(O),Yl(ie,()=>Q,220)})},Ru=()=>{if(On()){if(!Zt.isFollowing()||so(ie,1))return;Kn(!mn);return}if(hn&&hn.initialSpacerHeight>0){let i=ie.scrollHeight-hn.spacerHeight,g=mp({initialSpacerHeight:hn.initialSpacerHeight,contentHeightAtAnchor:hn.contentHeightAtAnchor,currentContentHeight:i});g!==hn.spacerHeight&&nc(g)}en()},Wu=i=>{let g=Qt();g==="follow"?(Vn(),Kn(!0)):g==="anchor-top"&&(Sr=!1,si=!0,Iu(i))},Bu=()=>{if(Qt()==="anchor-top"){if(si){Sr=!1;return}Sr=!0,Er(),Vn(),Kn(!0)}},Hu=i=>{let g=new Map;i.forEach(h=>{let b=ii.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(l.emit("assistant:message",h),!Ws&&(Qt()!=="anchor-top"||Pl())&&pi()&&(qn+=1,di(),en(),Rl(qn===1?"1 new message below.":`${qn} new messages below.`))),h.role==="assistant"&&b?.streaming&&h.streaming===!1&&l.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&l.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):l.emit("approval:requested",{approval:h.approval,message:h}))}),ii.clear(),g.forEach((h,b)=>{ii.set(b,h)})},Du=(i,g,h)=>{let b=document.createElement("div"),k=(()=>{let L=r.find(Fe=>Fe.renderLoadingIndicator);if(L?.renderLoadingIndicator)return L.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(L,Fe)=>Fe==null?!1:typeof Fe=="string"?(L.textContent=Fe,!0):(L.appendChild(Fe),!0),O=new Set,G=new Set,se=r.some(L=>L.renderAskUserQuestion),de=[],oe=[],we=o.enableComponentStreaming!==!1,Ve=o.approval!==!1,ht=[];if(g.forEach(L=>{O.add(L.id);let Fe=se&&Lo(L),Se=Ve&&L.variant==="approval"&&!!L.approval,_e=!Fe&&L.role==="assistant"&&!L.variant&&we&&wl(L);!Se&&zn.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),zn.delete(L.id)),!_e&&ho.has(L.id)&&(i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),ho.delete(L.id));let St=Lo(L)?`:${L.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${L.agentMetadata?.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=lp(L,ni)+St,xt=Fe||Se||_e?null:dp(mo,L.id,pt);if(xt){b.appendChild(xt.cloneNode(!0)),Lo(L)&&L.toolCall?.id&&L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(G.add(L.toolCall.id),ea(L,o,Ie.composerOverlay));return}let yt=null,_t=r.find(pe=>!!(L.variant==="reasoning"&&pe.renderReasoning||L.variant==="tool"&&pe.renderToolCall||!L.variant&&pe.renderMessage)),wo=o.layout?.messages;if(Lo(L)&&L.agentMetadata?.askUserQuestionAnswered===!0){zo.delete(L.id),i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime");return}if(Hi(L)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(L)&&o.features?.askUserQuestion?.enabled!==!1){let pe=r.find(Ct=>typeof Ct.renderAskUserQuestion=="function");if(pe&>.current){let Ct=zo.get(L.id),qt=Ct!==pt,Ht=null;if(qt){let{payload:Ye,complete:kt}=Zo(L),He=L.id,Ze=()=>gt.current?.getMessages().find(tn=>tn.id===He);Ht=pe.renderAskUserQuestion({message:L,payload:Ye,complete:kt,resolve:tn=>{let xo=Ze();xo&>.current?.resolveAskUserQuestion(xo,tn)},dismiss:()=>{let tn=Ze();tn?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(tn),gt.current?.resolveAskUserQuestion(tn,"(dismissed)"))},config:o})}let ot=Ct!=null;if(qt&&Ht===null&&!ot){L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(G.add(L.toolCall.id),ea(L,o,Ie.composerOverlay));return}let je=document.createElement("div");je.className="persona-flex",je.id=`wrapper-${L.id}`,je.setAttribute("data-wrapper-id",L.id),je.setAttribute("data-ask-plugin-stub","true"),je.setAttribute("data-preserve-runtime","true"),b.appendChild(je),de.push({messageId:L.id,fingerprint:pt,bubble:Ht});return}else{L.agentMetadata?.awaitingLocalTool===!0&&!L.agentMetadata?.askUserQuestionAnswered&&(G.add(L.toolCall.id),ea(L,o,Ie.composerOverlay));return}}else if(Se){let pe=r.find(ot=>typeof ot.renderApproval=="function")??s,qt=zn.get(L.id)!==pt,Ht=null;if(qt&&pe?.renderApproval){let ot=L.id,je=(Ye,kt)=>{let He=gt.current?.getMessages().find(Ze=>Ze.id===ot);He?.approval&&(He.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(He.id,Ye):gt.current?.resolveApproval(He.approval,Ye,kt))};Ht=pe.renderApproval({message:L,defaultRenderer:()=>za(L,o),config:o,approve:Ye=>je("approved",Ye),deny:Ye=>je("denied",Ye)})}if(qt&&Ht===null)i.querySelector(`#wrapper-${L.id}`)?.removeAttribute("data-preserve-runtime"),zn.delete(L.id),yt=za(L,o);else{let ot=document.createElement("div");ot.className="persona-flex",ot.id=`wrapper-${L.id}`,ot.setAttribute("data-wrapper-id",L.id),ot.setAttribute("data-approval-plugin-stub","true"),ot.setAttribute("data-preserve-runtime","true"),b.appendChild(ot),ht.push({messageId:L.id,fingerprint:pt,bubble:Ht});return}}else if(_t)if(L.variant==="reasoning"&&L.reasoning&&_t.renderReasoning){if(!te)return;yt=_t.renderReasoning({message:L,defaultRenderer:()=>sl(L,o),config:o})}else if(L.variant==="tool"&&L.toolCall&&_t.renderToolCall){if(!ge)return;yt=_t.renderToolCall({message:L,defaultRenderer:()=>il(L,o),config:o})}else _t.renderMessage&&(yt=_t.renderMessage({message:L,defaultRenderer:()=>{let pe=rl(L,h,wo,o.messageActions,Oe,{loadingIndicatorRenderer:k,widgetConfig:o});return L.role!=="user"&&gl(pe,L,o,F),pe},config:o}));if(!yt&&_e){let pe=eu(L);if(pe){let Ct=ho.get(L.id),qt=Ct!==pt,Ht=o.wrapComponentDirectiveInBubble!==!1&&Fn.getOptions(pe.component)?.bubbleChrome!==!1,ot=null;if(qt){let je=Yp(pe,{config:o,message:L,transform:h});if(je&&pe.component==="PersonaArtifactInline"){let Ye=je.hasAttribute("data-artifact-inline")?je:je.querySelector("[data-artifact-inline]"),kt=Ye?.getAttribute("data-artifact-inline")??"",He=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(kt):kt,Ze=kt?i.querySelector(`#wrapper-${L.id}`)?.querySelector(`[data-artifact-inline="${He}"]`)??null:null;Ye&&Ze&&Ze!==Ye&&op(Ze)&&(Ye===je?je=Ze:Ye.replaceWith(Ze))}if(je)if(Ht){let Ye=document.createElement("div");if(Ye.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ye.id=`bubble-${L.id}`,Ye.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let kt=document.createElement("div");kt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",kt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ye.appendChild(kt)}Ye.appendChild(je),ot=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${L.id}`,Ye.setAttribute("data-message-id",L.id),Ye.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let kt=document.createElement("div");kt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",kt.innerHTML=h({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ye.appendChild(kt)}Ye.appendChild(je),ot=Ye}}if(ot||Ct!=null){let je=document.createElement("div");je.className="persona-flex",je.id=`wrapper-${L.id}`,je.setAttribute("data-wrapper-id",L.id),je.setAttribute("data-component-directive-stub","true"),je.setAttribute("data-preserve-runtime","true"),Ht||je.classList.add("persona-w-full"),b.appendChild(je),oe.push({messageId:L.id,fingerprint:pt,bubble:ot});return}}}if(!yt)if(L.variant==="reasoning"&&L.reasoning){if(!te)return;yt=sl(L,o)}else if(L.variant==="tool"&&L.toolCall){if(!ge)return;yt=il(L,o)}else if(L.variant==="approval"&&L.approval){if(o.approval===!1)return;yt=za(L,o)}else{let pe=o.layout?.messages;pe?.renderUserMessage&&L.role==="user"?yt=pe.renderUserMessage({message:L,config:o,streaming:!!L.streaming}):pe?.renderAssistantMessage&&L.role==="assistant"?yt=pe.renderAssistantMessage({message:L,config:o,streaming:!!L.streaming}):yt=rl(L,h,pe,o.messageActions,Oe,{loadingIndicatorRenderer:k,widgetConfig:o}),L.role!=="user"&&yt&&gl(yt,L,o,F)}let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${L.id}`,ut.setAttribute("data-wrapper-id",L.id),L.role==="user"&&ut.classList.add("persona-justify-end"),yt?.getAttribute("data-persona-component-directive")==="true"&&ut.classList.add("persona-w-full"),ut.appendChild(yt),pp(mo,L.id,pt,ut),b.appendChild(ut)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let Se=Fe.getAttribute("data-persona-ask-sheet-for");Se&&!G.has(Se)&&tr(Ie.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let L=[],Fe=[];g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ge){Fe.push(Se);return}Se.variant==="reasoning"&&!te||(Fe.length>1&&L.push(Fe),Fe=[])}),Fe.length>1&&L.push(Fe),L.forEach((Se,_e)=>{let St=Se.map(Ct=>Array.from(b.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(St.length<2)return;let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-tool-group-${_e}-${Se[0].id}`,pt.setAttribute("data-wrapper-id",`tool-group-${_e}-${Se[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let _t=`Called ${Se.length} tools`,wo=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:_t,config:o});Q(yt,wo)||(yt.textContent=_t);let ut=document.createElement("div");ut.className="persona-tool-group-stack persona-flex persona-flex-col";let pe=o.features?.toolCallDisplay?.groupedMode==="summary";xt.appendChild(yt),pe||xt.appendChild(ut),pt.appendChild(xt),St[0].before(pt),St.forEach((Ct,qt)=>{if(pe){Ct.remove();return}let Ht=document.createElement("div");Ht.className="persona-tool-group-item persona-relative",Ht.setAttribute("data-persona-tool-group-item","true"),qt<St.length-1&&Ht.setAttribute("data-persona-tool-group-connector","true"),Ht.appendChild(Ct),ut.appendChild(Ht)})})}up(mo,O);let st=g.some(L=>L.role==="assistant"&&L.streaming),jt=g[g.length-1],Bt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(mn&&g.some(L=>L.role==="user")&&!st&&!Bt){let L={config:o,streaming:!0,location:"standalone",defaultRenderer:us},Fe=r.find(_e=>_e.renderLoadingIndicator),Se=null;if(Fe?.renderLoadingIndicator&&(Se=Fe.renderLoadingIndicator(L)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(L)),Se===null&&(Se=us()),Se){let _e=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1;_e.className=St?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),_e.setAttribute("data-typing-indicator","true"),_e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",_e.appendChild(Se);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-typing-indicator",pt.setAttribute("data-wrapper-id","typing-indicator"),pt.appendChild(_e),b.appendChild(pt)}}if(!mn&&g.length>0){let L=g[g.length-1],Fe={config:o,lastMessage:L,messageCount:g.length},Se=r.find(St=>St.renderIdleIndicator),_e=null;if(Se?.renderIdleIndicator&&(_e=Se.renderIdleIndicator(Fe)),_e===null&&o.loadingIndicator?.renderIdle&&(_e=o.loadingIndicator.renderIdle(Fe)),_e){let St=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;St.className=pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild(_e);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(St),b.appendChild(xt)}}if(Aa(i,b),de.length>0)for(let{messageId:L,fingerprint:Fe,bubble:Se}of de){let _e=i.querySelector(`#wrapper-${L}`);_e&&Se!==null&&(_e.replaceChildren(Se),_e.setAttribute("data-bubble-fp",Fe),zo.set(L,Fe))}if(zo.size>0)for(let L of zo.keys())O.has(L)||zo.delete(L);if(oe.length>0)for(let{messageId:L,fingerprint:Fe,bubble:Se}of oe){let _e=i.querySelector(`#wrapper-${L}`);_e&&Se!==null&&(_e.replaceChildren(Se),_e.setAttribute("data-bubble-fp",Fe),ho.set(L,Fe))}if(ho.size>0)for(let L of ho.keys())O.has(L)||ho.delete(L);if(ht.length>0)for(let{messageId:L,fingerprint:Fe,bubble:Se}of ht){let _e=i.querySelector(`#wrapper-${L}`);_e&&Se!==null&&(_e.replaceChildren(Se),_e.setAttribute("data-bubble-fp",Fe),zn.set(L,Fe))}if(zn.size>0)for(let L of zn.keys())O.has(L)||zn.delete(L)},kr=(i,g,h)=>{Du(i,g,h),_l()},Lr=null,Nu=()=>{if(Lr)return;let i=h=>{let b=h.composedPath();b.includes(Ee)||it&&b.includes(it)||mt(!1,"user")};Lr=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},oc=()=>{if(!Lr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Lr,!0),Lr=null};qe.push(()=>oc());let Pr=null,Fu=()=>{if(Pr)return;let i=h=>{h.key==="Escape"&&(h.isComposing||mt(!1,"user"))};Pr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},rc=()=>{if(!Pr)return;(t.ownerDocument??document).removeEventListener("keydown",Pr,!0),Pr=null};qe.push(()=>rc());let Ir=!1,sc=new Set,Ou=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},qo=()=>{if(!J())return;let i=Ie.peekBanner,g=Ie.peekTextNode;if(!i||!g)return;if(_){i.classList.remove("persona-pill-peek--visible");return}let h=F?.getMessages()??[],b;for(let Bt=h.length-1;Bt>=0;Bt--){let L=h[Bt];if(L.role==="assistant"&&L.content){b=L;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let S=b.content,k=!!b.streaming,Q=Ou(),O=ka(Q),G=O.type!=="none"?dr(O.type,Q?.plugins):null,se=G?.isAnimating?.(b)===!0,de=G!==null&&(k||se);de&&G&&!sc.has(G.name)&&(Ia(G,t),sc.add(G.name));let oe=de&&G?.containerClass?G.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==oe&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),oe&&we!==oe&&(g.classList.add(oe),g.dataset.personaPeekStreamClass=oe),de?(g.style.setProperty("--persona-stream-step",`${O.speed}ms`),g.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ve=de?La(S,O.buffer,G,b,k):S;if(de&&O.placeholder==="skeleton"&&k&&(!Ve||!Ve.trim())){let Bt=document.createElement("div"),L=is();L.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(L),Aa(g,Bt)}else{let Bt=Math.max(0,Ve.length-100),L=Ve.length>100?Ve.slice(-100):Ve,Fe=Jn(L);if(!de||!G){let Se=Ve.length>100?`\u2026${L}`:L;g.textContent!==Se&&(g.textContent=Se)}else{let Se=Fe;(G.wrap==="char"||G.wrap==="word")&&(Se=as(Fe,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:Bt}));let _e=document.createElement("div");if(_e.innerHTML=Se,G.useCaret&&L.length>0){let St=Pa(),pt=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),xt=pt[pt.length-1];xt?.parentNode?xt.parentNode.insertBefore(St,xt.nextSibling):_e.appendChild(St)}Aa(g,_e),G.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:O.speed,duration:O.duration})}}let jt=mn||Ir;i.classList.toggle("persona-pill-peek--visible",jt)};if(J()){let i=Ie.peekBanner;if(i){let b=S=>{S.preventDefault(),S.stopPropagation(),mt(!0,"user")};i.addEventListener("pointerdown",b),qe.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Ir||(Ir=!0,qo())},h=()=>{Ir&&(Ir=!1,qo())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",h),qe.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",g),it.addEventListener("pointerleave",h),qe.push(()=>{it.removeEventListener("pointerenter",g),it.removeEventListener("pointerleave",h)}))}let _u=i=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",b=g.bottomOffset??"16px",S=g.collapsedMaxWidth,k=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",O=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",oe=Ee.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",it){let we=it.style;we.bottom=b,we.width=S??""}if(i&&h!=="fullscreen"){if(h==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=O,oe.maxWidth=se,oe.maxHeight=G,oe.height=G;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${b} + ${de})`,oe.top=Q,oe.width=k,oe.maxWidth=se}},Rr=()=>{if(!D())return;if(J()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",de=_?"expanded":"collapsed";Ee.dataset.state=de,Ee.dataset.expandedSize=se,it&&(it.dataset.state=de,it.dataset.expandedSize=se),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),_u(_),ue.style.display=_?"flex":"none",Ls(),_?(Nu(),Fu()):(oc(),rc()),qo();return}let i=Ft(o),g=t.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,S=g.innerWidth<=h,k=b&&S&&I,Q=un(o).reveal;_?(Ee.style.removeProperty("display"),Ee.style.display=i?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":zt&&(zt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!k?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":zt&&(zt.style.display=i?"none":""))},mt=(i,g="user")=>{if(!D()||_===i)return;let h=_;_=i,Rr();let b=(()=>{let k=o.launcher?.sidebarMode??!1,Q=t.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,se=Q.innerWidth<=G,de=Ft(o)&&O&&se,oe=J()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||O&&se&&I||de||oe})();if(_&&b){if(!xn){let k=t.getRootNode(),Q=k instanceof ShadowRoot?k.host:t.closest(".persona-host");Q&&(xn=Yi(Q,o.launcher?.zIndex??Ut))}Cn||(Cn=Zi(t.ownerDocument))}else _||(xn?.(),xn=null,Cn?.(),Cn=null);_&&(Wr(),tc()||(Qt()==="follow"?Kn(!0):Zl()));let S={open:_,source:g,timestamp:Date.now()};_&&!h?l.emit("widget:opened",S):!_&&h&&l.emit("widget:closed",S),l.emit("widget:state",{open:_,launcherEnabled:I,voiceActive:Ge.active,streaming:F.isStreaming()})},ui=i=>{lt(i?"stop":"send"),V&&(V.disabled=i),Is.buttons.forEach(g=>{g.disabled=i}),z.dataset.personaComposerStreaming=i?"true":"false",z.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},fi=()=>{Ge.active||N&&N.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>fi(),200)});let ac=()=>{X.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",y.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",N.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let h=o.copy?.showWelcomeCard!==!1;i.style.display=h?"":"none",h?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!F?.isStreaming()&&(ne.textContent=o.copy?.sendButtonLabel??"Send"),N.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',N.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{x(g=>({...g,sessionId:i}))}});let bo=null,$u=()=>{bo==null&&(bo=setInterval(()=>{let i=ye.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(bo),bo=null;return}let g=Date.now();i.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=oa(g-b))})},100))},gi=(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,O)=>gi(Q,g[O]));let h=i,b=g,S=Object.keys(h),k=Object.keys(b);return S.length===k.length&&S.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&gi(h[Q],b[Q]))},ic=i=>{let{content:g,rawContent:h,llmContent:b,...S}=i;return S},mi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!wl(i),Uu=(i,g,h)=>{if(i.length!==g.length)return!1;let b=i[h.index],S=g[h.index];return!b||!S||b.id!==h.id||S.id!==h.id?!1:(!Object.is(b.content,S.content)||!Object.is(b.rawContent,S.rawContent)||!Object.is(b.llmContent,S.llmContent))&&mi(b)&&mi(S)&&gi(ic(b),ic(S))},lc=null,Vo=null,vo=null,Pn=null,Ds=i=>{lc=i;let g,h;Vo=null;for(let S=i.length-1;S>=0;S-=1){let k=i[S];if(!g&&k.role==="user"&&(g=k),!h&&k.role==="assistant"&&(h=k),!Vo&&mi(k)&&(Vo={index:S,id:k.id}),g&&h&&Vo)break}kr(ye,i,Ce),Ki(ye,fn.artifacts,{suppressTransition:mn}),$u(),ti(i),Kn(!mn),Hu(i),i.length===0&&(Er(),Sr=!0,si=!1),!oi||Ws?(oi=!0,ri=g?.id??null,ai=h?.id??null):g&&g.id!==ri?(ri=g.id,Wu(g.id)):h&&h.id!==ai&&Bu(),h&&(ai=h.id);let b=Ge.lastUserMessageId;g&&g.id!==b&&(Ge.lastUserMessageId=g.id,l.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,ci(i),qo()},hi=()=>{Pn!==null&&(cancelAnimationFrame(Pn),Pn=null);let i=vo;vo=null,i&&Ds(i)},cc=()=>{Pn!==null&&cancelAnimationFrame(Pn),Pn=null,vo=null},zu=i=>{let g=vo??lc;if(mn&&g&&Vo&&Uu(g,i,Vo)){vo=i,Pn===null&&(Pn=requestAnimationFrame(()=>{Pn=null;let h=vo;vo=null,h&&Ds(h)}));return}if(i.length===0){cc(),Ds(i);return}hi(),Ds(i)};F=new pa(o,{onMessagesChanged(i){zu(i)},onStatusChanged(i){let g=o.statusIndicator??{};Et(M,(b=>b==="idle"?g.idleText??Rt.idle:b==="connecting"?g.connectingText??Rt.connecting:b==="connected"?g.connectedText??Rt.connected:b==="error"?g.errorText??Rt.error:b==="paused"?g.pausedText??Rt.paused:b==="resuming"?g.resumingText??Rt.resuming:Rt[b])(i),g,i)},onStreamingChanged(i){i||(F?.getMessages().length===0?cc():hi()),mn=i,ui(i),F&&kr(ye,F.getMessages(),Ce),i||Kn(!0),en(),Rl(i?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":In(),Go();break;case"processing":In(),Gu();break;case"speaking":In(),Xu();break;default:i==="idle"&&F.isBargeInActive()?(In(),Go(),V?.setAttribute("aria-label","End voice session")):(Ge.active=!1,In(),Ln("system"),yn());break}},onArtifactsState(i){fn=i,i.artifacts.length===0&&(_o=!1),Ki(ye,i.artifacts,{suppressTransition:mn}),kn(),ci()},onReconnect(i){let{executionId:g,lastEventId:h}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:g,after:h}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:h,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:g,after:h})}}),gt.current=F,qe.push(()=>F.cancel());let yi=null;if(F.onReadAloudChange((i,g)=>{Fl=i,Ol=g,_l();let h=i??yi;i&&(yi=i);let b=h?F.getMessages().find(S=>S.id===h)??null:null;l.emit("message:read-aloud",{messageId:h,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(yi=null)}),oi=!0,o.voiceRecognition?.provider?.type==="runtype")try{F.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&F.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ae||o.onSSEEvent)&&F.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),ze?.processEvent(i,g),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let dc=()=>{o.resume&&typeof o.reconnectStream=="function"&&F.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=xl(i.metadata),T.syncFromMetadata()),i.messages?.length){Ws=!0;try{F.hydrateMessages(i.messages)}finally{Ws=!1}}i.artifacts?.length&&F.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>dc()):dc();let pc=()=>{!J()||_||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},uc=i=>{if(i.preventDefault(),F.isStreaming()){F.cancel(),ze?.reset(),Ne?.update();return}let g=N.value.trim(),h=Tt?.hasAttachments()??!1;if(!g&&!h)return;pc();let b;h&&(b=[],b.push(...Tt.getContentParts()),g&&b.push(Fi(g))),N.value="",N.style.height="auto",Ns(),F.sendMessage(g,{contentParts:b}),h&&Tt.clearAttachments()},ju=()=>o.features?.composerHistory!==!1,bi={...Sa},vi=!1,Ns=()=>{bi={...Sa}},qu=()=>F.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Vu=i=>{if(!N)return;vi=!0,N.value=i,N.dispatchEvent(new Event("input",{bubbles:!0})),vi=!1;let g=N.value.length;N.setSelectionRange(g,g)},fc=()=>{vi||Ns()},gc=i=>{if(N){if(ju()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=N.selectionStart===0&&N.selectionEnd===0,h=ip({direction:i.key==="ArrowUp"?"up":"down",history:qu(),currentValue:N.value,atStart:g,state:bi});if(bi=h.state,h.handled){i.preventDefault(),h.value!==void 0&&Vu(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(F.isStreaming()){i.preventDefault();return}Ns(),i.preventDefault(),ne.click()}}},mc=i=>{i.key!=="Escape"||i.isComposing||F.isStreaming()&&i.composedPath().includes(ue)&&(F.cancel(),ze?.reset(),Ne?.update(),Ns(),i.preventDefault(),i.stopImmediatePropagation())},hc=async i=>{if(o.attachments?.enabled!==!0||!Tt)return;let g=Xb(i.clipboardData);g.length!==0&&(i.preventDefault(),await Tt.handleFiles(g))},cn=null,An=!1,Ko=null,wt=null,yc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fs=(i="user")=>{if(An||F.isStreaming())return;let g=yc();if(!g)return;cn=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let S=N.value;cn.onresult=k=>{let Q="",O="";for(let se=0;se<k.results.length;se++){let de=k.results[se],oe=de[0].transcript;de.isFinal?Q+=oe+" ":O=oe}let G=S+Q+O;N.value=G,Ko&&clearTimeout(Ko),(Q||O)&&(Ko=window.setTimeout(()=>{let se=N.value.trim();se&&cn&&An&&(Gn(),N.value="",N.style.height="auto",F.sendMessage(se,{viaVoice:!0}))},b))},cn.onerror=k=>{k.error!=="no-speech"&&Gn()},cn.onend=()=>{if(An){let k=N.value.trim();k&&k!==S.trim()&&(N.value="",N.style.height="auto",F.sendMessage(k,{viaVoice:!0})),Gn()}};try{if(cn.start(),An=!0,Ge.active=!0,i!=="system"&&(Ge.manuallyDeactivated=!1),Ln(i),yn(),V){let k=o.voiceRecognition??{};wt={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,O=k.recordingIconColor,G=k.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let se=V.querySelector("svg");se&&se.setAttribute("stroke",O)}G&&(V.style.borderColor=G),V.setAttribute("aria-label","Stop voice recognition")}}catch{Gn("system")}},Gn=(i="user")=>{if(An){if(An=!1,Ko&&(clearTimeout(Ko),Ko=null),cn){try{cn.stop()}catch{}cn=null}if(Ge.active=!1,Ln(i),yn(),V){if(V.classList.remove("persona-voice-recording"),wt){V.style.backgroundColor=wt.backgroundColor,V.style.color=wt.color,V.style.borderColor=wt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",wt.color||"currentColor"),wt=null}V.setAttribute("aria-label","Start voice recognition")}}},Ku=(i,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",S=i?.provider?.type==="custom";if(!(h||b||S))return null;let Q=m("div","persona-send-button-wrapper"),O=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let G=i?.iconName??"mic",se=g?.size??"40px",de=i?.iconSize??se,oe=parseFloat(de)||24,we=i?.backgroundColor??g?.backgroundColor,Ve=i?.iconColor??g?.textColor;O.style.width=de,O.style.height=de,O.style.minWidth=de,O.style.minHeight=de,O.style.fontSize="18px",O.style.lineHeight="1",Ve?O.style.color=Ve:O.style.color="var(--persona-text, #111827)";let st=ae(G,oe,Ve||"currentColor",1.5);st?O.appendChild(st):O.textContent="\u{1F3A4}",we?O.style.backgroundColor=we: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),Q.appendChild(O);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let L=m("div","persona-send-button-tooltip");L.textContent=jt,Q.appendChild(L)}return{micButton:O,micButtonWrapper:Q}},wi=()=>{if(!V||wt)return;let i=o.voiceRecognition??{};wt={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}},xi=(i,g)=>{if(!V)return;let h=V.querySelector("svg");h&&h.remove();let b=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=ae(i,b,g,1.5);S&&V.appendChild(S)},Os=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Go=()=>{if(!V)return;wi();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,h=i.recordingIconColor,b=i.recordingBorderColor;if(Os(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let S=V.querySelector("svg");S&&S.setAttribute("stroke",h)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Gu=()=>{if(!V)return;wi();let i=o.voiceRecognition??{},g=F.getVoiceInterruptionMode(),h=i.processingIconName??"loader",b=i.processingIconColor??wt?.color??"",S=i.processingBackgroundColor??wt?.backgroundColor??"",k=i.processingBorderColor??wt?.borderColor??"";Os(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=S,V.style.borderColor=k;let Q=b||"currentColor";V.style.color=Q,xi(h,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Xu=()=>{if(!V)return;wi();let i=o.voiceRecognition??{},g=F.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??h,S=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??wt?.color??"":wt?.color??""),k=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":wt?.borderColor??"");Os(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=k,V.style.borderColor=Q;let O=S||"currentColor";V.style.color=O,xi(b,O);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",G),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},In=()=>{V&&(Os(),wt&&(V.style.backgroundColor=wt.backgroundColor??"",V.style.color=wt.color??"",V.style.borderColor=wt.borderColor??"",xi(wt.iconName,wt.color||"currentColor"),wt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},_s=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=F.getVoiceStatus(),g=F.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,yn(),Ln("user"),In()});return}F.toggleVoice().then(()=>{Ge.active=F.isVoiceActive(),Ge.manuallyDeactivated=!F.isVoiceActive(),yn(),Ln("user"),F.isVoiceActive()?Go():In()});return}if(An){let i=N.value.trim();Ge.manuallyDeactivated=!0,yn(),Gn("user"),i&&(N.value="",N.style.height="auto",F.sendMessage(i))}else Ge.manuallyDeactivated=!1,yn(),Fs("user")};Bl=_s,V&&(V.addEventListener("click",_s),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),In()):Gn("system"),V&&V.removeEventListener("click",_s)}));let Qu=l.on("assistant:complete",()=>{Kl&&(Ge.active||Ge.manuallyDeactivated||Kl==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?F.toggleVoice().then(()=>{Ge.active=F.isVoiceActive(),Ln("auto"),F.isVoiceActive()&&Go()}):Fs("auto"))},600))});qe.push(Qu);let Ju=l.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});qe.push(Ju);let bc=()=>{mt(!_,"user")},Ot=null,zt=null;if(I&&!J()){let{instance:i,element:g}=tl({config:o,plugins:r,onToggle:bc});Ot=i,i||(zt=g)}Ot?t.appendChild(Ot.element):zt&&t.appendChild(zt),Rr(),ti(),ac(),ui(F.isStreaming()),tc()||(Qt()==="follow"?Kn(!0):Zl()),Eu(),q&&(!I||J()?setTimeout(()=>fi(),0):_&&setTimeout(()=>fi(),200));let Wr=()=>{if(J()){Oo(),Rr();return}let i=Ft(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),b=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=k,O=S&&Q&&I;try{if(O){wr(),xr=ks();return}let G=!1;j&&(j=!1,wr(),G=!0);let se=ks();if(!G&&se!==xr&&(wr(),G=!0),xr=se,G&&Za(),!I&&!i){me.style.height="",me.style.width="";return}if(!g&&!i){let oe=o?.launcher?.width??o?.launcherWidth??Nn;me.style.width=oe,me.style.maxWidth=oe}if(Es(),!h){let de=b.innerHeight,oe=64,we=o.launcher?.heightOffset??0,Ve=Math.max(200,de-oe),ht=Math.min(640,Ve),st=Math.max(200,ht-we);me.style.height=`${st}px`}}finally{if(Oo(),Rr(),_&&I){let se=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),de=o.launcher?.sidebarMode??!1,oe=o.launcher?.mobileFullscreen??!0,we=Ft(o)&&oe&&se,Ve=de||oe&&se&&I||we;if(Ve&&!Cn){let ht=t.getRootNode(),st=ht instanceof ShadowRoot?ht.host:t.closest(".persona-host");st&&!xn&&(xn=Yi(st,o.launcher?.zIndex??Ut)),Cn=Zi(t.ownerDocument)}else Ve||(xn?.(),xn=null,Cn?.(),Cn=null)}}};Wr();let vc=t.ownerDocument.defaultView??window;if(vc.addEventListener("resize",Wr),qe.push(()=>vc.removeEventListener("resize",Wr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Oo()});i.observe(z),qe.push(()=>i.disconnect())}an=ie.scrollTop;let wc=Mn(ie),Yu=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Ci=()=>fp(Yu(),ie),xc=()=>{let i=ie.scrollTop,g=Mn(ie),h=g<wc;if(wc=g,!On()){an=i,en();return}let{action:b,nextLastScrollTop:S}=Ma({following:Zt.isFollowing(),currentScrollTop:i,lastScrollTop:an,nearBottom:so(ie,Bs),userScrollThreshold:Tu,isAutoScrolling:ln||Rs||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=S,b==="resume"){Ci()||Vn();return}b==="pause"&&Mr()};if(ie.addEventListener("scroll",xc,{passive:!0}),qe.push(()=>ie.removeEventListener("scroll",xc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Ru()});i.observe(ye),i.observe(ie),qe.push(()=>i.disconnect())}let Cc=()=>{On()&&Zt.isFollowing()&&Ci()&&Mr()},Ac=ie.ownerDocument;Ac.addEventListener("selectionchange",Cc),qe.push(()=>{Ac.removeEventListener("selectionchange",Cc)});let Zu=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Sc=i=>{Ll()&&On()&&Zt.isFollowing()&&Zu.has(i.key)&&Mr()},Tc=i=>{if(!Ll()||!On()||!Zt.isFollowing())return;let g=i.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&Mr()};ie.addEventListener("keydown",Sc),ie.addEventListener("focusin",Tc),qe.push(()=>{ie.removeEventListener("keydown",Sc),ie.removeEventListener("focusin",Tc)});let Mc=i=>{if(!On())return;let g=Ea({following:Zt.isFollowing(),deltaY:i.deltaY,nearBottom:so(ie,Bs),resumeWhenNearBottom:!0});g==="pause"?Mr():g==="resume"&&!Ci()&&Vn()};ie.addEventListener("wheel",Mc,{passive:!0}),qe.push(()=>ie.removeEventListener("wheel",Mc)),Pt.addEventListener("click",()=>{Er(),ie.scrollTop=ie.scrollHeight,an=ie.scrollTop,Vn(),Kn(!0),en()}),qe.push(()=>Pt.remove()),qe.push(()=>{Ql(),Er()});let Ec=()=>{A&&(go&&(A.removeEventListener("click",go),go=null),D()?(A.style.display="",go=()=>{mt(!1,"user")},A.addEventListener("click",go)):A.style.display="none")};Ec(),(()=>{let{clearChatButton:i}=Ie;i&&i.addEventListener("click",()=>{F.clearMessages(),mo.clear(),Vn(),tr(Ie.composerOverlay);try{localStorage.removeItem(gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==gr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&li(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},T.syncFromMetadata(),Ae?.clear(),ze?.reset(),Ne?.update()})})(),ke&&ke.addEventListener("submit",uc),N?.addEventListener("keydown",gc),N?.addEventListener("input",fc),N?.addEventListener("paste",hc);let kc=t.ownerDocument??document;kc.addEventListener("keydown",mc,!0);let Lc="persona-attachment-drop-active",Br=0,Ai=()=>{Br=0,ue.classList.remove(Lc)},Xo=()=>o.attachments?.enabled===!0&&Tt!==null,Pc=i=>{!qa(i.dataTransfer)||!Xo()||(Br++,Br===1&&ue.classList.add(Lc))},Ic=i=>{!qa(i.dataTransfer)||!Xo()||(Br--,Br<=0&&Ai())},Rc=i=>{!qa(i.dataTransfer)||!Xo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Wc=i=>{if(!qa(i.dataTransfer)||!Xo())return;i.preventDefault(),i.stopPropagation(),Ai();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Tt.handleFiles(g)},Xn=!0;ue.addEventListener("dragenter",Pc,Xn),ue.addEventListener("dragleave",Ic,Xn),t.addEventListener("dragover",Rc,Xn),t.addEventListener("drop",Wc,Xn);let $s=t.ownerDocument,Bc=i=>{Xo()&&i.preventDefault()},Hc=i=>{Xo()&&i.preventDefault()};$s.addEventListener("dragover",Bc),$s.addEventListener("drop",Hc),qe.push(()=>{ke&&ke.removeEventListener("submit",uc),N?.removeEventListener("keydown",gc),N?.removeEventListener("input",fc),N?.removeEventListener("paste",hc),kc.removeEventListener("keydown",mc,!0)}),qe.push(()=>{ue.removeEventListener("dragenter",Pc,Xn),ue.removeEventListener("dragleave",Ic,Xn),t.removeEventListener("dragover",Rc,Xn),t.removeEventListener("drop",Wc,Xn),$s.removeEventListener("dragover",Bc),$s.removeEventListener("drop",Hc),Ai()}),qe.push(()=>{F.cancel()}),Ot?qe.push(()=>{Ot?.destroy()}):zt&&qe.push(()=>{zt?.remove()});let It={update(i){let g=o.toolCall,h=o.messageActions,b=o.layout?.messages,S=o.colorScheme,k=o.loadingIndicator,Q=o.iterationDisplay,O=o.features?.showReasoning,G=o.features?.showToolCalls,se=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type;o={...o,...i},Ls(),es(t,o),hs(t,o),ys(t,o),kn(),o.colorScheme!==S&&Vl();let we=hl.getForInstance(o.plugins);r.length=0,r.push(...we),I=o.launcher?.enabled??!0,H=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,le=o.features?.scrollToBottom??{};let Ve=Qt();Z=o.features?.scrollBehavior??{},Ve!==Qt()&&(Er(),Vn()),Wl(),en();let ht=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!ht){if(Ae||(fe=new gs(ve),Ae=new fs(Te,fe),ze=ze??new ms,fe.open().then(()=>Ae?.restore()).catch(()=>{}),F.setSSEEventCallback((ee,tt)=>{o.onSSEEvent?.(ee,tt),ze?.processEvent(ee,tt),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(tt)})})),!rt&&B){let ee=o.features?.eventStream?.classNames,tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");rt=m("button",tt),rt.style.width="28px",rt.style.height="28px",rt.style.color=Gt.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let At=ae("activity","18px","currentColor",1.5);At&&rt.appendChild(At);let Ke=Ie.clearChatButtonWrapper,ct=Ie.closeButtonWrapper,$t=Ke||ct;$t&&$t.parentNode===B?B.insertBefore(rt,$t):B.appendChild(rt),rt.addEventListener("click",()=>{Pe?br():Xa()})}}else!Y&&ht&&(br(),rt&&(rt.remove(),rt=null),Ae?.clear(),fe?.destroy(),Ae=null,fe=null,ze?.reset(),ze=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Ot&&!zt){let{instance:ee,element:tt}=tl({config:o,plugins:r,onToggle:bc});Ot=ee,ee||(zt=tt),t.appendChild(tt)}Ot&&Ot.update(o),R&&o.launcher?.title!==void 0&&(R.textContent=o.launcher.title),K&&o.launcher?.subtitle!==void 0&&(K.textContent=o.launcher.subtitle);let st=o.layout?.header;if(st?.layout!==C&&B){let ee=st?Ba(o,st,{showClose:D(),onClose:()=>mt(!1,"user")}):Ho({config:o,showClose:D(),onClose:()=>mt(!1,"user")});ft.replaceHeader(ee),B=ft.header.element,E=ft.header.iconHolder,R=ft.header.headerTitle,K=ft.header.headerSubtitle,A=ft.header.closeButton,C=st?.layout}else if(st&&(E&&(E.style.display=st.showIcon===!1?"none":""),R&&(R.style.display=st.showTitle===!1?"none":""),K&&(K.style.display=st.showSubtitle===!1?"none":""),A&&(A.style.display=st.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let ee=st.showClearChat;if(ee!==void 0){Ie.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:tt}=Ie;tt&&!tt.classList.contains("persona-absolute")&&(ee?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}let Bt=o.layout?.showHeader!==!1;B&&(B.style.display=Bt?"":"none");let L=o.layout?.showFooter!==!1;z&&(z.style.display=L?"":"none"),Oo(),en(),I!==$?I?mt(H,"auto"):(_=!0,Rr()):H!==U&&mt(H,"auto"),U=H,$=I,Wr(),Ec();let _e=JSON.stringify(i.toolCall)!==JSON.stringify(g),St=JSON.stringify(o.messageActions)!==JSON.stringify(h),pt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),xt=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,yt=o.iterationDisplay!==Q,_t=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);(_e||St||pt||xt||yt||_t)&&F&&(ni++,kr(ye,F.getMessages(),Ce));let ut=o.features?.streamAnimation?.type;if(ut!==oe&&ut&&ut!=="none"){let ee=dr(ut,o.features?.streamAnimation?.plugins);ee&&Ia(ee,t)}let pe=o.launcher??{},Ct=pe.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Ht=Ct||qt===!1,ot=pe.headerIconName,je=pe.headerIconSize??"48px";if(E){let ee=ue.querySelector(".persona-border-b-persona-divider"),tt=ee?.querySelector(".persona-flex-col");if(Ht)E.style.display="none",ee&&tt&&!ee.contains(tt)&&ee.insertBefore(tt,ee.firstChild);else{if(E.style.display="",E.style.height=je,E.style.width=je,ee&&tt&&(ee.contains(E)?E.nextSibling!==tt&&(E.remove(),ee.insertBefore(E,tt)):ee.insertBefore(E,tt)),ot){let Ke=parseFloat(je)||24,ct=ae(ot,Ke*.6,"currentColor",1);ct?E.replaceChildren(ct):E.textContent=pe.agentIconText??"\u{1F4AC}"}else if(pe.iconUrl){let Ke=E.querySelector("img");if(Ke)Ke.src=pe.iconUrl,Ke.style.height=je,Ke.style.width=je;else{let ct=document.createElement("img");ct.src=pe.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=je,ct.style.width=je,E.replaceChildren(ct)}}else{let Ke=E.querySelector("svg"),ct=E.querySelector("img");(Ke||ct)&&E.replaceChildren(),E.textContent=pe.agentIconText??"\u{1F4AC}"}let At=E.querySelector("img");At&&(At.style.height=je,At.style.width=je)}}let Ye=o.layout?.header?.showTitle,kt=o.layout?.header?.showSubtitle;if(R&&(R.style.display=Ye===!1?"none":""),K&&(K.style.display=kt===!1?"none":""),A){o.layout?.header?.showCloseButton===!1?A.style.display="none":A.style.display="";let tt=pe.closeButtonSize??"32px",At=pe.closeButtonPlacement??"inline";A.style.height=tt,A.style.width=tt;let{closeButtonWrapper:Ke}=Ie,ct=At==="top-right",$t=Ke?.classList.contains("persona-absolute");if(Ke&&ct!==$t)if(Ke.remove(),ct)Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(Ke);else{let Ue=pe.clearChat?.placement??"inline",Nt=pe.clearChat?.enabled??!0;Ke.className=Nt&&Ue==="inline"?"":"persona-ml-auto";let Yt=ue.querySelector(".persona-border-b-persona-divider");Yt&&Yt.appendChild(Ke)}if(A.style.color=pe.closeButtonColor||Gt.actionIconColor,pe.closeButtonBackgroundColor?(A.style.backgroundColor=pe.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Ue=pe.closeButtonBorderWidth||"0px",Nt=pe.closeButtonBorderColor||"transparent";A.style.border=`${Ue} solid ${Nt}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");pe.closeButtonBorderRadius?(A.style.borderRadius=pe.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(A.style.paddingLeft=pe.closeButtonPaddingX,A.style.paddingRight=pe.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),pe.closeButtonPaddingY?(A.style.paddingTop=pe.closeButtonPaddingY,A.style.paddingBottom=pe.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let nn=pe.closeButtonIconName??"x",bn=pe.closeButtonIconText??"\xD7";A.innerHTML="";let Vt=ae(nn,"28px","currentColor",1);Vt?A.appendChild(Vt):A.textContent=bn;let Mt=pe.closeButtonTooltipText??"Close chat",on=pe.closeButtonShowTooltip??!0;if(A.setAttribute("aria-label",Mt),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),on&&Mt)){let Ue=null,Nt=()=>{if(Ue||!A)return;let So=A.ownerDocument,Fr=So.body;if(!Fr)return;Ue=Sn(So,"div","persona-clear-chat-tooltip"),Ue.textContent=Mt;let Or=Sn(So,"div");Or.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Or);let To=A.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(oo),Ue.style.left=`${To.left+To.width/2}px`,Ue.style.top=`${To.top-8}px`,Ue.style.transform="translate(-50%, -100%)",Fr.appendChild(Ue)},Yt=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};Ke.addEventListener("mouseenter",Nt),Ke.addEventListener("mouseleave",Yt),A.addEventListener("focus",Nt),A.addEventListener("blur",Yt),Ke._cleanupTooltip=()=>{Yt(),Ke&&(Ke.removeEventListener("mouseenter",Nt),Ke.removeEventListener("mouseleave",Yt)),A&&(A.removeEventListener("focus",Nt),A.removeEventListener("blur",Yt))}}}let{clearChatButton:He,clearChatButtonWrapper:Ze}=Ie;if(He){let ee=pe.clearChat??{},tt=ee.enabled??!0,At=o.layout?.header?.showClearChat,Ke=At!==void 0?At:tt,ct=ee.placement??"inline";if(Ze){Ze.style.display=Ke?"":"none";let{closeButtonWrapper:$t}=Ie;!J()&&$t&&!$t.classList.contains("persona-absolute")&&(Ke?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let nn=ct==="top-right",bn=Ze.classList.contains("persona-absolute");if(!J()&&nn!==bn&&Ke){if(Ze.remove(),nn)Ze.className="persona-absolute persona-top-4 persona-z-50",Ze.style.right="48px",ue.style.position="relative",ue.appendChild(Ze);else{Ze.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ze.style.right="";let Mt=ue.querySelector(".persona-border-b-persona-divider"),on=Ie.closeButtonWrapper;Mt&&on&&on.parentElement===Mt?Mt.insertBefore(Ze,on):Mt&&Mt.appendChild(Ze)}let Vt=Ie.closeButtonWrapper;Vt&&!Vt.classList.contains("persona-absolute")&&(nn?Vt.classList.add("persona-ml-auto"):Vt.classList.remove("persona-ml-auto"))}}if(Ke){if(!J()){let Ue=ee.size??"32px";He.style.height=Ue,He.style.width=Ue}let $t=ee.iconName??"refresh-cw",nn=ee.iconColor??"";He.style.color=nn||Gt.actionIconColor,He.innerHTML="";let bn=J()?"14px":"20px",Vt=ae($t,bn,"currentColor",2);if(Vt&&He.appendChild(Vt),ee.backgroundColor?(He.style.backgroundColor=ee.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let Ue=ee.borderWidth||"0px",Nt=ee.borderColor||"transparent";He.style.border=`${Ue} solid ${Nt}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");ee.borderRadius?(He.style.borderRadius=ee.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),ee.paddingX?(He.style.paddingLeft=ee.paddingX,He.style.paddingRight=ee.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),ee.paddingY?(He.style.paddingTop=ee.paddingY,He.style.paddingBottom=ee.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Mt=ee.tooltipText??"Clear chat",on=ee.showTooltip??!0;if(He.setAttribute("aria-label",Mt),Ze&&(Ze._cleanupTooltip&&(Ze._cleanupTooltip(),delete Ze._cleanupTooltip),on&&Mt)){let Ue=null,Nt=()=>{if(Ue||!He)return;let So=He.ownerDocument,Fr=So.body;if(!Fr)return;Ue=Sn(So,"div","persona-clear-chat-tooltip"),Ue.textContent=Mt;let Or=Sn(So,"div");Or.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Or);let To=He.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(oo),Ue.style.left=`${To.left+To.width/2}px`,Ue.style.top=`${To.top-8}px`,Ue.style.transform="translate(-50%, -100%)",Fr.appendChild(Ue)},Yt=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};Ze.addEventListener("mouseenter",Nt),Ze.addEventListener("mouseleave",Yt),He.addEventListener("focus",Nt),He.addEventListener("blur",Yt),Ze._cleanupTooltip=()=>{Yt(),Ze&&(Ze.removeEventListener("mouseenter",Nt),Ze.removeEventListener("mouseleave",Yt)),He&&(He.removeEventListener("focus",Nt),He.removeEventListener("blur",Yt))}}}}let tn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[bl],xo=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick];T=vl({parsers:tn,handlers:xo,getSessionMetadata:v,updateSessionMetadata:x,emit:l.emit,documentRef:typeof document<"u"?document:null}),Ce=ru(o,T,Me),F.updateConfig(o),kr(ye,F.getMessages(),Ce),ti(),ac(),ui(F.isStreaming());let Dc=o.voiceRecognition?.enabled===!0,Us=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if(Dc&&(Us||Lt))if(!V||!$e){let ee=Ku(o.voiceRecognition,o.sendButton);ee&&(V=ee.micButton,$e=ee.micButtonWrapper,Re.insertBefore($e,De),V.addEventListener("click",_s),V.disabled=F.isStreaming())}else{let ee=o.voiceRecognition??{},tt=o.sendButton??{},At=ee.iconName??"mic",Ke=tt.size??"40px",ct=ee.iconSize??Ke,$t=parseFloat(ct)||24;V.style.width=ct,V.style.height=ct,V.style.minWidth=ct,V.style.minHeight=ct;let nn=ee.iconColor??tt.textColor??"currentColor";V.innerHTML="";let bn=ae(At,$t,nn,2);bn?V.appendChild(bn):V.textContent="\u{1F3A4}";let Vt=ee.backgroundColor??tt.backgroundColor;Vt?V.style.backgroundColor=Vt:V.style.backgroundColor="",nn?V.style.color=nn:V.style.color="var(--persona-text, #111827)",ee.borderWidth?(V.style.borderWidth=ee.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ee.borderColor?V.style.borderColor=ee.borderColor:V.style.borderColor="",ee.paddingX?(V.style.paddingLeft=ee.paddingX,V.style.paddingRight=ee.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ee.paddingY?(V.style.paddingTop=ee.paddingY,V.style.paddingBottom=ee.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Mt=$e?.querySelector(".persona-send-button-tooltip"),on=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&on)if(Mt)Mt.textContent=on,Mt.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=on,$e?.insertBefore(Nt,V)}else Mt&&(Mt.style.display="none");$e.style.display="",V.disabled=F.isStreaming()}else V&&$e&&($e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()&&F.toggleVoice():An&&Gn());if(o.attachments?.enabled===!0)if(!Be||!xe){let ee=o.attachments??{},At=(o.sendButton??{}).size??"40px";Qe||(Qe=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",ke.insertBefore(Qe,N)),Le||(Le=document.createElement("input"),Le.type="file",Le.accept=(ee.allowedTypes??Dn).join(","),Le.multiple=(ee.maxFiles??4)>1,Le.style.display="none",Le.setAttribute("aria-label","Attach files"),ke.insertBefore(Le,N)),Be=m("div","persona-send-button-wrapper"),xe=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),xe.type="button",xe.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ke=ee.buttonIconName??"paperclip",ct=At,$t=parseFloat(ct)||40,nn=Math.round($t*.6);xe.style.width=ct,xe.style.height=ct,xe.style.minWidth=ct,xe.style.minHeight=ct,xe.style.fontSize="18px",xe.style.lineHeight="1",xe.style.backgroundColor="transparent",xe.style.color="var(--persona-primary, #111827)",xe.style.border="none",xe.style.borderRadius="6px",xe.style.transition="background-color 0.15s ease",xe.addEventListener("mouseenter",()=>{xe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),xe.addEventListener("mouseleave",()=>{xe.style.backgroundColor="transparent"});let bn=ae(Ke,nn,"currentColor",1.5);bn?xe.appendChild(bn):xe.textContent="\u{1F4CE}",xe.addEventListener("click",on=>{on.preventDefault(),Le?.click()}),Be.appendChild(xe);let Vt=ee.buttonTooltipText??"Attach file",Mt=m("div","persona-send-button-tooltip");Mt.textContent=Vt,Be.appendChild(Mt),et.append(Be),!Tt&&Le&&Qe&&(Tt=Yr.fromConfig(ee),Tt.setPreviewsContainer(Qe),Le.addEventListener("change",async()=>{Tt&&Le?.files&&(await Tt.handleFileSelect(Le.files),Le.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(su(ee.dropOverlay))}else{Be.style.display="";let ee=o.attachments??{};Le&&(Le.accept=(ee.allowedTypes??Dn).join(","),Le.multiple=(ee.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else Be&&(Be.style.display="none"),Tt&&Tt.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},Hr=Dt.useIcon??!1,js=Dt.iconText??"\u2191",Qo=Dt.iconName,Dr=Dt.tooltipText??"Send message",Si=Dt.showTooltip??!1,Co=Dt.size??"40px",Rn=Dt.backgroundColor,Ao=Dt.textColor;if(Hr){if(ne.style.width=Co,ne.style.height=Co,ne.style.minWidth=Co,ne.style.minHeight=Co,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.innerHTML="",Ao?ne.style.color=Ao:ne.style.color="var(--persona-button-primary-fg, #ffffff)",Qo){let ee=parseFloat(Co)||24,tt=Ao?.trim()||"currentColor",At=ae(Qo,ee,tt,2);At?ne.appendChild(At):ne.textContent=js}else ne.textContent=js;ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Rn?(ne.style.backgroundColor=Rn,ne.classList.remove("persona-bg-persona-primary")):(ne.style.backgroundColor="",ne.classList.add("persona-bg-persona-primary"))}else ne.textContent=o.copy?.sendButtonLabel??"Send",ne.style.width="",ne.style.height="",ne.style.minWidth="",ne.style.minHeight="",ne.style.fontSize="",ne.style.lineHeight="",ne.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",Rn?(ne.style.backgroundColor=Rn,ne.classList.remove("persona-bg-persona-accent")):ne.classList.add("persona-bg-persona-accent"),Ao?ne.style.color=Ao:ne.classList.add("persona-text-white");Dt.borderWidth?(ne.style.borderWidth=Dt.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Dt.borderColor?ne.style.borderColor=Dt.borderColor:ne.style.borderColor="",Dt.paddingX?(ne.style.paddingLeft=Dt.paddingX,ne.style.paddingRight=Dt.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Dt.paddingY?(ne.style.paddingTop=Dt.paddingY,ne.style.paddingBottom=Dt.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let Nr=De?.querySelector(".persona-send-button-tooltip");if(Si&&Dr)if(Nr)Nr.textContent=Dr,Nr.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Dr,De?.insertBefore(ee,ne)}else Nr&&(Nr.style.display="none");let qs=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);qs?(ye.style.maxWidth=qs,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",ke&&(ke.style.maxWidth=qs,ke.style.marginLeft="auto",ke.style.marginRight="auto"),bt&&(bt.style.maxWidth=qs,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",ke&&(ke.style.maxWidth="",ke.style.marginLeft="",ke.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let Qn=o.statusIndicator??{},ef=Qn.visible??!0;if(M.style.display=ef?"":"none",F){let ee=F.getStatus();Et(M,(At=>At==="idle"?Qn.idleText??Rt.idle:At==="connecting"?Qn.connectingText??Rt.connecting:At==="connected"?Qn.connectedText??Rt.connected:At==="error"?Qn.errorText??Rt.error:Rt[At])(ee),Qn,ee)}M.classList.remove("persona-text-left","persona-text-center","persona-text-right");let tf=Qn.align==="left"?"persona-text-left":Qn.align==="center"?"persona-text-center":"persona-text-right";M.classList.add(tf)},open(){D()&&mt(!0,"api")},close(){D()&&mt(!1,"api")},toggle(){D()&&mt(!_,"api")},reconnect(){F.reconnectNow()},clearChat(){En=!1,F.clearMessages(),mo.clear(),Vn();try{localStorage.removeItem(gr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${gr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==gr)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),d?.clear&&li(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},T.syncFromMetadata(),Ae?.clear(),ze?.reset(),Ne?.update()},setMessage(i){return!N||F.isStreaming()?!1:(!_&&D()&&mt(!0,"system"),N.value=i,N.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(F.isStreaming())return!1;let g=i?.trim()||N.value.trim();return g?(!_&&D()&&mt(!0,"system"),N.value="",N.style.height="auto",F.sendMessage(g),!0):!1},startVoiceRecognition(){return F.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(F.isVoiceActive()||(!_&&D()&&mt(!0,"system"),Ge.manuallyDeactivated=!1,yn(),F.toggleVoice().then(()=>{Ge.active=F.isVoiceActive(),Ln("user"),F.isVoiceActive()&&Go()})),!0):An?!0:yc()?(!_&&D()&&mt(!0,"system"),Ge.manuallyDeactivated=!1,yn(),Fs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,yn(),Ln("user"),In()}),!0):!1:An?(Ge.manuallyDeactivated=!0,yn(),Gn("user"),!0):!1},injectMessage(i){return!_&&D()&&mt(!0,"system"),F.injectMessage(i)},injectAssistantMessage(i){!_&&D()&&mt(!0,"system");let g=F.injectAssistantMessage(i);return ce&&(ce=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),g},injectUserMessage(i){return!_&&D()&&mt(!0,"system"),F.injectUserMessage(i)},injectSystemMessage(i){return!_&&D()&&mt(!0,"system"),F.injectSystemMessage(i)},injectMessageBatch(i){return!_&&D()&&mt(!0,"system"),F.injectMessageBatch(i)},injectComponentDirective(i){return!_&&D()&&mt(!0,"system"),F.injectComponentDirective(i)},injectTestMessage(i){!_&&D()&&mt(!0,"system"),F.injectTestEvent(i)},async connectStream(i,g){return F.connectStream(i,g)},__pushEventStreamEvent(i){Ae&&(ze?.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(){!Y||!Ae||Xa()},hideEventStream(){Pe&&br()},isEventStreamVisible(){return Pe},showArtifacts(){Xt(o)&&(En=!1,_o=!0,kn(),Je?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(En=!0,kn())},upsertArtifact(i){return Xt(o)?(Eo(o.features?.artifacts,i.artifactType)==="panel"&&(En=!1,_o=!0),F.upsertArtifact(i)):null},selectArtifact(i){Xt(o)&&F.selectArtifact(i)},clearArtifacts(){Xt(o)&&F.clearArtifacts()},getArtifacts(){return F?.getArtifacts()??[]},getSelectedArtifactId(){return F?.getSelectedArtifactId()??null},focusInput(){return I&&!_&&!J()||!N?!1:(N.focus(),!0)},async resolveApproval(i,g,h){let S=F.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!S?.approval)throw new Error(`Approval not found: ${i}`);if(S.approval.toolType==="webmcp"){F.resolveWebMcpApproval(S.id,g);return}return F.resolveApproval(S.approval,g,h)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){x(i)},on(i,g){return l.on(i,g)},off(i,g){l.off(i,g)},isOpen(){return D()&&_},isVoiceActive(){return Ge.active},toggleReadAloud(i){F.toggleReadAloud(i)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(i){return F.getReadAloudState(i)},onReadAloudChange(i){return F.onReadAloudChange(i)},getState(){return{open:D()&&_,launcherEnabled:I,voiceActive:Ge.active,streaming:F.isStreaming()}},showCSATFeedback(i){!_&&D()&&mt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let h=tu({onSubmit:async(b,S)=>{F.isClientTokenMode()&&await F.submitCSATFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!_&&D()&&mt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let h=nu({onSubmit:async(b,S)=>{F.isClientTokenMode()&&await F.submitNPSFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return F.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return F.submitNPSFeedback(i,g)},destroy(){hi(),bo!=null&&(clearInterval(bo),bo=null),qe.forEach(i=>i()),Ee.remove(),it?.remove(),Ot?.destroy(),zt?.remove(),go&&A.removeEventListener("click",go)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:h=>h?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=g,qe.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&It.focusInput()};if(window.addEventListener("persona:focusInput",g),qe.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let O=se=>{let de=se.detail;(!de?.instanceId||de.instanceId===i)&&It.showEventStream()},G=se=>{let de=se.detail;(!de?.instanceId||de.instanceId===i)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",G),qe.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",G)})}let h=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&It.showArtifacts()},b=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&It.hideArtifacts()},S=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&It.upsertArtifact(G.artifact)},k=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&It.selectArtifact(G.id)},Q=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",Q),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",Q)})}let dn=Qb(o.persistState);if(dn&&D()){let i=Jb(dn.storage),g=`${dn.keyPrefix}widget-open`,h=`${dn.keyPrefix}widget-voice`,b=`${dn.keyPrefix}widget-voice-mode`;if(i){let S=dn.persist?.openState&&i.getItem(g)==="true",k=dn.persist?.voiceState&&i.getItem(h)==="true",Q=dn.persist?.voiceState&&i.getItem(b)==="true";if(S&&setTimeout(()=>{It.open(),setTimeout(()=>{if(k||Q)It.startVoiceRecognition();else if(dn.persist?.focusInput){let O=t.querySelector("textarea");O&&O.focus()}},100)},0),dn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(g,"true")}),l.on("widget:closed",()=>{i.setItem(g,"false")})),dn.persist?.voiceState&&(l.on("voice:state",O=>{i.setItem(h,O.active?"true":"false")}),l.on("user:message",O=>{i.setItem(b,O.viaVoice?"true":"false")})),dn.clearOnChatClear){let O=()=>{i.removeItem(g),i.removeItem(h),i.removeItem(b)},G=()=>O();window.addEventListener("persona:clear-chat",G),qe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(w&&D()&&setTimeout(()=>{It.open()},0),qo(),!Su){let i=Ks(()=>{F&&(ni++,mo.clear(),kr(ye,F.getMessages(),Ce))});qe.push(i)}return It};var iu=(t,e)=>{let n=t.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,e*parseFloat(r[1])/100):420},Yb=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Zb=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},ev=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.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."+(e.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 ${e.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.")},lu=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},Tl=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},cu=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Tl(t)},Cl=t=>{t.style.transition=""},Al=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Sl=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Va=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},tv=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},nv=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},ov=t=>{let e=sr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Kt(e,r)??r;return{inset:o(n?.inset,fa),canvasBackground:o(n?.canvasBackground,ga)}},du=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},rv=(t,e,n,o,r,s,a,l)=>{let p=un(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";tv(t,e,n,o,d),nv(t,e,n,o,p.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.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.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,P=f!=null?f.innerWidth<=x:!1;if(v&&P&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Al(e),Cl(o),cu(o),Sl(n),Va(r,o),du(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.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??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),cu(o),Yb(o,p.maxHeight),du(o,c&&a,u,w),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Al(e),Cl(o),Sl(n),Va(r,o);let T=p.animate?"transform 180ms ease":"none",I=p.side==="right"?"translateX(100%)":"translateX(-100%)",H=a?"translateX(0)":I;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=T,o.style.transform=H,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"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Cl(o),Tl(o),Va(r,o);let T=iu(p.width,t.clientWidth),I=Math.max(0,t.clientWidth),H=p.animate?"margin-left 180ms ease":"none",q=p.side==="right"?a?-T:0:a?0:-T;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${I+T}px`,e.style.transition=H,e.style.marginLeft=`${q}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}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{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Al(e),Tl(o),Sl(n),Va(r,o);let T=p.reveal==="emerge";T?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let I=a?p.width:"0px",H=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",q=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${I}`,o.style.width=I,o.style.maxWidth=I,o.style.minWidth=I,o.style.minHeight="0",Zb(o,p.maxHeight),o.style.overflow=T||q?"hidden":"visible",o.style.transition=H,T){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let U=c?`calc(${iu(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=U,r.style.minWidth=U,r.style.maxWidth=U,r.style.boxSizing="border-box"}}},sv=(t,e)=>{let n=t.ownerDocument.createElement("div");return lu(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){lu(n,o)},destroy(){n.remove()}}},av=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.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=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.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,t),p.appendChild(t);let w=null,f=()=>{w?.disconnect(),w=null},v=null,x=()=>{v=e?.launcher?.detachedPanel===!0?ov(e):null};x();let P=()=>{rv(a,l,p,d,c,e,u,v)},W=null,T=()=>{W?.(),W=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(W=ma(()=>{x(),P()}))},I=()=>{f(),un(e).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},H=!1,q=()=>{P(),I(),u&&!H&&a.dataset.personaDockMobileFullscreen!=="true"&&(H=!0,ev(a,un(e)))},U=a.ownerDocument.defaultView,$=()=>{q()};return U?.addEventListener("resize",$),un(e).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),q(),T(),{mode:"docked",host:c,shell:a,syncWidgetState(C){let j=C.launcherEnabled?C.open:!0;u!==j&&(u=j,q())},updateConfig(C){e=C,(e?.launcher?.enabled??!0)===!1&&(u=!0),x(),q(),T()},destroy(){U?.removeEventListener("resize",$),W?.(),W=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},pu=(t,e)=>Ft(e)?av(t,e):sv(t,e);var vs={desktop:{w:1280,h:800},mobile:{w:390,h:844}},uu=.15,fu=1.5,Ml="persona-preview-shell-theme",iv={load:()=>null,save:()=>{},clear:()=>{}},lv=["How do I get started?","Pricing & plans","Talk to support"];function El(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function cv(t){return t==="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 gu(t){let e=cv(t);return`* { box-sizing: border-box; }
|
|
112
135
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
113
|
-
html { color-scheme: ${
|
|
136
|
+
html { color-scheme: ${t}; }
|
|
114
137
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
115
138
|
.preview-iframe-mock { min-height: 100%; }
|
|
116
139
|
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
|
|
@@ -132,7 +155,7 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
132
155
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
133
156
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
134
157
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
135
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
158
|
+
.preview-workspace-card.short { height: 96px; }`}function mu(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Ml);o||(o=n.createElement("style"),o.id=Ml,n.head.appendChild(o)),o.textContent=gu(e)}var dv=`
|
|
136
159
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
137
160
|
<div class="preview-iframe-chrome">
|
|
138
161
|
<span class="preview-iframe-dot"></span>
|
|
@@ -151,7 +174,7 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
151
174
|
<div class="preview-iframe-line body"></div>
|
|
152
175
|
<div class="preview-iframe-line body"></div>
|
|
153
176
|
</div>
|
|
154
|
-
</div>`,
|
|
177
|
+
</div>`,pv=`
|
|
155
178
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
156
179
|
<div class="preview-iframe-line hero"></div>
|
|
157
180
|
<div class="preview-iframe-line body"></div>
|
|
@@ -164,9 +187,9 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
164
187
|
<div class="preview-workspace-card short"></div>
|
|
165
188
|
<div class="preview-workspace-card short"></div>
|
|
166
189
|
</div>
|
|
167
|
-
</div>`;function
|
|
168
|
-
${
|
|
169
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${
|
|
190
|
+
</div>`;function hu(t,e,n,o){let r=`
|
|
191
|
+
${dv}
|
|
192
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
170
193
|
<div class="preview-workspace-shell">
|
|
171
194
|
<div class="preview-workspace-topbar">
|
|
172
195
|
<div class="preview-workspace-topbar-left">
|
|
@@ -176,8 +199,8 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
176
199
|
<span class="preview-workspace-topbar-pill"></span>
|
|
177
200
|
</div>
|
|
178
201
|
<div class="preview-workspace-body">
|
|
179
|
-
<div id="preview-content-${
|
|
180
|
-
${
|
|
202
|
+
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
203
|
+
${pv}
|
|
181
204
|
</div>
|
|
182
205
|
</div>
|
|
183
206
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -185,16 +208,16 @@ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
185
208
|
<head>
|
|
186
209
|
<meta charset="UTF-8">
|
|
187
210
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
188
|
-
<link rel="stylesheet" href="${
|
|
189
|
-
<style id="${
|
|
211
|
+
<link rel="stylesheet" href="${El(o)}">
|
|
212
|
+
<style id="${Ml}">${gu(e)}</style>
|
|
190
213
|
</head>
|
|
191
214
|
<body>
|
|
192
|
-
${
|
|
215
|
+
${n?s:r}
|
|
193
216
|
</body>
|
|
194
|
-
</html>`}var
|
|
195
|
-
${
|
|
196
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
197
|
-
</div
|
|
217
|
+
</html>`}var uv=()=>[{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()}],fv=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function gv(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="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()}]:t==="conversation"&&fv(e)?[...uv(),...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 mv(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:lv:t.suggestionChips,initialMessages:gv(e,t,n),storageAdapter:iv};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function hv(t,e){let n=t.theme?Ro(t.theme,{validate:!1}):Ro();return{...dt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function mr(t,e){let n=t.scene??"conversation";return mv(hv(t,e),n,t.appendedMessages??[])}function yu(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:mr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:mr(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:mr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:mr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:mr(t,n),shellMode:n}]}function yv(t,e){let n={...e},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 T=getComputedStyle(t),I=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),H=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),q=40,U=(n.compareMode??"off")!=="off",$=(t.clientWidth-I-q)/(U?2:1),C=t.clientHeight-H-q;if($<=0||C<=0)return 1;let j=vs[c()]??vs.desktop;return Math.min($/j.w,C/j.h,1)}function f(){l=w();let T=Math.max(uu,Math.min(fu,u()));p=T;let I=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let H of I){let q=H.dataset.device??"desktop",U=vs[q]??vs.desktop;H.style.width=`${U.w*T}px`,H.style.height=`${U.h*T}px`,q==="mobile"&&(H.style.borderRadius=`${32*T}px`);let $=H.querySelector("iframe");$&&($.style.width=`${U.w}px`,$.style.height=`${U.h}px`,$.style.transformOrigin="top left",$.style.transition="none",$.style.transform=`scale(${T})`)}n.onScaleChange?.(T)}function v(){n.onBeforeDestroy?.();for(let T of o)T.destroy();for(let T of r)T();o=[],r=[]}function x(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function P(){if(a)return;v();let T=++d,I=yu(n),H=c(),q=(n.compareMode??"off")!=="off",U=(n.scene??"conversation")==="minimized",$=n.widgetCssPath??"/widget-dist/widget.css",C=n.buildSrcdoc??hu,j=H==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",J=Ce=>`<div class="${j}" data-mount-id="${Ce.mountId}" data-device="${H}" data-shell-mode="${Ce.shellMode}">
|
|
218
|
+
${q?`<div class="preview-frame-meta"><span class="preview-frame-label">${El(Ce.label)}</span></div>`:""}
|
|
219
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ce.mountId}"></iframe>
|
|
220
|
+
</div>`,D=q?`<div class="preview-compare-grid">${I.map(Ce=>`<div class="preview-compare-cell">${J(Ce)}</div>`).join("")}</div>`:`<div class="preview-single">${J(I[0])}</div>`;n.morphContainer?n.morphContainer(t,D):t.innerHTML=D,f();let _=x(),ce=0,he=_.length,Me=()=>{if(a||T!==d)return;for(let te of _){let ge=te.dataset.mountId;if(!ge||!te.contentDocument)continue;let Y=I.find(fe=>fe.mountId===ge);if(!Y)continue;let le=()=>{},Z=Ft(Y.config),be=Z?(()=>{let fe=te.contentDocument?.getElementById(`preview-content-${ge}`);if(!fe)return null;let Te=pu(fe,Y.config),Ae=te.contentDocument.createElement("div");Ae.id=ge,Ae.style.height="100%",Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1",Ae.style.minHeight="0",Te.host.appendChild(Ae);let ze=()=>Te.syncWidgetState(ve.getState()),Ne=le;return le=()=>{Te.destroy(),Ne()},Ae.__syncDock=ze,Ae.__hostLayout=Te,Ae})():te.contentDocument.getElementById(ge);if(!be)continue;let ve=au(be,Y.config);if(o.push(ve),Z&&be.__syncDock){let fe=be.__syncDock,Te=ve.on("widget:opened",fe),Ae=ve.on("widget:closed",fe),ze=le;le=()=>{Te(),Ae(),ze()},fe()}r.push(le),U&&ve.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let te of o)te.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
198
221
|
|
|
199
222
|
This is a preview of the artifact sidebar.
|
|
200
223
|
|
|
@@ -202,4 +225,4 @@ This is a preview of the artifact sidebar.
|
|
|
202
225
|
|
|
203
226
|
- Markdown rendering
|
|
204
227
|
- Document toolbar
|
|
205
|
-
- Resizable panes
|
|
228
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:_,controllers:[...o]})};for(let Ce of _){let te=Ce.dataset.mountId;if(!te)continue;let ge=I.find(Y=>Y.mountId===te);ge&&(Ce.addEventListener("load",()=>{ce++,ce>=he&&Me()},{once:!0}),Ce.srcdoc=C(te,ge.shellMode,Ft(ge.config),$))}he===0&&Me()}function W(){if(a)return;let T=yu(n);if(o.length!==T.length){P();return}if(T.some(H=>{let q=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${H.mountId}"]`);return!q||q.dataset.shellMode!==H.shellMode})){P();return}o.forEach((H,q)=>{H.update(T[q].config),(n.scene??"conversation")==="minimized"&&H.close()});for(let H of T){let q=t.querySelector(`iframe[data-mount-id="${H.mountId}"]`);q&&mu(q,H.shellMode)}n.onAfterUpdate?.({iframes:x(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(t)),P(),{update(T){if(a)return;let I=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},I?P():W()},destroy(){a||(a=!0,v(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return x()},getScale(){return p},setZoom(T){a||(n={...n,zoom:T},f())}}}export{yv as createThemePreview};
|