@runtypelabs/persona 4.14.0 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
- package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-QJ4LV2KW.js +1 -0
- package/dist/codegen.cjs +12 -11
- package/dist/codegen.js +14 -13
- package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
- package/dist/context-mentions.cjs +11 -8
- package/dist/context-mentions.d.cts +520 -21
- package/dist/context-mentions.d.ts +520 -21
- package/dist/context-mentions.js +11 -8
- package/dist/index.cjs +69 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +595 -46
- package/dist/index.d.ts +595 -46
- package/dist/index.global.js +60 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +69 -68
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +520 -21
- package/dist/smart-dom-reader.d.ts +520 -21
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +7 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +67 -67
- package/dist/theme-editor-preview.d.cts +534 -22
- package/dist/theme-editor-preview.d.ts +534 -22
- package/dist/theme-editor-preview.js +57 -57
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +521 -23
- package/dist/theme-editor.d.ts +521 -23
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +104 -3
- package/dist/theme-reference.d.ts +104 -3
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/ask-user-question-tool.ts +10 -7
- package/src/components/artifact-pane.test.ts +27 -0
- package/src/components/artifact-pane.ts +7 -3
- package/src/components/artifact-preview.ts +1 -1
- package/src/components/composer-parts.test.ts +103 -4
- package/src/components/composer-parts.ts +53 -15
- package/src/components/header-builder.ts +27 -2
- package/src/components/header-layouts.test.ts +56 -0
- package/src/components/header-layouts.ts +29 -9
- package/src/components/launcher-surface.test.ts +403 -0
- package/src/components/launcher.ts +297 -2
- package/src/components/messages.ts +5 -2
- package/src/components/panel.ts +92 -71
- package/src/components/pill-composer-builder.test.ts +18 -0
- package/src/components/suggestions.test.ts +273 -0
- package/src/components/suggestions.ts +528 -86
- package/src/components/welcome.test.ts +121 -0
- package/src/components/welcome.ts +305 -0
- package/src/components/widget-view.test.ts +5 -3
- package/src/components/widget-view.ts +18 -7
- package/src/defaults.ts +7 -5
- package/src/generated/runtype-openapi-contract.ts +17 -0
- package/src/index-core.ts +29 -2
- package/src/launcher-global.ts +11 -8
- package/src/plugins/types.ts +136 -3
- package/src/presets.ts +3 -3
- package/src/session.ts +10 -8
- package/src/styles/widget-styles.test.ts +382 -0
- package/src/styles/widget.css +778 -4
- package/src/suggest-replies-tool.test.ts +233 -2
- package/src/suggest-replies-tool.ts +115 -39
- package/src/testing/mock-stream.test.ts +19 -0
- package/src/testing/mock-stream.ts +20 -0
- package/src/theme-editor/preview-utils.test.ts +34 -0
- package/src/theme-editor/preview-utils.ts +77 -2
- package/src/theme-editor/sections.test.ts +33 -0
- package/src/theme-editor/sections.ts +83 -6
- package/src/theme-reference.ts +34 -5
- package/src/types/theme.ts +72 -3
- package/src/types.ts +312 -18
- package/src/ui.body-top-slot.test.ts +95 -0
- package/src/ui.content-width.test.ts +91 -0
- package/src/ui.detached-panel.test.ts +1 -1
- package/src/ui.docked.test.ts +7 -4
- package/src/ui.launcher-teaser.test.ts +162 -0
- package/src/ui.rebuild-composer.test.ts +491 -0
- package/src/ui.render-welcome.test.ts +505 -0
- package/src/ui.scroll-additive.test.ts +91 -21
- package/src/ui.scroll.test.ts +302 -14
- package/src/ui.suggest-replies.test.ts +1112 -1
- package/src/ui.ts +1008 -149
- package/src/ui.welcome.test.ts +504 -0
- package/src/utils/artifact-file.test.ts +1 -1
- package/src/utils/artifact-gate.test.ts +27 -0
- package/src/utils/artifact-gate.ts +9 -0
- package/src/utils/attachment-manager.test.ts +37 -0
- package/src/utils/attachment-manager.ts +15 -0
- package/src/utils/auto-follow.test.ts +23 -0
- package/src/utils/auto-follow.ts +11 -1
- package/src/utils/code-generators.test.ts +40 -0
- package/src/utils/code-generators.ts +22 -0
- package/src/utils/config-merge.test.ts +24 -0
- package/src/utils/config-merge.ts +2 -0
- package/src/utils/content-width.test.ts +37 -0
- package/src/utils/content-width.ts +17 -0
- package/src/utils/icons.test.ts +26 -0
- package/src/utils/icons.ts +8 -0
- package/src/utils/plugin-storage.test.ts +94 -0
- package/src/utils/plugin-storage.ts +98 -0
- package/src/utils/theme.test.ts +216 -0
- package/src/utils/tokens.ts +113 -3
- package/src/welcome.test.ts +213 -0
- package/src/welcome.ts +130 -0
- package/dist/chunk-MMUPR2JW.js +0 -1
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!
|
|
3
|
-
`):e};var
|
|
1
|
+
import{a as Mp}from"./chunk-5EIIHQLQ.js";import{a as b,b as Tp,c as Ee,d as Pn,e as ae,f as Lp,h as Pp,i as Ip}from"./chunk-QJ4LV2KW.js";import{a as Ep,b as kp}from"./chunk-IO5VVUKP.js";var xr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(f=>(r=f,f)).catch(f=>{throw s=null,f}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:$w,load:Nm,provide:Uw,getSync:Ll}=xr({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),Ra=new Set,_m=()=>{let e=[...Ra];Ra.clear();for(let t of e)try{t()}catch{}};var $m=()=>{let e=Ll();return e?Promise.resolve(e):Nm().then(t=>(_m(),t))},Ha=e=>Ll()?()=>{}:(Ra.add(e),$m().catch(()=>{}),()=>{Ra.delete(e)});var Gn=Ll;var Um=e=>{if(e)return e},Pl=e=>{let t=null;return n=>{let o=Gn();if(!o)return mo(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Um(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Ba=e=>e?Pl({markedOptions:e.options,renderer:e.renderer}):Pl(),Vw=Pl();var mo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var zm={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"]},jm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Vm=()=>{let e=null;return t=>{let n=Gn();if(!n)return mo(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!jm.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,zm)}},Da=e=>e===!1?null:typeof e=="function"?e:Vm();var Wp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Rp=e=>e.includes("|"),Hp=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},qm=e=>`| ${e.join(" | ")} |`,Km=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Gm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Bp=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Rp(r)||Wp.test(r)||!Wp.test(s))continue;let a=Hp(r).length;if(a<1)continue;let l=Km(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let u=o+2;for(;u<t.length;u++){let d=t[u];if(d.trim()===""||!Rp(d))break;let c=qm(Gm(Hp(d),a));t[u]!==c&&(t[u]=c,n=!0)}o=u-1}return n?t.join(`
|
|
3
|
+
`):e};var Dp="var(--persona-md-table-scroll-fade, 24px)",Fp=new WeakSet;function Np(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Op(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Dp),e.style.setProperty("--persona-fade-r",r<=1?"0px":Dp)}function Il(e){Fp.has(e)||(Fp.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Op(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Op)}var Yn="webmcp:",Wl=new Map,_p=e=>{Wl.clear();for(let t of e){let n=t.title?.trim();n&&Wl.set(t.name,n)}},ws=e=>Wl.get(jp(e)),Fa={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$p=null;function zp(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${Ym(t.join(""))}`}function Up(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Ym(e){let t=Up(e,0).toString(36),n=Up(e,2654435761).toString(36);return`${t}.${n}`}var Oa=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Fa.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}_p(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=Qm(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return In("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return In(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=jp(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return In(`Failed to read WebMCP registry: ${C}`)}_p(a);let l=a.find(v=>v.name===s);if(!l)return In(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return In(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return In("Aborted by cancel()");let u=ws(s),d={toolName:s,args:n,description:l.description,...u?{title:u}:{},reason:"gate"};if(!await this.requestConfirm(d))return In("User declined the tool call.");if(o?.aborted)return In("Aborted by cancel()");let c=new AbortController,f=!1,w=setTimeout(()=>{f=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let v=await r.executeTool(l,th(n),{signal:c.signal});return Jm(v)}catch(v){if(f)return In(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return In("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return In(C)}finally{clearTimeout(w),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}($p?await $p():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Fa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Fa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??Zm;try{return await n(t)}catch(o){return Fa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Xm(t,o))}},jp=e=>e.startsWith(Yn)?e.slice(Yn.length):e,Cr=e=>e.startsWith(Yn),Xm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Qm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Jm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:nh(t)}]}},In=e=>({isError:!0,content:[{type:"text",text:e}]}),Zm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=eh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
6
|
${t}`:"")+(e.description?`
|
|
7
7
|
|
|
8
|
-
${e.description}`:"");return window.confirm(n)},mg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},hg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},yg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function un(e){return e==="card"?"collapsed":e}function er(e){return e.split(";",1)[0].trim().toLowerCase()}function bg(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(er(r)===t)return{mode:un(s),selector:er(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(er(r)===o)return{mode:un(s),selector:o}}function vg(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:un(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?er(t.file.mimeType):void 0,p=l?bg(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:un(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:un(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:un(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:un(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:un(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ro(e,t){return vg(e,t).mode}function Qr(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var wg="agent_",xg="flow_";function kd(e){return e.startsWith(wg)?{kind:"agentId",agentId:e}:e.startsWith(xg)?{kind:"flowId",flowId:e}:null}function Ld(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=kd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=kd(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Cg,ARR as Ag,OBJ as Sg,STR as Tg}from"partial-json";var Ui="ask_user_question",Xr=8,tr="data-persona-ask-sheet-for",Mg="Other",Eg="Other\u2026",Id="Type your own answer here",Rd="Send",kg="Next",Lg="Back",Pg="Submit all",Ig="Skip",Rg=3,Vi="data-ask-current-index",qi="data-ask-question-count",Wd="data-ask-answers",Ki="data-ask-grouped",Hd="data-ask-layout",Wg=e=>e.layout==="pills"?"pills":"rows",Hg=e=>e.getAttribute(Hd)==="pills"?"pills":"rows",Pd=!1,Bd=e=>e.replace(/["\\]/g,"\\$&"),Lo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ui,Gi=e=>e?.features?.askUserQuestion??{},nr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Cg(r,Tg|Sg|Ag);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Jr=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Xr&&!Pd&&(Pd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Xr}.`)),t.slice(0,Xr)},Bg=e=>Jr(e)[0]??null,Dg=(e,t)=>Jr(e)[t]??null,Fg=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Dd=(e,t,n)=>{if(e!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ng=(e,t,n,o)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=h("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Dd(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Og=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},_g=(e,t,n,o)=>{let s=h("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Rg;c++)s.appendChild(Og(o));return s}if(p.forEach((c,u)=>{s.appendChild(Ng(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Mg:Eg;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=h("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Id,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let v=Dd(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},Fd=(e,t)=>{let o=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Id,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Rd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},$g=e=>{let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Rd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},zg=(e,t,n)=>{let o=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Lg,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ig,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Pg:n.nextLabel??kg,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=e=>{let t=e.getAttribute(Wd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Nd=(e,t)=>{e.setAttribute(Wd,JSON.stringify(t))},fn=e=>{let t=Number(e.getAttribute(Vi)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},jg=(e,t)=>{e.setAttribute(Vi,String(Math.max(0,Math.floor(t))))},or=e=>{let t=Number(e.getAttribute(qi)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(Ki)==="true",Ug=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Vg=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},fa=(e,t)=>{let{payload:n}=nr(t),o=Jr(n),r=Po(e),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Od=e=>{let t=Po(e),n=fn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},_d=e=>{if(!so(e))return;let t=Po(e),n=fn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Qi=(e,t,n)=>{let o=Gi(n),r=Hg(e),{payload:s,complete:a}=nr(t),l=so(e),p=fn(e),d=or(e),c=l?Dg(s,p):Bg(s),u=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof c?.question=="string"?c.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let L=_g(c,o,a,r);C.replaceWith(L)}if(r!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Fd(o,r))}let R=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!R?e.appendChild($g(o)):(!u||l)&&R&&R.remove(),e.setAttribute("data-multi-select",u?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let L=zg(p,d,o);B?B.replaceWith(L):e.appendChild(L)}else B&&B.remove();Od(e),_d(e)},qg=(e,t,n)=>{let o=Gi(t),r=Wg(o),s=e.toolCall.id,a=Jr(n),l=Math.max(1,a.length),p=l>1,d=Ug(e,a),c=p?Vg(e,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(tr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(qi,String(l)),u.setAttribute(Vi,String(c)),u.setAttribute(Ki,p?"true":"false"),u.setAttribute(Hd,r),Nd(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Fg(u,o);let w=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let R=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return R.setAttribute("data-ask-pill-list","true"),R.setAttribute("role","group"),u.appendChild(R),r!=="rows"&&u.appendChild(Fd(o,r)),Qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Kg=(e,t,n)=>{let{payload:o}=nr(t),r=Math.max(1,Jr(o).length);r>or(e)&&(e.setAttribute(qi,String(r)),r>1&&!so(e)&&e.setAttribute(Ki,"true")),Qi(e,t,n)};var ga=(e,t,n)=>{if(!n||!Lo(e)||Gi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${tr}]`).forEach(d=>{d.getAttribute(tr)!==r&&d.remove()});let a=n.querySelector(`[${tr}="${Bd(r)}"]`);if(a){Kg(a,e,t);return}let{payload:l}=nr(e),p=qg(e,t,l);n.appendChild(p)},rr=(e,t)=>{if(!e)return;let n=t?`[${tr}="${Bd(t)}"]`:`[${tr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Xi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=Po(e),o=fn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Nd(e,n),Od(e),_d(e)},ma=(e,t,n,o)=>{let r=or(e),s=Math.max(0,Math.min(r-1,o));jg(e,s),Qi(e,t,n)};var On="suggest_replies";var Gg={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},$d={name:On,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Gg,origin:"sdk",annotations:{readOnlyHint:!0}},Ji=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Yi=e=>e.variant==="tool"&&e.toolCall?.name===On,Qg=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},zd=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Yi(n))continue;let o=Qg(n.toolCall?.args);return o.length>0?o:null}return null},jd=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Xg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Xr,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Jg={name:Ui,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Xg,origin:"sdk",annotations:{readOnlyHint:!0}},ha=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Jg),jd(e)&&t.push($d),t};import{parse as Yg,STR as Zg,OBJ as em}from"partial-json";var Ud=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function yn(e){return e==="card"?"collapsed":e}function Ar(e){return e.split(";",1)[0].trim().toLowerCase()}function oh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ar(r)===t)return{mode:yn(s),selector:Ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ar(r)===o)return{mode:yn(s),selector:o}}function rh(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ar(t.file.mimeType):void 0,u=l?oh(o.files.byMediaType,l):void 0;if(l&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:l,selector:u.selector}};if(o.files.default)return{mode:yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:yn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ho(e,t){return rh(e,t).mode}function xs(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var sh="agent_",ah="flow_";function Vp(e){return e.startsWith(sh)?{kind:"agentId",agentId:e}:e.startsWith(ah)?{kind:"flowId",flowId:e}:null}function qp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=Vp(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[a];if(!u)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:u(l).payload}}let r=Vp(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as ih,ARR as lh,OBJ as ch,STR as dh}from"partial-json";var Rl="ask_user_question",Cs=8,Sr="data-persona-ask-sheet-for",ph="Other",uh="Other\u2026",Gp="Type your own answer here",Yp="Send",fh="Next",gh="Back",mh="Submit all",hh="Skip",yh=3,Hl="data-ask-current-index",Bl="data-ask-question-count",Xp="data-ask-answers",Dl="data-ask-grouped",Qp="data-ask-layout",bh=e=>e.layout==="pills"?"pills":"rows",vh=e=>e.getAttribute(Qp)==="pills"?"pills":"rows",Kp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Rl,Fl=e=>e?.features?.askUserQuestion??{},Tr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=ih(r,dh|ch|lh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},As=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Cs&&!Kp&&(Kp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},wh=e=>As(e)[0]??null,xh=(e,t)=>As(e)[t]??null,Ch=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Zp=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=b("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let u=Zp(n,o,t);u&&s.appendChild(u)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Th=(e,t,n,o)=>{let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,u=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(u.length===0&&!n){for(let c=0;c<yh;c++)s.appendChild(Sh(o));return s}if(u.forEach((c,f)=>{s.appendChild(Ah(c,f,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ph:uh;if(o==="rows"){let f=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(u.length)),f.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Gp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),f.appendChild(w);let v=Zp(o,a,u.length);v&&f.appendChild(v),s.appendChild(f)}else{let f=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,s.appendChild(f)}}return s},eu=(e,t)=>{let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Gp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=b("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Yp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Yp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Eh=(e,t,n)=>{let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);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=n.skipLabel??hh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let u=e===t-1;return l.textContent=u?n.submitAllLabel??mh:n.nextLabel??fh,l.setAttribute("data-ask-user-action",u?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(Xp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(e,t)=>{e.setAttribute(Xp,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(Hl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Bl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Dl)==="true",Lh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ph=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=Tr(t),o=As(n),r=Ko(e),s={},a=new Set;return o.forEach((l,u)=>{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,u)&&(s[d]=r[u]))}),s},nu=e=>{let t=Ko(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(u=>r.add(u));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(u=>{let d=u.getAttribute("data-option-label")??"",c=r.has(d);u.setAttribute("aria-pressed",c?"true":"false"),u.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(u=>u.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ou=e=>{if(!yo(e))return;let t=Ko(e),n=bn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ol=(e,t,n)=>{let o=Fl(n),r=vh(e),{payload:s,complete:a}=Tr(t),l=yo(e),u=bn(e),d=Mr(e),c=l?xh(s,u):wh(s),f=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${u+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let S=typeof c?.question=="string"?c.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=Th(c,o,a,r);C.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(eu(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(Mh(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=Eh(u,d,o);B?B.replaceWith(S):e.appendChild(S)}else B&&B.remove();nu(e),ou(e)},Ih=(e,t,n)=>{let o=Fl(t),r=bh(o),s=e.toolCall.id,a=As(n),l=Math.max(1,a.length),u=l>1,d=Lh(e,a),c=u?Ph(e,l):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sr,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(Bl,String(l)),f.setAttribute(Hl,String(c)),f.setAttribute(Dl,u?"true":"false"),f.setAttribute(Qp,r),tu(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(f,o);let w=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),f.appendChild(w);let T=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(eu(o,r)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wh=(e,t,n)=>{let{payload:o}=Tr(t),r=Math.max(1,As(o).length);r>Mr(e)&&(e.setAttribute(Bl,String(r)),r>1&&!yo(e)&&e.setAttribute(Dl,"true")),Ol(e,t,n)};var _a=(e,t,n)=>{if(!n||!qo(e)||Fl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Wh(a,e,t);return}let{payload:l}=Tr(e),u=Ih(e,t,l);n.appendChild(u)},Er=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Nl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),bo=(e,t)=>{let n=Ko(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tu(e,n),nu(e),ou(e)},$a=(e,t,n,o)=>{let r=Mr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Ol(e,t,n)};var Xn="suggest_replies";var Rh={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},su={name:Xn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>e.variant==="tool"&&e.toolCall?.name===Xn,Hh=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},au=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ss(n))continue;let o=Hh(n.toolCall?.args);return o.length>0?o:null}return null},ru=new Set,Bh=(e,t,n)=>{let o=`${e}:${t}:${n}`;ru.has(o)||(ru.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},vo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],u=n?.[a];l===void 0||u===void 0||l!==u&&Bh(a,u,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Dh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,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},Fh={name:Rl,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:Dh,origin:"sdk",annotations:{readOnlyHint:!0}},Ua=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fh),vo(e).expose&&t.push(su),t};import{parse as Oh,STR as Nh,OBJ as _h}from"partial-json";var iu=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},$h=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},lu=e=>e.status==="complete"?$h(e):e.status==="pending"?"Waiting":"",Uh=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var cu=e=>e.status==="complete"?Uh(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ms=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},ja=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},$l=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ms(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ts(o,n.slice(s,a.index),[]),a[1]!==void 0?Ts(o,a[1],["bold"]):a[2]!==void 0?Ts(o,a[2],["italic"]):a[3]!==void 0&&Ts(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ts(o,n.slice(s),[]),o},Ts=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},zh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Kd=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gd=()=>{let e=om();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Qd=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Yg(n,Zg|em);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ud(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ud(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Xd=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Jd="4.14.0";var ts=Jd;var sm="https://api.runtype.com/v1/dispatch",wa="https://api.runtype.com";function am(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function im(e){switch(e){case"json":return Qd;case"regex-json":return Gd;case"xml":return Xd;default:return Kd}}var Yd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function lm(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Yd(n);if(!Yd(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=es(e);return es(t)!==null&&a===null?t:e}var ns=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??sm,this.headers={"Content-Type":"application/json","X-Persona-Version":ts,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??im(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new ua(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ld(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(el).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ts},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||wa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Md(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||wa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let f={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(el).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...ha(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=S=>{let D=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,y=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,P=S.tools?S.tools.map(T=>({...T,chunks:T.chunks?[...T.chunks]:void 0})):void 0;return{...S,reasoning:D,toolCall:y,tools:P}},w=S=>{if(S.role!=="assistant"||S.variant)return!0;let D=Array.isArray(S.contentParts)&&S.contentParts.length>0,y=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||D||y||!!S.stopReason},f=S=>{w(S)&&n({type:"message",message:u(S)})},v=null,C=null,R={current:null},B={current:null},L=null,E="",M=new Map,_=new Map,G=new Map,x=new Map,j=new Map,U={lastId:null,byStep:new Map},oe={lastId:null,byCall:new Map},F=S=>{if(S==null)return null;try{return String(S)}catch{return null}},$=S=>F(S.stepId??S.step_id??S.step??S.parentId??S.flowStepId??S.flow_step_id),X=S=>F(S.callId??S.call_id??S.requestId??S.request_id??S.toolCallId??S.tool_call_id??S.stepId??S.step_id),me=o,he=!1,Ae=()=>{if(v)return v;let S,D="",y=L;return!he&&me?(S=me,he=!0,D=r??""):me&&y?S=`${me}_${y}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:S,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(v),v},Z=(S,D)=>{U.lastId=D,S&&U.byStep.set(S,D)},ce=(S,D)=>{let y=S.reasoningId??S.id,P=$(S);if(y){let I=String(y);return Z(P,I),I}if(P){let I=U.byStep.get(P);if(I)return U.lastId=I,I}if(U.lastId&&!D)return U.lastId;if(!D)return null;let T=`reason-${c()}`;return Z(P,T),T},ee=S=>{let D=x.get(S);if(D)return D;let y={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return x.set(S,y),f(y),y},le=(S,D)=>{oe.lastId=D,S&&oe.byCall.set(S,D)},Y=new Set,pe=new Map,xe=new Set,ye=new Map,ve=S=>{if(!S)return!1;let D=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return D==="emit_artifact_markdown"||D==="emit_artifact_component"},je=(S,D)=>{let y=S.toolId??S.id,P=X(S);if(y){let I=String(y);return le(P,I),I}if(P){let I=oe.byCall.get(P);if(I)return oe.lastId=I,I}if(oe.lastId&&!D)return oe.lastId;if(!D)return null;let T=`tool-${c()}`;return le(P,T),T},Me=S=>{let D=j.get(S);if(D)return D;let y={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return j.set(S,y),f(y),y},De=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let D=Number(S);if(!Number.isNaN(D)&&Number.isFinite(D))return D;let y=Date.parse(S);if(!Number.isNaN(y))return y}return Date.now()},Qe=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},Ve=new Map,Te=new Map,Le=new Map,Xe=(S,D,y)=>{let P=Le.get(S);P||(P=[],Le.set(S,P));let T=0,I=P.length;for(;T<I;){let H=T+I>>>1;P[H].seq<D?T=H+1:I=H}P[T]?.seq===D?P[T]={seq:D,text:y}:P.splice(T,0,{seq:D,text:y});let q="";for(let H=0;H<P.length;H++)q+=P[H].text;return q},Ht=(S,D)=>{let y=Qe(D),P=Te.get(S.id),T=lm(P,y);S.rawContent=T;let I=Ve.get(S.id),q=Re=>{let Je=S.content??"";Re.trim()!==""&&(Je.trim().length===0||Re.startsWith(Je)||Re.trimStart().startsWith(Je.trim()))&&(S.content=Re)},H=()=>{if(I){let Re=I.close?.();Re instanceof Promise&&Re.catch(()=>{})}Ve.delete(S.id),Te.delete(S.id),S.streaming=!1,f(S)};if(!I){q(y),H();return}let z=es(T);if(z!==null&&z.trim()!==""){q(z),H();return}let J=Re=>{let Je=typeof Re=="string"?Re:Re?.text??null;if(Je!==null&&Je.trim()!=="")return Je;let rt=I.getExtractedText();return rt!==null&&rt.trim()!==""?rt:y},qe;try{qe=I.processChunk(T)}catch{q(y),H();return}if(qe instanceof Promise){qe.then(Re=>{q(J(Re)),H()}).catch(()=>{q(y),H()});return}q(J(qe)),H()},It=null,qt=(S,D,y,P)=>{S.rawContent=D,Ve.has(S.id)||Ve.set(S.id,this.createStreamParser());let T=Ve.get(S.id),I=D.trim().startsWith("{")||D.trim().startsWith("[");if(I&&Te.set(S.id,D),T.__isPlainTextParser===!0){S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S);return}let H=T.processChunk(D);if(H instanceof Promise)H.then(z=>{let J=typeof z=="string"?z:z?.text??null;J!==null&&J.trim()!==""?(S.content=J,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}).catch(()=>{S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S)});else{let z=typeof H=="string"?H:H?.text??null;z!==null&&z.trim()!==""?(S.content=z,f(S)):!I&&!D.trim().startsWith("<")&&(S.content=P!==void 0?D:S.content+y,Te.delete(S.id),Ve.delete(S.id),S.rawContent=void 0,f(S))}},xt=(S,D)=>{let y=D??S.content;if(y==null||y===""){S.streaming=!1,f(S);return}let T=Te.get(S.id)??Qe(y);S.rawContent=T;let I=Ve.get(S.id),q=null,H=!1;if(I&&(q=I.getExtractedText(),q===null&&(q=es(T)),q===null)){let z=I.processChunk(T);z instanceof Promise?(H=!0,z.then(J=>{let qe=typeof J=="string"?J:J?.text??null;qe!==null&&(S.content=qe,S.streaming=!1,Ve.delete(S.id),Te.delete(S.id),f(S))}).catch(()=>{})):q=typeof z=="string"?z:z?.text??null}if(!H){q!==null&&q.trim()!==""?S.content=q:Te.has(S.id)||(S.content=Qe(y));let z=Ve.get(S.id);if(z){let J=z.close?.();J instanceof Promise&&J.catch(()=>{}),Ve.delete(S.id)}Te.delete(S.id),S.streaming=!1,f(S)}},He=(S,D,y)=>{let P=_.get(S);if(P)return P;let T={id:`nested-${D}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:D}};return _.set(S,T),f(T),T},de=[],et,Ie=new Map,fe=0,se="agent",Pe=!1,it=null,ue=null,Ce=new Map,te=this.config.iterationDisplay??"separate";for(et=()=>{for(let S=0;S<de.length;S++){let D=de[S].payloadType,y=de[S].payload;if(!Pe&&se!=="flow"&&typeof y.stepType=="string"&&(se="flow"),D==="reasoning_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T),He(P,T,"reasoning");continue}let I=ce(y,!0)??`reason-${c()}`,q=ee(I);q.reasoning=q.reasoning??{id:I,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??De(y.startedAt??y.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),q.streaming=!0,q.reasoning.status="streaming",f(q)}else if(D==="reasoning_delta"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let H=_.get(P),z=y.reasoningText??y.text??y.delta??"";z&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(z)),f(H));continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=ee(T);I.reasoning=I.reasoning??{id:T,status:"streaming",chunks:[]},I.reasoning.startedAt=I.reasoning.startedAt??De(y.startedAt??y.timestamp);let q=y.reasoningText??y.text??y.delta??"";if(q&&y.hidden!==!0){let H=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(H!==void 0){let z=Xe(T,H,String(q));I.reasoning.chunks=[z]}else I.reasoning.chunks.push(String(q))}if(I.reasoning.status=y.done?"complete":"streaming",y.done){I.reasoning.completedAt=De(y.completedAt??y.timestamp);let H=I.reasoning.startedAt??Date.now();I.reasoning.durationMs=Math.max(0,(I.reasoning.completedAt??Date.now())-H)}I.streaming=I.reasoning.status!=="complete",f(I)}else if(D==="reasoning_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)&&_.has(P)){let z=_.get(P);if(z.reasoning){let J=typeof y.text=="string"?y.text:"";J&&z.reasoning.chunks.length===0&&z.reasoning.chunks.push(J),z.reasoning.status="complete",z.streaming=!1,f(z)}M.delete(P),_.delete(P);continue}let T=ce(y,!1)??ce(y,!0)??`reason-${c()}`,I=typeof y.text=="string"?y.text:"";!x.get(T)&&(I||y.scope==="loop")&&ee(T);let q=x.get(T);if(q?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(q.reasoning.scope=y.scope),I&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(I),q.reasoning.status="complete",q.reasoning.completedAt=De(y.completedAt??y.timestamp);let z=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-z),q.streaming=!1,f(q)}let H=$(y);H&&U.byStep.delete(H)}else if(D==="tool_start"){v&&(v.streaming=!1,f(v),v=null),typeof y.iteration=="number"&&(fe=y.iteration);let P=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??je(y,!0)??`tool-${c()}`,T=y.toolName??y.name;if(ve(T)){Y.add(P);continue}le(X(y),P);let I=Me(P),q=I.toolCall??{id:P,status:"pending"};q.name=T??q.name,q.status="running",y.parameters!==void 0?q.args=y.parameters:y.args!==void 0&&(q.args=y.args),q.startedAt=q.startedAt??De(y.startedAt??y.timestamp),q.completedAt=void 0,q.durationMs=void 0,I.toolCall=q,I.streaming=!0,y.executionId&&(I.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(I)}else if(D==="tool_output_delta"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P))continue;let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.startedAt=I.startedAt??De(y.startedAt??y.timestamp);let q=y.text??y.delta??y.message??"";q&&(I.chunks=I.chunks??[],I.chunks.push(String(q))),I.status="running",T.toolCall=I,T.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T)}else if(D==="tool_complete"){let P=je(y,!1)??je(y,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let T=Me(P),I=T.toolCall??{id:P,status:"running"};I.status="complete",y.result!==void 0&&(I.result=y.result),typeof y.duration=="number"&&(I.duration=y.duration),I.completedAt=De(y.completedAt??y.timestamp);let q=y.duration??y.executionTime;if(typeof q=="number")I.durationMs=q;else{let J=I.startedAt??Date.now();I.durationMs=Math.max(0,(I.completedAt??Date.now())-J)}T.toolCall=I,T.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(T.agentMetadata=T.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(T);let z=X(y);z&&oe.byCall.delete(z)}else if(D==="await"&&y.toolName){let P=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,T=P??y.toolId??`local-${c()}`,I=Me(T),q=y.toolName,H=y.origin==="webmcp"&&!Zo(q)?`webmcp:${q}`:q,z=Zo(H),J=I.toolCall??{id:T,status:"pending"};J.name=H,J.args=y.parameters,J.status=z?"running":"complete",J.chunks=J.chunks??[],J.startedAt=J.startedAt??De(y.startedAt??y.timestamp??y.awaitedAt),z?(J.completedAt=void 0,J.duration=void 0,J.durationMs=void 0):J.completedAt=J.completedAt??J.startedAt,I.toolCall=J,I.streaming=!1,I.agentMetadata={...I.agentMetadata,executionId:y.executionId??I.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(I)}else if(D==="text_start"){let P=typeof y.id=="string"?y.id:null,T=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(P&&T){M.set(P,T);continue}let I=v;I&&(se==="flow"?(xt(I),It=I):(I.streaming=!1,f(I)),v=null),L=typeof y.id=="string"?y.id:L,E=""}else if(D==="text_delta"){let P=typeof y.id=="string"?y.id:null,T=P?M.get(P):void 0;if(P&&T){let q=typeof y.delta=="string"?y.delta:"",H=(G.get(P)??"")+q;if(G.set(P,H),H.trim()==="")continue;let z=He(P,T);z.agentMetadata={...z.agentMetadata,executionId:y.executionId,parentToolId:T},qt(z,H,q,void 0);continue}if(L=typeof y.id=="string"?y.id:L,se==="flow"){let q=typeof y.delta=="string"?y.delta:"";if(E+=q,E.trim()==="")continue;let H=Ae();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},qt(H,E,q,void 0),C=H;continue}let I=Ae();I.content+=y.delta??"",I.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:it??void 0,agentName:ue?.agentName},C=I,f(I)}else if(D==="text_complete"){let P=typeof y.id=="string"?y.id:null;if(P&&M.has(P)){let I=_.get(P);I&&xt(I),M.delete(P),G.delete(P),_.delete(P);continue}let T=v;T&&(se==="flow"?(xt(T),It=T):((T.content??"")===""&&typeof y.text=="string"&&(T.content=y.text),T.streaming=!1,f(T)),v=null),L=null,E=""}else if(D==="step_complete"){let P=y.stepType,T=y.executionType;if(P==="tool"||T==="context")continue;if(y.success===!1){let I=y.error,q=typeof I=="string"&&I!==""?I:I!=null&&typeof I=="object"&&Reflect.has(I,"message")?String(I.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let H=v;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let I=It;It=null;let q=y.stopReason,H=y.result?.response;if(I)q&&(I.stopReason=q),H!=null?Ht(I,H):I.streaming!==!1&&(Ve.delete(I.id),Te.delete(I.id),I.streaming=!1,f(I));else{let z=H!=null&&H!=="";if(z||q){let J=Ae();q&&(J.stopReason=q),z?xt(J,H):(J.streaming=!1,f(J))}}continue}}else if(D==="execution_start")se=y.kind==="flow"?"flow":"agent",Pe=!0,se==="agent"&&(ue={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:De(y.startedAt)});else if(D==="turn_start"){let P=typeof y.iteration=="number"?y.iteration:fe;if(P!==fe){if(ue&&(ue.currentIteration=P),te==="separate"&&P>1){let T=v;T&&(T.streaming=!1,f(T),Ce.set(P-1,T),v=null)}fe=P}it=typeof y.id=="string"?y.id:null,C=null}else if(D==="tool_input_delta"){let P=y.toolCallId??oe.lastId;if(P){let T=j.get(P);T?.toolCall&&(T.toolCall.chunks=T.toolCall.chunks??[],T.toolCall.chunks.push(y.delta??""),f(T))}}else{if(D==="tool_input_complete")continue;if(D==="turn_complete"){let P=y.stopReason,T=v??C;if(P&&T!==null){let I=y.id;(!I||T.agentMetadata?.turnId===I)&&(T.stopReason=P,f(T))}it===y.id&&(it=null)}else if(D==="media_start"){let P=String(y.id);Ie.set(P,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(D==="media_delta"){let P=Ie.get(String(y.id));P&&typeof y.delta=="string"&&P.parts.push(y.delta)}else if(D==="media_complete"){let P=String(y.id),T=Ie.get(P);Ie.delete(P);let I=(typeof y.mediaType=="string"?y.mediaType:void 0)??T?.mediaType??"application/octet-stream",q=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:T&&T.parts.length>0?T.parts.join(""):void 0,z=null;if(q)z={type:"media",data:q,mediaType:I};else if(H){let Je=I.toLowerCase();z={type:Je==="image"||Je.startsWith("image/")?"image-url":"file-url",url:H,mediaType:I}}let J=y.toolCallId??T?.toolCallId,qe=z?[z]:[],Re=[];for(let Je of qe){if(!Je||typeof Je!="object")continue;let rt=Je,V=typeof rt.type=="string"?rt.type:void 0,_e=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",be=null,$e="";if(V==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;$e=_e.length>0?_e:"application/octet-stream",be=`data:${$e};base64,${Fe}`}else if(V==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else if(V==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;$e=_e,be=Fe}else continue;if(be)if(V==="image-url"||$e.startsWith("image/"))Re.push({type:"image",image:be,...$e.includes("/")?{mimeType:$e}:{}});else if($e.startsWith("audio/"))Re.push({type:"audio",audio:be,mimeType:$e});else if($e.startsWith("video/"))Re.push({type:"video",video:be,mimeType:$e});else{let Fe=$e||"application/octet-stream";Re.push({type:"file",data:be,mimeType:Fe,filename:am(Fe)})}}if(Re.length>0){let Je=c(),rt=J,_e={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Je}`:String(Je)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Je,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:fe}};f(_e);let be=v;be&&(be.streaming=!1,f(be)),v=null,R.current=null}}else if(D==="execution_complete"){let P=y.kind??se;P==="agent"&&ue&&(ue.status=y.success?"complete":"error",ue.completedAt=De(y.completedAt),ue.stopReason=y.stopReason);let T=v;T&&(P==="flow"&&T.streaming!==!1?xt(T):(T.streaming=!1,f(T)),v=null),L=null,E="",It=null,n({type:"status",status:"idle",terminal:!0})}else if(D==="execution_error"){let P=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(D!=="ping"){if(D==="approval_start"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(T)}else if(D==="step_await"&&y.awaitReason==="approval_required"){let P=y.approvalId??`approval-${c()}`,T={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(T)}else if(D==="approval_complete"){let P=y.approvalId;if(P){let I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:y.decision??"approved",agentId:ue?.agentId??"virtual",executionId:y.executionId??ue?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(I)}}else if(D==="artifact_start"||D==="artifact_delta"||D==="artifact_update"||D==="artifact_complete"){if(D==="artifact_start"){let P=y.artifactType,T=String(y.id),I=typeof y.title=="string"?y.title:void 0,q=y.file,H;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&(H={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:T,artifactType:P,title:I,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let z=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ye.set(T,{markdown:"",title:I,file:H,...z?{props:z}:{}}),!xe.has(T)){xe.add(T);let J=ro(this.config.features?.artifacts,{artifactType:P,...H?{file:H}:{}}),qe=typeof y.component=="string"?y.component:void 0,Re={id:`artifact-ref-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Qr(J,{artifactId:T,title:I,artifactType:P,status:"streaming",...H?{file:H}:{},...qe?{component:qe}:{}})};pe.set(T,Re),f(Re)}}else if(D==="artifact_delta"){let P=String(y.id),T=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:P,artDelta:T});let I=ye.get(P);I&&(I.markdown+=T)}else if(D==="artifact_update"){let P=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:P,component:typeof y.component=="string"?y.component:void 0});let T=ye.get(String(y.id));T&&(T.props={...T.props??{},...P})}else if(D==="artifact_complete"){let P=String(y.id);n({type:"artifact_complete",id:P});let T=pe.get(P);if(T){T.streaming=!1;try{let I=JSON.parse(T.rawContent??"{}");if(I.props){I.props.status="complete";let q=ye.get(P);q?.markdown&&(I.props.markdown=q.markdown),q?.file&&(I.props.file=q.file),I.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(I.props.componentProps=q.props)}T.rawContent=JSON.stringify(I)}catch{}ye.delete(P),f(T),pe.delete(P)}}}else if(D==="transcript_insert"){let P=y.message;if(!P||typeof P!="object")continue;let T=String(P.id??`msg-${c()}`),I=P.role,H={id:T,role:I==="user"?"user":I==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let J=JSON.parse(H.rawContent)?.props?.artifactId;typeof J=="string"&&xe.add(J)}catch{}v=null,R.current=null,Ve.delete(T),Te.delete(T)}else if(D==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let P=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(P)});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}else if(D==="step_error"||D==="dispatch_error"||D==="flow_error"){let P=null;if(y.error instanceof Error)P=y.error;else if(D==="dispatch_error"){let T=y.message??y.error;T!=null&&T!==""&&(P=new Error(String(T)))}else{let T=y.error;typeof T=="string"&&T!==""?P=new Error(T):T!=null&&typeof T=="object"&&Reflect.has(T,"message")&&(P=new Error(String(T.message??T)))}if(P){n({type:"error",error:P});let T=v;T&&T.streaming&&(T.streaming=!1,f(T)),n({type:"status",status:"idle"})}}}}}de.length=0};;){let{done:S,value:D}=await s.read();if(S)break;l+=a.decode(D,{stream:!0});let y=l.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},uu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var gu="4.16.0";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ul=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Oa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=qp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},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$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Ul).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:u}=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":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/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 u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:u(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)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=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(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
|
|
12
12
|
|
|
13
|
-
`);l=
|
|
14
|
-
`),I="message",q="",H=null;for(let Re of T)Re.startsWith("event:")?I=Re.replace("event:","").trim():Re.startsWith("data:")?q+=Re.replace("data:","").trim():Re.startsWith("id:")&&(H=Re.slice(3).trim());let z=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!q){z();continue}let J;try{J=JSON.parse(q)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let qe=I!=="message"?I:J.type??"message";if(this.onSSEEvent?.(qe,J),this.parseSSEEvent){R.current=v;let Re=await this.handleCustomSSEEvent(J,n,R,f,c,B);if(R.current&&R.current!==v&&(v=R.current),Re){z();continue}}de.push({payloadType:qe,payload:J}),et(),z()}}et()}};function xa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function sr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ca="[Image]";function Zd(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ar(e){return{type:"text",text:e}}var ep=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cm=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],_n=[...ep,...cm];function dm(e){return ep.includes(e)||e.startsWith("image/")}function Aa(e){return dm(e.type)}async function tp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Aa(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function np(e,t=_n,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function pm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function op(e,t){let n=pm(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var rp=16e3,um=24e3,fm=4096,gm=1380533830;function mm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===gm?new Uint8Array(e,44):new Uint8Array(e)}function hm(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var os=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:rp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new cd(um);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${hm(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(fm,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=mm(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Io=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ir(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new os(e.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function sp(e){if(e?.type==="custom"&&e.custom)return ir({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return ir({type:"runtype",runtype:e.runtype});if(Io.isSupported())return ir({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function tl(e){try{return sp(e),!0}catch{return!1}}function Sa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var lr=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Sa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var rs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function nl(e){if(!e)return"";let t=ym(e);return ap(t!==null?t:e)}function ym(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function ap(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);l=h.pop()??"";for(let W of h){let L=W.split(`
|
|
14
|
+
`),R="message",q="",$=null;for(let de of L)de.startsWith("event:")?R=de.replace("event:","").trim():de.startsWith("data:")?q+=de.replace("data:","").trim():de.startsWith("id:")&&($=de.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!q){K();continue}let ce;try{ce=JSON.parse(q)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let je=R!=="message"?R:ce.type??"message";if(this.onSSEEvent?.(je,ce),this.parseSSEEvent){T.current=v;let de=await this.handleCustomSSEEvent(ce,n,T,g,c,B);if(T.current&&T.current!==v&&(v=T.current),de){K();continue}}et.push({payloadType:je,payload:ce}),Le(),K()}}Le()}};function Ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Lr(e){return{type:"text",text:e}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yh=["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"],Qn=[...yu,...Yh];function Xh(e){return yu.includes(e)||e.startsWith("image/")}function Ya(e){return Xh(e.type)}async function bu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function vu(e,t=Qn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wu(e,t){let n=Qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var xu=16e3,Jh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:xu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mp(Jh);if(r!==this.callGeneration){u.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ny(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let w=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let u=l.inputBuffer.getChannelData(0),d=new Int16Array(u.length);for(let c=0;c<u.length;c++){let f=Math.max(-1,Math.min(1,u[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=ty(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Go=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!Go.isSupported())throw new Error("Browser speech recognition not supported");return new Go(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Cu(e){if(e?.type==="custom"&&e.custom)return Pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Pr({type:"runtype",runtype:e.runtype});if(Go.isSupported())return Pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zl(e){try{return Cu(e),!0}catch{return!1}}function Xa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ir=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function jl(e){if(!e)return"";let t=oy(e);return Au(t!==null?t:e)}function oy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Au(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
|
-
`),t.trim()}var
|
|
16
|
+
`),t.trim()}var Su=null;var Vl=()=>Su?Su():import("./runtype-tts-entry-UJAEF7NZ.js");var ry=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function sy(e,t){return ry.some(n=>e[n]!==t[n])}function ql(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]}),lp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,cp=e=>Zo(e)||e===On,Ta=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new rs(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Zo(n.name)||n.name===On&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ns(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ol().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return tl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=lr.isSupported()?new lr({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return ol().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=ir(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!vm(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ns(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?xa():n==="assistant"?sr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,C={id:p??(r==="user"?xa():r==="assistant"?sr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),Tu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Mu=e=>Cr(e)||e===Xn,Qa=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Is(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Cr(n.name)||n.name===Xn&&vo(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ls(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Vl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return zl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ir.isSupported()?new Ir({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Vl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:u})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new u(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Pr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let u=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=u.id}if(l){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:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let u=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=u.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!sy(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Ls(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:u,streaming:d=!1,voiceProcessing:c,rawContent:f}=t,g={id:a??(n==="user"?Ka():n==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...f!==void 0&&{rawContent:f}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:u,createdAt:d,sequence:c,streaming:f=!1,voiceProcessing:w,rawContent:g}=o,C={id:u??(r==="user"?Ka():r==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:u}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...u!==void 0&&{sequence:u}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(ar(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(ar(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=xa(),s=sr();this.activeAssistantMessageId=null;let a=n?.contentParts&&Zd(n.contentParts)?Ca:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=rl(c,this.config.errorMessage);if(w){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=sr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=rl(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let v=c[f],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==On?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:u,resumeKey:f,output:Ji(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),R;if(!C)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await C}catch(B){let L=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return L||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,ss(L?"Aborted by cancel()":lp(B)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,ss("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:R,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===On?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,ss("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===On,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let v;if(d?v=Ji():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,ss("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,ss(C||p.aborted?"Aborted by cancel()":lp(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ro(this.config.features?.artifacts,t),r=Qr(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ro(this.config.features?.artifacts,n),s=Qr(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>rl(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=sr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=nl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Sa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=nl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&cp(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&cp(f)&&r.toolCall?.status==="complete";(u||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ma={allowedTypes:_n,maxFileSize:10*1024*1024,maxFiles:4};function wm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function xm(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var as=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ma.allowedTypes,maxFileSize:t.maxFileSize??Ma.maxFileSize,maxFiles:t.maxFiles??Ma.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ma.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=np(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await tp(n),s=Aa(n)?URL.createObjectURL(n):null,a={id:wm(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Aa(t.file),o=h("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=h("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=h("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=xm(t.file.type),p=ie(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=h("span");d.textContent=op(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Lt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Ea=Vt+1;var Cm=8,Am=8,sl=10,al=new WeakMap,dp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Sm=e=>{let t=e.getRootNode?.();return dp(t)?t:e.ownerDocument.body},il=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ot(e){al.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Cm,viewportPadding:a=Am}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,f=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),R=()=>{u?.(),u=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let oe=l(),F=p(),$=t.getBoundingClientRect(),X=d.getBoundingClientRect(),me=oe.documentElement.clientWidth||F.innerWidth,he=oe.documentElement.clientHeight||F.innerHeight,Ae=me-a-X.width,Z=$.left+$.width/2-X.width/2,ce=il(Z,a,Ae),ee=$.top-a,le=he-a-$.bottom,Y=X.height+s,pe=ee>=Y||ee>=le?"top":"bottom",xe=pe==="top"?$.top-s-X.height:$.bottom+s,ye=he-a-X.height,ve=il(xe,a,ye),je=$.left+$.width/2,Me=Math.max(sl,X.width-sl),De=il(je-ce,sl,Me);d.dataset.placement=pe,d.style.left=`${ce}px`,d.style.top=`${ve}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${De}px`)},L=()=>{if(v||!r||d||!t.isConnected)return;let oe=C(),F=Sm(t);if(!oe||!F)return;let $=l(),X=p();d=$.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Ea),c=$.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=oe,d.appendChild(c);let me=$.createElement("span");me.className="persona-control-tooltip__arrow",d.appendChild(me),F.appendChild(d),B(),d.dataset.state="open";let he=()=>{if(!t.isConnected){R();return}c&&(c.textContent=C()),B()};X.addEventListener("scroll",he,!0),X.addEventListener("resize",he);let Ae=t.getRootNode(),Z=dp(Ae)?Ae:$.documentElement,ce=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||R()});ce?.observe(Z,{childList:!0,subtree:!0}),u=()=>{X.removeEventListener("scroll",he,!0),X.removeEventListener("resize",he),ce?.disconnect()}},E=()=>{w||f?L():R()},M=()=>{let oe=p();(!oe.matchMedia||!oe.matchMedia("(hover: none)").matches)&&(w=!0,E())},_=()=>{w=!1,E()},G=()=>{f=!0,E()},x=()=>{f=!1,E()},j=oe=>{oe.key==="Escape"&&(w=!1,f=!1,R())};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",_),t.addEventListener("focus",G),t.addEventListener("blur",x),t.addEventListener("keydown",j);let U={get isOpen(){return d!==null},show:L,hide:R,reposition:B,destroy:()=>{v||(v=!0,R(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",_),t.removeEventListener("focus",G),t.removeEventListener("blur",x),t.removeEventListener("keydown",j),al.delete(t))}};return al.set(t,U),U}function pp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=h("div","persona-send-button-wrapper"),d=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ie(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ot({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:nw,load:Tm}=Yo({fallbackImport:()=>import("./context-mentions-ONG7A7M6.js")});var ll=Tm;var{setLoader:sw,load:Mm}=Yo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var up=Mm;function is(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Be("span",{className:Dn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ie(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Be("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function fp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=ud(t).filter(E=>E.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(E=>E.sources.some(M=>typeof M.matchCommand=="function")),r=E=>o.some(M=>M.trigger?M.position==="line-start"?E.split(`
|
|
23
|
-
`).some(
|
|
24
|
-
`)[0]).startsWith(M.trigger):!1),s=(E,M)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:M}))}catch{}},a=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,w=null,f=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let E=ll().then(M=>(l=M.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:L,emit:s}),l)).catch(M=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",M),p===E&&(p=null),null));return p=E,E},C=()=>{up().then(E=>{let M=E.mountInlineComposer({textarea:e.textarea,renderToken:G=>is(G,{render:t.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});c=M.input,u=M.destroy;let _=d;_.replaceWith(M.element),d=M.element,f={next:M.element,prev:_},w?.(M.element,_),l?l.rebindComposer(M.input):p&&p.then(G=>G?.rebindComposer(M.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};t.display==="inline"&&C();let R=[],B=new Map;for(let E of n){if(!E.showButton)continue;let M=pp({config:{...t,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(_=>_?.openMenu(E.trigger))}});R.push(M),B.set(E.trigger,M.button)}let L=(E,M,_)=>{let G=B.get(M);G&&(G.setAttribute("aria-expanded",E?"true":"false"),E?G.setAttribute("aria-controls",_):G.removeAttribute("aria-controls"))};return{affordanceButtons:R.map(E=>E.wrapper),contextRow:a,handleInput:E=>{if(l){l.handleInput();return}if(!pd(E))return;let M=d,_=M.selectionStart??0;dd(M.value,_,n)&&v().then(G=>G?.handleInput())},handleKeydown:E=>{if(l?.isMenuOpen())return l.handleKeydown(E);if(E.key==="Backspace"&&l?.hasMentions()&&!f){let M=d,_=M.selectionStart===0&&M.selectionEnd===0;if((M.value.length===0||_)&&l.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(l??await v())?.dispatchInlineCommand(E)??null:null,clear:()=>l?.clear(),prefetch:()=>{ll().catch(()=>{})},onComposerSwap:E=>{w=E,f&&E(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let E of R)E.wrapper.remove();a.remove()}}}var gp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ls(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];gp(s)&&gp(r)?n[o]=ls(s,r):n[o]=r}return n}var $n="min(440px, calc(100vw - 24px))",hp="440px",Em={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:$n,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},at={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Em,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function mp(e,t){if(!(!e&&!t))return e?t?ls(e,t):e:t}function ka(e){return e?{...at,...e,theme:mp(at.theme,e.theme),darkTheme:mp(at.darkTheme,e.darkTheme),launcher:{...at.launcher,...e.launcher,dock:{...at.launcher?.dock,...e.launcher?.dock},clearChat:{...at.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...at.copy,...e.copy},sendButton:{...at.sendButton,...e.sendButton},statusIndicator:{...at.statusIndicator,...e.statusIndicator},voiceRecognition:{...at.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=at.features?.artifacts,n=e.features?.artifacts,o=at.features?.scrollToBottom,r=e.features?.scrollToBottom,s=at.features?.scrollBehavior,a=e.features?.scrollBehavior,l=at.features?.streamAnimation,p=e.features?.streamAnimation,d=at.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...at.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??at.suggestionChips,suggestionChipsConfig:{...at.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...at.layout,...e.layout,header:{...at.layout?.header,...e.layout?.header},messages:{...at.layout?.messages,...e.layout?.messages,avatar:{...at.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...at.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...at.layout?.slots,...e.layout?.slots}},markdown:{...at.markdown,...e.markdown,options:{...at.markdown?.options,...e.markdown?.options}},messageActions:{...at.messageActions,...e.messageActions}}:at}var La="16px",Pa="transparent",km={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Lm={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Pm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:$n,maxWidth:hp,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:La,canvasBackground:Pa},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(e,o):o}function yp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Gt(e,a);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Im(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function bp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=bp(s,r):n[o]=r}return n}function Rm(e,t){return t?bp(e,t):e}function cr(e,t={}){let n={palette:km,semantic:Lm,components:Pm},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Rm(n.components,e?.components)};if(t.validate!==!1){let r=Im(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function vp(e){let t=yp(e),n={};for(let[x,j]of Object.entries(t)){let U=x.replace(/\./g,"-");n[`--persona-${U}`]=j.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??La,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Pa,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let f=d?.artifact;if(f?.toolbar){let x=f.toolbar;x.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=x.iconHoverColor),x.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=x.iconHoverBackground),x.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=x.iconPadding),x.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=x.iconBorderRadius),x.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=x.iconBorder),x.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=x.toggleGroupGap),x.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=x.toggleBorderRadius),x.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=x.toggleGroupPadding),x.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=x.toggleGroupBorder),x.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=x.toggleGroupBorderRadius),x.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(e,x.toggleGroupBackground)??x.toggleGroupBackground),x.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=x.copyBackground),x.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=x.copyBorder),x.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=x.copyColor),x.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=x.copyBorderRadius),x.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=x.copyPadding),x.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=x.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??x.copyMenuBackground),x.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=x.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??x.copyMenuBorder),x.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=x.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??x.copyMenuShadow),x.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=x.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??x.copyMenuBorderRadius),x.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=x.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??x.copyMenuItemHoverBackground),x.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=x.iconBackground),x.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=x.toolbarBorder)}if(f?.tab){let x=f.tab;x.background&&(n["--persona-artifact-tab-bg"]=x.background),x.activeBackground&&(n["--persona-artifact-tab-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-artifact-tab-active-border"]=x.activeBorder),x.borderRadius&&(n["--persona-artifact-tab-radius"]=x.borderRadius),x.textColor&&(n["--persona-artifact-tab-color"]=x.textColor),x.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=x.hoverBackground),x.listBackground&&(n["--persona-artifact-tab-list-bg"]=x.listBackground),x.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=x.listBorderColor),x.listPadding&&(n["--persona-artifact-tab-list-padding"]=x.listPadding)}if(f?.pane){let x=f.pane;if(x.toolbarBackground){let j=Gt(e,x.toolbarBackground)??x.toolbarBackground;n["--persona-artifact-toolbar-bg"]=j}}if(f?.card){let x=f.card;x.background&&(n["--persona-artifact-card-bg"]=x.background),x.border&&(n["--persona-artifact-card-border"]=x.border),x.borderRadius&&(n["--persona-artifact-card-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=x.hoverBackground),x.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=x.hoverBorderColor)}if(f?.inline){let x=f.inline;x.background&&(n["--persona-artifact-inline-bg"]=Gt(e,x.background)??x.background),x.border&&(n["--persona-artifact-inline-border"]=x.border),x.borderRadius&&(n["--persona-artifact-inline-radius"]=x.borderRadius),x.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,x.mutedColor)??x.mutedColor),x.frameHeight&&(n["--persona-artifact-inline-frame-height"]=x.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Gt(e,v.background)??v.background));let C=n["--persona-surface"],R=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",L=n["--persona-palette-colors-gray-200"]??"#e5e7eb",E=n["--persona-palette-colors-gray-300"]??"#d1d5db",M=!R||R===C,_=M?B:R,G=M?L:R;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,M&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??E),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var Wm={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},wp=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},cl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Hm=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":cl()},xp=e=>Hm(e),Bm=e=>cr(e),Dm=e=>cr({...e,palette:{...e?.palette,colors:{...Wm.colors,...e?.palette?.colors}}},{validate:!1}),dr=e=>{let t=xp(e),n=wp(e?.theme),o=wp(e?.darkTheme);return t==="dark"?Dm(ls(n??{},o??{})):Bm(n)},Fm=e=>vp(e),cs=(e,t)=>{let n=dr(t),o=Fm(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",xp(t))},Ia=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(cl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(cl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Mn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Cp(e){let t=Mn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ra(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,u=r.contentParts.length>0;if(l){let d=[];s&&d.push(Lr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(u){let d=[];a&&d.push(Lr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ka(),s=kr();this.activeAssistantMessageId=null;let a=n?.contentParts&&hu(n.contentParts)?Ga:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let c=this.messages.find(f=>f.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:u.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let w=ql(c,this.config.errorMessage);if(w){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=kr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=ql(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let u=this.config.approval,d=u&&typeof u=="object"?u.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let f=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let w=typeof f[0]?.question=="string"?f[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,u=t.toolCall?.args,d=Array.isArray(u?.questions)?u.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([f,w])=>`${f}: ${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((f,w)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let v=c[g],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Xn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{let d=u.toolCall?.name,c=u.toolCall?.id;if(!d||!c)return null;let f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(f),o.push(f);let w=this.markWebMcpToolRunning(u),g=u.agentMetadata?.webMcpToolCallId??d;if(d===Xn)return{dedupeKey:f,resumeKey:g,output:_l(),toolMessage:u,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,u.toolCall?.args,v.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch(B){let S=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return S||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(u,Ws(S?"Aborted by cancel()":Tu(B)),w),this.webMcpInflightKeys.delete(f),null}return v.signal.aborted?(this.markWebMcpToolComplete(u,Ws("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:T,toolMessage:u,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let u={};for(let c of l)u[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,u,{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===Xn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Ws("Aborted by cancel()"),c.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:u}=l;this.setStreaming(!0);let d=o===Xn,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,u),w="execute",g=a;try{let v;if(d?v=_l():f?v=await f:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),u.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:u})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||u.aborted)&&this.markWebMcpToolComplete(t,Ws(C||u.aborted?"Aborted by cancel()":Tu(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ho(this.config.features?.artifacts,t),r=xs(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ho(this.config.features?.artifacts,n),s=xs(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ql(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=kr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=jl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Xa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=jl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,f=n.approval;a.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,u=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Mu(l)&&u&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${u}:${d}`,f=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,v=r.agentMetadata?.executionId===u&&r.toolCall?.id===d&&g!==void 0&&Mu(g)&&r.toolCall?.status==="complete";(f||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ja={allowedTypes:Qn,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Rs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ja.allowedTypes,maxFileSize:t.maxFileSize??Ja.maxFileSize,maxFiles:t.maxFiles??Ja.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ja.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=vu(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 bu(n),s=Ya(n)?URL.createObjectURL(n):null,a={id:ay(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ya(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=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 l=iy(t.file.type),u=ae(l,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let d=b("span");d.textContent=wu(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Nt=1e5,Za=Nt+1;var ly=8,cy=8,Kl=10,Gl=new WeakMap,Eu=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,dy=e=>{let t=e.getRootNode?.();return Eu(t)?t:e.ownerDocument.body},Yl=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function _t(e){Gl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=ly,viewportPadding:a=cy}=e,l=()=>t.ownerDocument,u=()=>l().defaultView??window,d=null,c=null,f=null,w=!1,g=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),T=()=>{f?.(),f=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let te=l(),A=u(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),ie=te.documentElement.clientWidth||A.innerWidth,Y=te.documentElement.clientHeight||A.innerHeight,ue=ie-a-Q.width,X=G.left+G.width/2-Q.width/2,ge=Yl(X,a,ue),Z=G.top-a,pe=Y-a-G.bottom,ee=Q.height+s,me=Z>=ee||Z>=pe?"top":"bottom",we=me==="top"?G.top-s-Q.height:G.bottom+s,he=Y-a-Q.height,ke=Yl(we,a,he),Ne=G.left+G.width/2,Ue=Math.max(Kl,Q.width-Kl),Qe=Yl(Ne-ge,Kl,Ue);d.dataset.placement=me,d.style.left=`${ge}px`,d.style.top=`${ke}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Qe}px`)},S=()=>{if(v||!r||d||!t.isConnected)return;let te=C(),A=dy(t);if(!te||!A)return;let G=l(),Q=u();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Za),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=te,d.appendChild(c);let ie=G.createElement("span");ie.className="persona-control-tooltip__arrow",d.appendChild(ie),A.appendChild(d),B(),d.dataset.state="open";let Y=()=>{if(!t.isConnected){T();return}c&&(c.textContent=C()),B()};Q.addEventListener("scroll",Y,!0),Q.addEventListener("resize",Y);let ue=t.getRootNode(),X=Eu(ue)?ue:G.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||T()});ge?.observe(X,{childList:!0,subtree:!0}),f=()=>{Q.removeEventListener("scroll",Y,!0),Q.removeEventListener("resize",Y),ge?.disconnect()}},k=()=>{w||g?S():T()},P=()=>{let te=u();(!te.matchMedia||!te.matchMedia("(hover: none)").matches)&&(w=!0,k())},H=()=>{w=!1,k()},F=()=>{g=!0,k()},N=()=>{g=!1,k()},z=te=>{te.key==="Escape"&&(w=!1,g=!1,T())};n.addEventListener("mouseenter",P),n.addEventListener("mouseleave",H),t.addEventListener("focus",F),t.addEventListener("blur",N),t.addEventListener("keydown",z);let j={get isOpen(){return d!==null},show:S,hide:T,reposition:B,destroy:()=>{v||(v=!0,T(),n.removeEventListener("mouseenter",P),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",F),t.removeEventListener("blur",N),t.removeEventListener("keydown",z),Gl.delete(t))}};return Gl.set(t,j),j}function ku(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",u=b("div","persona-send-button-wrapper"),d=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),u.appendChild(d),_t({anchor:d,trigger:u,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:u}}var{setLoader:aC,load:py}=xr({fallbackImport:()=>import("./context-mentions-BTSTIBFC.js")});var Xl=py;var{setLoader:cC,load:uy}=xr({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Lu=uy;function Hs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ee("span",{className:Pn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=b("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ee("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Pu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Lp(t).filter(k=>k.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(k=>k.sources.some(P=>typeof P.matchCommand=="function")),r=k=>o.some(P=>P.trigger?P.position==="line-start"?k.split(`
|
|
23
|
+
`).some(F=>F.startsWith(P.trigger)):(P.position==="anywhere"?k:k.split(`
|
|
24
|
+
`)[0]).startsWith(P.trigger):!1),s=(k,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${k}`,{detail:P}))}catch{}},a=Ee("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,u=null,d=e.textarea,c=null,f=null,w=null,g=null,v=()=>{if(l)return Promise.resolve(l);if(u)return u;let k=Xl().then(P=>(l=P.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:s}),l)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),u===k&&(u=null),null));return u=k,k},C=()=>{Lu().then(k=>{let P=k.mountInlineComposer({textarea:e.textarea,renderToken:F=>Hs(F,{render:t.renderMentionToken}),onMentionRemoved:F=>l?.untrackMention(F)});c=P.input,f=P.destroy;let H=d;H.replaceWith(P.element),d=P.element,g={next:P.element,prev:H},w?.(P.element,H),l?l.rebindComposer(P.input):u&&u.then(F=>F?.rebindComposer(P.input))}).catch(k=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",k)})};t.display==="inline"&&C();let T=[],B=new Map;for(let k of n){if(!k.showButton)continue;let P=ku({config:{...t,buttonIconName:k.buttonIconName,buttonTooltipText:k.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(H=>H?.openMenu(k.trigger))}});T.push(P),B.set(k.trigger,P.button)}let S=(k,P,H)=>{let F=B.get(P);F&&(F.setAttribute("aria-expanded",k?"true":"false"),k?F.setAttribute("aria-controls",H):F.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(k=>k.wrapper),contextRow:a,handleInput:k=>{if(l){l.handleInput();return}if(!kp(k))return;let P=d,H=P.selectionStart??0;Ep(P.value,H,n)&&v().then(F=>F?.handleInput())},handleKeydown:k=>{if(l?.isMenuOpen())return l.handleKeydown(k);if(k.key==="Backspace"&&l?.hasMentions()&&!g){let P=d,H=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||H)&&l.removeLastChip())return k.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async k=>r(k)?(l??await v())?.dispatchInlineCommand(k)??null:null,clear:()=>l?.clear(),prefetch:()=>{Xl().catch(()=>{})},onComposerSwap:k=>{w=k,g&&k(g.next,g.prev)},destroy:()=>{l?.destroy(),f?.();for(let k of T)k.wrapper.remove();a.remove()}}}var Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Iu(s)&&Iu(r)?n[o]=Bs(s,r):n[o]=r}return n}var Jn="min(440px, calc(100vw - 24px))",Ru="440px",fy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:fy,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Wu(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function ei(e){return e?{...rt,...e,theme:Wu(rt.theme,e.theme),darkTheme:Wu(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=rt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=rt.features?.streamAnimation,u=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&u===void 0?void 0:{...l,...u},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...g!==void 0?{scrollBehavior:g}:{},...f!==void 0?{artifacts:f}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var ti="16px",ni="transparent",gy={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"}},my={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"}},hy={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Jn,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ti,canvasBackground:ni},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Qt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Qt(e,o):o}function Hu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let u=Qt(e,a);u!==void 0&&(t[l]={path:l,value:u,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yy(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Bu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Bu(s,r):n[o]=r}return n}function by(e,t){return t?Bu(e,t):e}function Wr(e,t={}){let n={palette:gy,semantic:my,components:hy},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:by(n.components,e?.components)};if(t.validate!==!1){let r=yy(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Du(e){let t=Hu(e),n={};for(let[A,G]of Object.entries(t)){let Q=A.replace(/\./g,"-");n[`--persona-${Q}`]=G.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ti,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ni,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],a=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=a&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let u=n["--persona-components-markdown-heading-h1-fontSize"];u&&(n["--persona-md-h1-size"]=u);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let w=n["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(n["--persona-md-prose-font-family"]=w),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let g=e.components,v=g?.iconButton;v&&(v.background&&(n["--persona-icon-btn-bg"]=v.background),v.border&&(n["--persona-icon-btn-border"]=v.border),v.color&&(n["--persona-icon-btn-color"]=v.color),v.padding&&(n["--persona-icon-btn-padding"]=v.padding),v.borderRadius&&(n["--persona-icon-btn-radius"]=v.borderRadius),v.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=v.hoverBackground),v.hoverColor&&(n["--persona-icon-btn-hover-color"]=v.hoverColor),v.activeBackground&&(n["--persona-icon-btn-active-bg"]=v.activeBackground),v.activeBorder&&(n["--persona-icon-btn-active-border"]=v.activeBorder));let C=g?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let T=g?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let B=g?.artifact;if(B?.toolbar){let A=B.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(B?.tab){let A=B.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(B?.pane){let A=B.pane;if(A.toolbarBackground){let G=Qt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(B?.card){let A=B.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(B?.inline){let A=B.inline;A.background&&(n["--persona-artifact-inline-bg"]=Qt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let S=g?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=Qt(e,S.background)??S.background));let k=n["--persona-surface"],P=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",F=n["--persona-palette-colors-gray-200"]??"#e5e7eb",N=n["--persona-palette-colors-gray-300"]??"#d1d5db",z=!P||P===k,j=z?H:P,te=z?F:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??te,z&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??N),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var vy={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"}}},Fu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ql=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",wy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ql()},Ou=e=>wy(e),xy=e=>Wr(e),Cy=e=>Wr({...e,palette:{...e?.palette,colors:{...vy.colors,...e?.palette?.colors}}},{validate:!1}),Rr=e=>{let t=Ou(e),n=Fu(e?.theme),o=Fu(e?.darkTheme);return t==="dark"?Cy(Bs(n??{},o??{})):xy(n)},Ay=e=>Du(e),Ds=(e,t)=>{let n=Rr(t),o=Ay(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Ou(t))},oi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ql())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ql());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var xo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function Bn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Nu(e){let t=Bn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ri(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
25
25
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
26
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
27
|
-
`).length,
|
|
26
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Yo(e){let t=Nu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Co(e){switch(Yo(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Nu(e.path);return t?t.toUpperCase():"File"}}}function _u(e){let t=e.markdown??"";return e.file?{filename:Bn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ri(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Jl="http://www.w3.org/2000/svg";function $u(e){let t=document.createElementNS(Jl,"svg");t.setAttribute("class",Pn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Jl,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Jl,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var Ao=(e,t,n)=>{let o=n;for(let r of t){let s=b("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Uu(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Ao(e,t,0)}var Zl="persona-artifact-status-label",zu="persona-artifact-status-detail",ju="data-artifact-status-label",ec=new Map,Vu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Hr(e){e&&ec.delete(e)}function Sy(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Co(t):e.artifactType==="component"?"Component":"Document"}function Br(e,t,n){let o=Sy(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,l=ec.get(a);e.status!=="complete"&&l===void 0&&(l=Vu(),ec.set(a,l));let u=l===void 0?0:Math.max(0,Vu()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:c.length,w=d||c===""?0:c.split(`
|
|
27
|
+
`).length,g=e.artifactType==="markdown"?e.file:void 0,v={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:w,elapsedMs:u,content:()=>d?"":c,surface:n};try{let C=s(v);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function Ty(e){e.className=Zl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Xo(e,t,n){let o=e.querySelector(`:scope > .${Zl}`);o||(o=b("span",Zl),e.appendChild(o)),o.getAttribute(ju)!==t.label&&(Ty(o),Uu(o,t.label,n),o.setAttribute(ju,t.label));let r=e.querySelector(`:scope > .${zu}`),s=t.detail;s?(r||(r=b("span",zu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var My={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"},Ey=15e4,si={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 ky(e,t){let n=(e||"").trim().toLowerCase();if(n&&si[n])return si[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(si[r])return si[r]}}return null}function ai(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let l of t){l.re.lastIndex=o;let u=l.re.exec(e);if(u&&u.index===o&&u[0].length>0){s(o);let d=l.map?l.map(u[0]):l.type;n.push({type:d,value:u[0]}),o+=u[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var Ly=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"]),Py=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Ly.has(e)?"keyword":"plain"}];function qu(e){return ai(e,Py)}var Iy=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Wy(e){let t=ai(e,Iy);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Ry=[{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 Ku(e){let t=ai(e,Ry),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let l=t[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Hy=[{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 By(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),l=a===-1?o:a+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),l=a===-1?o:a+1,u=e.slice(r,l);for(let c of ai(u,Hy))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(u);if(d&&!/\/>\s*$/.test(u)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=w?r+w.index:o,v=e.slice(r,g),C=c==="script"?qu(v):Ku(v);for(let T of C)t.push(T);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Dy(e,t){switch(t){case"html":return By(e);case"css":return Ku(e);case"js":return qu(e);case"json":return Wy(e)}}function Fy(e){let t=Tp(),n=b("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=My[r];if(a){let l=b("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
28
28
|
`);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
29
|
-
`)),n=h("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Ip(e,t,n){let o=e.length<=$m?zm(t,n):null,r=o?Xm(e,o):[{type:"plain",value:e}];return Jm(r)}function fr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ea)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let R=document.createElement("hr");a.appendChild(R)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let R=ie(f.icon,16,"currentColor",1.5);R&&v.appendChild(R)}let C=document.createElement("span");C.textContent=f.label,v.appendChild(C),v.addEventListener("click",R=>{R.stopPropagation(),c(),n(f.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Pt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ie(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Wo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=h("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ie(t,s??14,"currentColor",2);w&&c.appendChild(w)}let u=h("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function Ba(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=h("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=Pt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=h("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Rp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=e,d=h("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=h("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ie(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=fr({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",f=>{f.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let f=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var Da="persona-artifact-custom-action-btn";function gr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Da+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Da+(n?" persona-artifact-doc-icon-btn":"");o=h("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=h("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Wo({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-copy-btn":"")}):o=Pt({icon:e.icon,label:e.label,className:Da+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function ps(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Wp(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Mn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?lo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,R={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},B=ur(R,C,"card");Ro(v,B,C)}else s&&pr(s),v.textContent=d;if(w.append(f,v),c.append(u,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of C)try{if(L.visible===void 0||L.visible(B)){let E=gr(L);E.setAttribute("data-artifact-custom-action",L.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let R=Wo({label:"Download",className:"persona-flex-shrink-0"});R.title=`Download ${r}`,R.setAttribute("data-download-artifact",s),c.append(R)}return c}var Fa=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Wp(e,t)});if(l)return l}return Wp(e,t)};var po=new WeakMap;function fl(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=po.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Np(e){return po.has(e)}function Ym(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Hp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Mn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Zm(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Bp=180,eh=240,th=.8,nh=300,oh=500,rh="cubic-bezier(0.2, 0, 0, 1)",Dp=240,sh=.35;function ah(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Bp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(oh,Math.max(nh,eh+d*th))),u=Math.round(c*sh),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:Dp,delay:u,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:rh});e.style.height=`${p}px`;let C=!1,R=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,f?.finished].filter(Boolean)).then(R),window.setTimeout(R,Math.max(c,u+Dp)+120)},Bp)}function ih(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var us="--persona-artifact-inline-body-height";function lh(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function Fp(e,t){let n=Ym(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=ih(o),p=o?.inlineActions??[],d=lh(o),c=d.completeDisplay==="card",u=null,w=n,f=h("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let v=ee=>Fa(Zm(ee),t),C=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(us),f.replaceChildren(v(ee)),po.set(f,le=>{f.replaceChildren(v(le))})};if(c&&n.status==="complete")return C(n),f;let R=Na(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(R.el);let L=ee=>{let le=ee.status!=="complete",Y=le?d.streamingHeight:d.completeHeight,pe=typeof Y=="number";pe?f.style.setProperty(us,`${Y}px`):f.style.removeProperty(us);let xe=!!R.el.querySelector(".persona-code-pre"),ye=!!R.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",xe),B.classList.toggle("persona-artifact-inline-body--sized",pe&&ye),B.classList.toggle("persona-artifact-inline-body--cap",!le&&!ye&&typeof d.completeHeight=="number")},E=n.status,M=(ee,le)=>{E!=="complete"&&ee.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(us,`${d.completeHeight}px`):f.style.removeProperty(us),_p(B,le?.suppressTransition?"none":d.transition,ee.id,()=>{R.update(ee),L(ee)})):R.update(ee),L(ee),E=ee.status};L(n);let _=d.overflow==="clip"&&a&&!!n.id;if(_&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Hp(n).title} in panel`)),!r)return f.appendChild(B),po.set(f,M),f;let G=h("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=h("div","persona-artifact-inline-chrome-lead"),j=h("span","persona-flex persona-items-center persona-flex-shrink-0"),U=ie("file-text",16,"currentColor",2);U&&j.appendChild(U);let oe=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),F=h("span","persona-artifact-inline-type");x.append(j,oe,F);let $=h("div","persona-artifact-inline-chrome-actions"),X=h("span","persona-flex persona-items-center persona-gap-1"),me=()=>u??d.viewMode,he=l?Ba({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:me(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let le=ee==="source"?"source":"rendered";le!==me()&&(u=le,R.update(w),L(w))}}):null,Ae=s?Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ae&&n.id&&Ae.setAttribute("data-copy-artifact",n.id);let Z=a?Pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(X),he&&$.appendChild(he.element),Ae&&$.appendChild(Ae),Z&&$.appendChild(Z),G.append(x,$),f.append(G,B);let ce=ee=>{let{title:le,typeLabel:Y}=Hp(ee);oe.textContent=le,oe.title=le,_&&B.setAttribute("aria-label",`Open ${le} in panel`);let pe=ee.status!=="complete";if(pe){F.classList.contains("persona-artifact-inline-status")||(F.className="persona-artifact-inline-status",F.removeAttribute("data-preserve-animation"),F.replaceChildren());let xe=ur(ee,o,"inline-chrome");Ro(F,xe,o)}else pr(ee.id),F.className="persona-artifact-inline-type",F.removeAttribute("data-preserve-animation"),F.replaceChildren(),F.textContent=Y;if(Ae&&Ae.classList.toggle("persona-hidden",pe),he){let xe=ee.artifactType==="markdown"?ee.file:void 0,ye=!1;if(!pe&&xe&&d.viewMode!=="source"){let ve=ds(xe);ve==="markdown"?ye=!0:(ve==="html"||ve==="svg")&&(ye=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ye),he.setSelected(me())}if(X.replaceChildren(),!pe&&p.length>0){let xe=ps(ee);if(xe)for(let ye of p)try{if(ye.visible===void 0||ye.visible(xe)){let ve=gr(ye,{documentChrome:!0});ve.setAttribute("data-artifact-custom-action",ye.id),ve.classList.add("persona-flex-shrink-0"),X.appendChild(ve)}}catch{}}};return ce(n),po.set(f,(ee,le)=>{if(c&&E!=="complete"&&ee.status==="complete"){let Y=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let pe=ee,xe=!1,ye=ve=>{pe=ve,xe=!0};po.set(f,ye),ah(f,Y,{swap:()=>{C(pe),xe=!1,po.set(f,ye)},onSettled:()=>{xe?C(pe):po.set(f,ve=>{f.replaceChildren(v(ve))})}});return}(ee.status!=="complete"||ee.id!==w.id)&&(u=null),w=ee,M(ee,le),ce(ee)}),f}var Op=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Fp(e,t)});if(l)return l}return Fp(e,t)};var gl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},zn=new gl;zn.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});zn.register("PersonaArtifactInline",Op,{bubbleChrome:!1});function fs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ra(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var ml=!1;function ch(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function _p(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||ml||s){o();return}ml=!0;let a=ch(n);e.style.setProperty("view-transition-name",a);let l=()=>{ml=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var dh="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",ph="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function uh(e){let t=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function fh(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var gh=220;function mh(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function hh(e){return`
|
|
30
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function yh(e,t,n){let o=h("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=h("div","persona-artifact-frame-loading-indicator");r.appendChild(Sp());let s=null;return n.label!==!1&&(s=h("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function bh(e,t,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},u=(E,M)=>{let _=setTimeout(()=>{d.delete(_),E()},M);d.add(_)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let E=yh(r,s,o);a=E.el,e.appendChild(a),l=Date.now(),o.label!==!1&&u(E.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,gh))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",L)},R=()=>{if(p||(p=!0,C(),c(),!a))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?u(v,E):v()};function B(E){if(n===null)return;let M=E.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||E.source===t.contentWindow&&R()}function L(){let E=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};E(()=>E(()=>R()))}return u(f,o.delayMs),u(R,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",L),()=>{p=!0,c(),C(),w()}}function Na(e,t){let{config:n}=t,o=t.registry??zn,r=t.bodyLayout,s=n.markdown?ca(n.markdown):null,a=da(n.sanitize),l=e,p=!1,d=Z=>{let ce=Fn()!==null;s&&!ce&&!p&&(p=!0,la(()=>Ae(l)));let ee=s?s(Z):oo(Z);return s&&ce&&a?a(ee):ee},c=h("div","persona-artifact-preview-body"),u=null,w=null,f=null,v=()=>{f&&(f(),f=null),u=null,w=null},C=null,R=null,B=null,L=!1,E=()=>{C=null,R=null,B=null,L=!1},M=null,_=null,G=()=>{M=null,_=null},x=40,j=0,U=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),oe=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=x,F=Z=>{if(!r)return;let ce=Z.scrollHeight-Z.clientHeight>1,ee=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ce&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ce&&ee>1)},$=Z=>{j||(j=U(()=>{j=0,Z.scrollTop=Z.scrollHeight,F(Z)}))},X=(Z,ce,ee,le)=>{let Y=!!r,pe=ee.id+"|"+(Y?"w":"p");if(!C||B!==pe||C.parentElement!==c){v(),G(),c.replaceChildren();let ve=h("pre",dh+" persona-code-pre"),je=h("code","persona-code");if(ve.appendChild(je),Y){let Me=h("div","persona-artifact-source-window");if(Me.appendChild(ve),c.appendChild(Me),!(r?.overflow==="clip")&&typeof Me.addEventListener=="function"){let Qe=()=>Me.scrollHeight-Me.clientHeight>1;Me.addEventListener("scroll",()=>{oe(Me)&&(L=!1),F(Me)},{passive:!0}),Me.addEventListener("wheel",Ve=>{Qe()&&Ve.deltaY<0&&(L=!0)},{passive:!0}),Me.addEventListener("touchmove",()=>{Qe()&&(L=!0)},{passive:!0})}C=Me}else c.appendChild(ve),C=ve;R=je,B=pe}let xe=Y?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",le),xe.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let ye=xe?oe(xe):!0;if(R.replaceChildren(Ip(Z,ce?.language,ce?.path)),xe){let ve=ee.status!=="complete";le&&ve&&r?.followOutput&&!L&&ye?$(xe):ve||(L=!1),F(xe)}},me=Z=>{v(),E(),G(),c.replaceChildren();let ce=h("div",ph);ce.innerHTML=d(Z),c.appendChild(ce)},he=Z=>{let ce=Z.id,ee=n.features?.artifacts,le=ur(Z,ee,"status-body");if(M&&_===ce&&M.parentElement===c){let xe=M.querySelector(".persona-artifact-status-view-text");xe&&Ro(xe,le,ee);return}v(),E(),c.replaceChildren();let Y=h("div","persona-artifact-status-view"),pe=h("div","persona-artifact-status-view-text");Ro(pe,le,ee),Y.appendChild(pe),c.appendChild(Y),M=Y,_=ce},Ae=Z=>{l=Z;let ce=t.resolveViewMode?.(Z)??r?.viewMode??"rendered",ee=Z.artifactType==="markdown"?Z.file:void 0,le=Z.status!=="complete";le||pr(Z.id);let Y=le?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof Y=="number";if(r?.streamingView==="status"&&le){he(Z);return}if(ee){let ye=Ra(Z.markdown??""),ve=ds(ee),je=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ce==="rendered"&&je&&(ve==="html"||ve==="svg")){let De=Z.id+"\0"+ye;if(u&&w===De&&u.parentElement===c)return;E(),G(),v(),c.replaceChildren();let Qe=n.features?.artifacts?.filePreview,Ve=Qe?.iframeSandbox??"allow-scripts";!Qe?.dangerouslyAllowSameOrigin&&Ve.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ve=Ve.split(/\s+/).filter(It=>It&&It!=="allow-same-origin").join(" "));let Te=fh(Qe?.loading),Le=h("div","persona-artifact-frame"),Xe=h("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Ve),Xe.setAttribute("data-artifact-id",Z.id);let Ht=null;Te.enabled&&Te.injectReadySignal?(Ht=mh(),Xe.srcdoc=ye+hh(Ht)):Xe.srcdoc=ye,Le.appendChild(Xe),c.appendChild(Le),Te.enabled&&(f=bh(Le,Xe,Ht,Te,Z.id,n)),u=Le,w=De;return}if(v(),!le&&ve==="markdown"&&ce==="rendered"){me(ye);return}X(ye,{language:ee.language,path:ee.path},Z,pe);return}if(Z.artifactType==="markdown"){if(ce==="source"){v(),X(Z.markdown??"",void 0,Z,pe);return}me(Z.markdown??"");return}v(),E(),G(),c.replaceChildren();let xe=Z.component?o.get(Z.component):void 0;if(xe){let ve={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let je=xe(Z.props??{},ve);if(je){c.appendChild(je);return}}catch{}}c.appendChild(uh(Z))};return Ae(e),{el:c,update(Z){Ae(Z)}}}import{Idiomorph as vh}from"idiomorph";var Oa=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;vh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var $p=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hl={index:-1,draft:""};function zp(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function jp(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Up(){return new Map}function Vp(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function qp(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Kp(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Gp(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function _a(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function En(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return En(e)-e.scrollTop<=t}function $a(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function za(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Qp(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Xp(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Jp(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var gs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wh=["pre","code","a","script","style"],ja=e=>({type:e?.type??gs.type,placeholder:e?.placeholder??gs.placeholder,speed:e?.speed??gs.speed,duration:e?.duration??gs.duration,buffer:e?.buffer??gs.buffer}),xh=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],Zp=new Map;for(let e of xh)Zp.set(e.name,e);var mr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Zp.get(e)??null,Ua=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
-
`);return s<0?"":e.slice(0,s)}return e},Ch=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},Ah=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},yl=/\s/,Sh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Th=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(yl.test(s[l])){let p=l;for(;p<s.length&&yl.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!yl.test(s[d]);)p.appendChild(Ch(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,e)},Mh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Ah(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},ms=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??wh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Sh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Th:Mh;for(let u of l)c(u,n,d);return r.innerHTML},Va=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},hs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Yp=new WeakMap,Eh=(e,t)=>{if(!e.styles)return;let n=Yp.get(t);if(n||(n=new Set,Yp.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},bl=new WeakMap,kh=(e,t)=>{if(!e.onAttach)return;let n=bl.get(t);if(n||(n=new Map,bl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},eu=e=>{let t=bl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},qa=(e,t)=>{Eh(e,t),kh(e,t)};function vl(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var ys=0,fo=null;function wl(e=document){if(ys++,ys===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;fo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,ys=Math.max(0,ys-1),ys===0&&fo)){let n=e.body,o=e.defaultView??window;n.style.overflow=fo.originalOverflow,n.style.position=fo.originalPosition,n.style.top=fo.originalTop,n.style.width=fo.originalWidth,o.scrollTo(0,fo.scrollY),fo=null}}}var bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Dt=e=>(e?.launcher?.mountMode??"floating")==="docked",vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",gn=e=>{let t=e?.launcher?.dock;return{side:t?.side??bs.side,width:t?.width??bs.width,animate:t?.animate??bs.animate,reveal:t?.reveal??bs.reveal,maxHeight:t?.maxHeight??bs.maxHeight}};var Cn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Lh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ka=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lh,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",p=h("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Be("button",{className:Dn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Qt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ie(u,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,p.appendChild(v),Ot({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},Ph="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ga=(e,t={})=>{let{wrapperClassName:n=Ph,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",R=a.tooltipText??"Clear chat",B=a.showTooltip??!0,L=h("div",n),E=!!(u||w),M=Be("button",{className:Dn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":R},style:{height:l,width:l,color:d||Qt.actionIconColor,backgroundColor:c||void 0,border:E?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),_=ie(p,r,"currentColor",1);return _&&(_.style.display="block",M.appendChild(_)),L.appendChild(M),Ot({anchor:M,trigger:L,text:()=>M.getAttribute("aria-label")??R,enabled:B}),{button:M,wrapper:L}};var Qt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=e=>{let{config:t,showClose:n=!0}=e,o=Be("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Be("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let _=parseFloat(s)||24,G=ie(p,_*.6,"currentColor",1);G?d.replaceChildren(G):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let _=h("img");_.src=t.launcher.iconUrl,_.alt="",_.className="persona-rounded-xl persona-object-cover",_.style.height=s,_.style.width=s,d.replaceChildren(_)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Be("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Qt.titleColor}}),w=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Qt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},v=f.enabled??!0,C=f.placement??"inline",R=null,B=null;if(v){let G=Ga(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});R=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:M}=Ka(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:E,closeButtonWrapper:M,clearChatButton:R,clearChatButtonWrapper:B}},ws=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Ih=e=>{let t=Ho({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Rh(e,t,n){if(t?.length)for(let o of t){let r=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ie(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let a=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Wh=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Rp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Qt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Qt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Rh(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let E=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||E()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),E())})}let L=r?.titleRowHover;L&&(d.style.borderRadius=L.borderRadius??"10px",d.style.padding=L.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=L.background??"",d.style.borderColor=L.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Qt.actionIconColor;let v=a.closeButtonIconName??"x",C=ie(v,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let R=h("div");R.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:R,headerTitle:c,headerSubtitle:B,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},tu={default:Ih,minimal:Wh},Hh=e=>tu[e]??tu.default,Qa=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=h("div");l.style.display="none";let p=h("span"),d=h("span"),c=h("button");c.style.display="none";let u=h("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Hh(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Xa=e=>{let t=h("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ja=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",w=t.backgroundColor,f=t.textColor,v=h("div","persona-send-button-wrapper"),C=Be("button",{className:Dn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&w||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),R=null,B=null;if(n){let M=parseFloat(u)||24,_=f?.trim()||"currentColor";r?(R=ie(r,M,_,2),R?C.appendChild(R):C.textContent=o):C.textContent=o,B=ie(s,M,_,2)}else C.textContent=p;C.setAttribute("aria-label",a),v.appendChild(C),Ot({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let L="send";return{button:C,wrapper:v,setMode:M=>{if(M===L)return;L=M;let _=M==="stop"?l:a;if(C.setAttribute("aria-label",_),n){if(R&&B){let G=M==="stop"?B:R;C.replaceChildren(G)}}else C.textContent=M==="stop"?d:p}}},Ya=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,w=h("div","persona-send-button-wrapper"),f=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ie(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let R=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return Ot({anchor:f,trigger:w,text:()=>f.getAttribute("aria-label")??R,enabled:B}),{button:f,wrapper:w}},Za=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??_n).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=h("div","persona-send-button-wrapper"),c=Be("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ie(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},ei=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=h("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=h("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ti=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ni=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=ti(),r=Be("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Xa(t);a();let l=Ja(t),p=Ya(t),d=Za(t),c=ei(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Be("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:f,setSendButtonMode:l.setMode}};var nu=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=h("span","persona-pill-peek__icon"),n=ie("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=ie("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ou=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ti(),r=ei(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Xa(t);s.style.maxHeight="100px",a();let l=Ja(t),p=Ya(t),d=Za(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Be("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var ru=e=>{let t=e?.launcher?.enabled??!0,n=Dt(e);if(vs(e)){let c=e?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Vt);let w=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Vt),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Cn[r.position]?Cn[r.position]:Cn["bottom-right"],a=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??$n;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},Bh=(e,t)=>{let n=h("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Ka(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let M=Ga(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=M.button,l=M.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Be("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u),f=h("div","persona-flex persona-flex-col persona-gap-3"),v=e?.layout?.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let R=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),B=ou({config:e}),{root:L,textNode:E}=nu();return n.append(p,r,d,R),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:R,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:p,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:L,peekTextNode:E}},su=(e,t=!0)=>{if(vs(e))return Bh(e,t);let n=Be("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Qa(e,o,{showClose:t}):Ho({config:e,showClose:t}),a=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let l=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Dt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=h("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=ni({config:e}),v=e?.layout?.showFooter!==!1;r?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let C=Be("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var xl=(e,t)=>{let n=h("button");n.type="button",n.innerHTML=`
|
|
29
|
+
`)),n=b("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Gu(e,t,n){let o=e.length<=Ey?ky(t,n):null,r=o?Dy(e,o):[{type:"plain",value:e}];return Fy(r)}function Dr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,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(Za)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let 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",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let T=ae(g.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let C=document.createElement("span");C.textContent=g.label,v.appendChild(C),v.addEventListener("click",T=>{T.stopPropagation(),c(),n(g.id)}),a.appendChild(v)}let l=null;function u(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function f(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:f,destroy:w}}function Wt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,u=b("button","persona-icon-btn"+(s?" "+s:""));u.type="button",u.setAttribute("aria-label",n),u.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&u.appendChild(d),a&&u.addEventListener("click",a),l)for(let[c,f]of Object.entries(l))u.setAttribute(c,f);return u}function Qo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:u}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=b("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ae(t,s??14,"currentColor",2);w&&c.appendChild(w)}let f=b("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),u)for(let[w,g]of Object.entries(u))c.setAttribute(w,g);return c}function ii(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=b("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function u(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let f;c.icon?f=Wt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,u(),o(c.id)}}):(f=b("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{a=c.id,u(),o(c.id)})),f.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:f}),s.appendChild(f)}function d(c){a=c,u()}return{element:s,setSelected:d}}function Yu(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:u}=e,d=b("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=b("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),u&&(d.style.borderRadius=u.borderRadius??"10px",d.style.padding=u.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=u.background??"",d.style.borderColor=u.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=Dr({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",g=>{g.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let g=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var li="persona-artifact-custom-action-btn";function Fr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+li+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+li+(n?" persona-artifact-doc-icon-btn":"");o=b("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Qo({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-copy-btn":"")}):o=Wt({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Fs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Xu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Bn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Co(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...u?{presentation:u}:{}},B=Br(T,C,"card");Xo(v,B,C)}else s&&Hr(s),v.textContent=d;if(w.append(g,v),c.append(f,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let S of C)try{if(S.visible===void 0||S.visible(B)){let k=Fr(S);k.setAttribute("data-artifact-custom-action",S.id),k.className=`${k.className} persona-flex-shrink-0`,c.append(k)}}catch{}}let T=Qo({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),c.append(T)}return c}var ci=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Xu(e,t)});if(l)return l}return Xu(e,t)};var So=new WeakMap;function tc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=So.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function tf(e){return So.has(e)}function Oy(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Qu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Bn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Co(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ny(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Ju=180,_y=240,$y=.8,Uy=300,zy=500,jy="cubic-bezier(0.2, 0, 0, 1)",Zu=240,Vy=.35;function qy(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Ju,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let u=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!u||Math.abs(u-t)<1){l(),r();return}let d=Math.abs(t-u),c=Math.round(Math.min(zy,Math.max(Uy,_y+d*$y))),f=Math.round(c*Vy),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=w?w.animate([{opacity:0},{opacity:1}],{duration:Zu,delay:f,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${u}px`}],{duration:c,easing:jy});e.style.height=`${u}px`;let C=!1,T=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,g?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+Zu)+120)},Ju)}function Ky(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Os="--persona-artifact-inline-body-height";function Gy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",u=l==="clip"?!1:t?.followOutput!==!1,d,c,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:u,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:g}}function ef(e,t){let n=Oy(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Ky(o),u=o?.inlineActions??[],d=Gy(o),c=d.completeDisplay==="card",f=null,w=n,g=b("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let v=Z=>ci(Ny(Z),t),C=Z=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Os),g.replaceChildren(v(Z)),So.set(g,pe=>{g.replaceChildren(v(pe))})};if(c&&n.status==="complete")return C(n),g;let T=di(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),B=b("div","persona-artifact-inline-body");B.appendChild(T.el);let S=Z=>{let pe=Z.status!=="complete",ee=pe?d.streamingHeight:d.completeHeight,me=typeof ee=="number";me?g.style.setProperty(Os,`${ee}px`):g.style.removeProperty(Os);let we=!!T.el.querySelector(".persona-code-pre"),he=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",we),B.classList.toggle("persona-artifact-inline-body--sized",me&&he),B.classList.toggle("persona-artifact-inline-body--cap",!pe&&!he&&typeof d.completeHeight=="number")},k=n.status,P=(Z,pe)=>{k!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Os,`${d.completeHeight}px`):g.style.removeProperty(Os),of(B,pe?.suppressTransition?"none":d.transition,Z.id,()=>{T.update(Z),S(Z)})):T.update(Z),S(Z),k=Z.status};S(n);let H=d.overflow==="clip"&&a&&!!n.id;if(H&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Qu(n).title} in panel`)),!r)return g.appendChild(B),So.set(g,P),g;let F=b("div","persona-artifact-inline-chrome");F.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let N=b("div","persona-artifact-inline-chrome-lead"),z=b("span","persona-flex persona-items-center persona-flex-shrink-0"),j=ae("file-text",16,"currentColor",2);j&&z.appendChild(j);let te=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),A=b("span","persona-artifact-inline-type");N.append(z,te,A);let G=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),ie=()=>f??d.viewMode,Y=l?ii({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:ie(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let pe=Z==="source"?"source":"rendered";pe!==ie()&&(f=pe,T.update(w),S(w))}}):null,ue=s?Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ue&&n.id&&ue.setAttribute("data-copy-artifact",n.id);let X=a?Wt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;X&&n.id&&X.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),Y&&G.appendChild(Y.element),ue&&G.appendChild(ue),X&&G.appendChild(X),F.append(N,G),g.append(F,B);let ge=Z=>{let{title:pe,typeLabel:ee}=Qu(Z);te.textContent=pe,te.title=pe,H&&B.setAttribute("aria-label",`Open ${pe} in panel`);let me=Z.status!=="complete";if(me){A.classList.contains("persona-artifact-inline-status")||(A.className="persona-artifact-inline-status",A.removeAttribute("data-preserve-animation"),A.replaceChildren());let we=Br(Z,o,"inline-chrome");Xo(A,we,o)}else Hr(Z.id),A.className="persona-artifact-inline-type",A.removeAttribute("data-preserve-animation"),A.replaceChildren(),A.textContent=ee;if(ue&&ue.classList.toggle("persona-hidden",me),Y){let we=Z.artifactType==="markdown"?Z.file:void 0,he=!1;if(!me&&we&&d.viewMode!=="source"){let ke=Yo(we);ke==="markdown"?he=!0:(ke==="html"||ke==="svg")&&(he=o?.filePreview?.enabled!==!1)}Y.element.classList.toggle("persona-hidden",!he),Y.setSelected(ie())}if(Q.replaceChildren(),!me&&u.length>0){let we=Fs(Z);if(we)for(let he of u)try{if(he.visible===void 0||he.visible(we)){let ke=Fr(he,{documentChrome:!0});ke.setAttribute("data-artifact-custom-action",he.id),ke.classList.add("persona-flex-shrink-0"),Q.appendChild(ke)}}catch{}}};return ge(n),So.set(g,(Z,pe)=>{if(c&&k!=="complete"&&Z.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;k="complete";let me=Z,we=!1,he=ke=>{me=ke,we=!0};So.set(g,he),qy(g,ee,{swap:()=>{C(me),we=!1,So.set(g,he)},onSettled:()=>{we?C(me):So.set(g,ke=>{g.replaceChildren(v(ke))})}});return}(Z.status!=="complete"||Z.id!==w.id)&&(f=null),w=Z,P(Z,pe),ge(Z)}),g}var nf=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>ef(e,t)});if(l)return l}return ef(e,t)};var nc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Zn=new nc;Zn.register("PersonaArtifactCard",ci,{bubbleChrome:!1});Zn.register("PersonaArtifactInline",nf,{bubbleChrome:!1});function Ns(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ri(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var oc=!1;function Yy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function of(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||oc||s){o();return}oc=!0;let a=Yy(n);e.style.setProperty("view-transition-name",a);let l=()=>{oc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Xy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Qy="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Jy(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Zy(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var eb=220;function tb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function nb(e){return`
|
|
30
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function ob(e,t,n){let o=b("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=b("div","persona-artifact-frame-loading-indicator");r.appendChild($u());let s=null;return n.label!==!1&&(s=b("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 rb(e,t,n,o,r,s){let a=null,l=0,u=!1,d=new Set,c=()=>{d.forEach(k=>clearTimeout(k)),d.clear()},f=(k,P)=>{let H=setTimeout(()=>{d.delete(H),k()},P);d.add(H)},w=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||u)return;let k=ob(r,s,o);a=k.el,e.appendChild(a),l=Date.now(),o.label!==!1&&f(k.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),f(w,eb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",S)},T=()=>{if(u||(u=!0,C(),c(),!a))return;let k=Math.max(0,o.minVisibleMs-(Date.now()-l));k>0?f(v,k):v()};function B(k){if(n===null)return;let P=k.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||k.source===t.contentWindow&&T()}function S(){let k=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};k(()=>k(()=>T()))}return f(g,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",S),()=>{u=!0,c(),C(),w()}}function di(e,t){let{config:n}=t,o=t.registry??Zn,r=t.bodyLayout,s=n.markdown?Ba(n.markdown):null,a=Da(n.sanitize),l=e,u=!1,d=X=>{let ge=Gn()!==null;s&&!ge&&!u&&(u=!0,Ha(()=>ue(l)));let Z=s?s(X):mo(X);return s&&ge&&a?a(Z):Z},c=b("div","persona-artifact-preview-body"),f=null,w=null,g=null,v=()=>{g&&(g(),g=null),f=null,w=null},C=null,T=null,B=null,S=!1,k=()=>{C=null,T=null,B=null,S=!1},P=null,H=null,F=()=>{P=null,H=null},N=40,z=0,j=X=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>X()):setTimeout(X,0),te=X=>X.scrollHeight-X.clientHeight-X.scrollTop<=N,A=X=>{if(!r)return;let ge=X.scrollHeight-X.clientHeight>1,Z=X.scrollHeight-X.clientHeight-X.scrollTop;X.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&X.scrollTop>1),X.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Z>1)},G=X=>{z||(z=j(()=>{z=0,X.scrollTop=X.scrollHeight,A(X)}))},Q=(X,ge,Z,pe)=>{let ee=!!r,me=Z.id+"|"+(ee?"w":"p");if(!C||B!==me||C.parentElement!==c){v(),F(),c.replaceChildren();let ke=b("pre",Xy+" persona-code-pre"),Ne=b("code","persona-code");if(ke.appendChild(Ne),ee){let Ue=b("div","persona-artifact-source-window");if(Ue.appendChild(ke),c.appendChild(Ue),!(r?.overflow==="clip")&&typeof Ue.addEventListener=="function"){let Oe=()=>Ue.scrollHeight-Ue.clientHeight>1;Ue.addEventListener("scroll",()=>{te(Ue)&&(S=!1),A(Ue)},{passive:!0}),Ue.addEventListener("wheel",_e=>{Oe()&&_e.deltaY<0&&(S=!0)},{passive:!0}),Ue.addEventListener("touchmove",()=>{Oe()&&(S=!0)},{passive:!0})}C=Ue}else c.appendChild(ke),C=ke;T=Ne,B=me}let we=ee?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",pe),we.classList.toggle("persona-artifact-source-window--clip",pe&&r?.overflow==="clip"));let he=we?te(we):!0;if(T.replaceChildren(Gu(X,ge?.language,ge?.path)),we){let ke=Z.status!=="complete";pe&&ke&&r?.followOutput&&!S&&he?G(we):ke||(S=!1),A(we)}},ie=X=>{v(),k(),F(),c.replaceChildren();let ge=b("div",Qy);ge.innerHTML=d(X),c.appendChild(ge)},Y=X=>{let ge=X.id,Z=n.features?.artifacts,pe=Br(X,Z,"status-body");if(P&&H===ge&&P.parentElement===c){let we=P.querySelector(".persona-artifact-status-view-text");we&&Xo(we,pe,Z);return}v(),k(),c.replaceChildren();let ee=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");Xo(me,pe,Z),ee.appendChild(me),c.appendChild(ee),P=ee,H=ge},ue=X=>{l=X;let ge=t.resolveViewMode?.(X)??r?.viewMode??"rendered",Z=X.artifactType==="markdown"?X.file:void 0,pe=X.status!=="complete";pe||Hr(X.id);let ee=pe?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&pe){Y(X);return}if(Z){let he=ri(X.markdown??""),ke=Yo(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!pe&&ge==="rendered"&&Ne&&(ke==="html"||ke==="svg")){let Qe=X.id+"\0"+he;if(f&&w===Qe&&f.parentElement===c)return;k(),F(),v(),c.replaceChildren();let Oe=n.features?.artifacts?.filePreview,_e=Oe?.iframeSandbox??"allow-scripts";!Oe?.dangerouslyAllowSameOrigin&&_e.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),_e=_e.split(/\s+/).filter(gt=>gt&>!=="allow-same-origin").join(" "));let Ae=Zy(Oe?.loading),Se=b("div","persona-artifact-frame"),ze=b("iframe","persona-artifact-iframe");ze.setAttribute("sandbox",_e),ze.setAttribute("data-artifact-id",X.id);let Gt=null;Ae.enabled&&Ae.injectReadySignal?(Gt=tb(),ze.srcdoc=he+nb(Gt)):ze.srcdoc=he,Se.appendChild(ze),c.appendChild(Se),Ae.enabled&&(g=rb(Se,ze,Gt,Ae,X.id,n)),f=Se,w=Qe;return}if(v(),!pe&&ke==="markdown"&&ge==="rendered"){ie(he);return}Q(he,{language:Z.language,path:Z.path},X,me);return}if(X.artifactType==="markdown"){if(ge==="source"){v(),Q(X.markdown??"",void 0,X,me);return}ie(X.markdown??"");return}v(),k(),F(),c.replaceChildren();let we=X.component?o.get(X.component):void 0;if(we){let ke={message:{id:X.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=we(X.props??{},ke);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Jy(X))};return ue(e),{el:c,update(X){ue(X)}}}import{Idiomorph as sb}from"idiomorph";var pi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;sb.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var rf=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var rc={index:-1,draft:""};function sf(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function af(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function lf(){return new Map}function cf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function df(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function uf(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function ui(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Dn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function eo(e,t){return Dn(e)-e.scrollTop<=t}function fi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&u&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function gi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function ff(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sc(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function gf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var _s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ab=["pre","code","a","script","style"],mi=e=>({type:e?.type??_s.type,placeholder:e?.placeholder??_s.placeholder,speed:e?.speed??_s.speed,duration:e?.duration??_s.duration,buffer:e?.buffer??_s.buffer}),ib=[{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"}],hf=new Map;for(let e of ib)hf.set(e.name,e);var Or=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:hf.get(e)??null,hi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
+
`);return s<0?"":e.slice(0,s)}return e},lb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},cb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},ac=/\s/,db=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(ac.test(s[l])){let u=l;for(;u<s.length&&ac.test(s[u]);)u+=1;a.appendChild(o.createTextNode(s.slice(l,u))),l=u}else{let u=o.createElement("span");u.className="persona-stream-word-group";let d=l;for(;d<s.length&&!ac.test(s[d]);)u.appendChild(lb(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(u),l=d}r.replaceChild(a,e)},ub=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let u of l)u&&(/^\s+$/.test(u)?a.appendChild(o.createTextNode(u)):(a.appendChild(cb(o,u,t,n.value)),n.value+=1));r.replaceChild(a,e)},$s=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ab).map(f=>f.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],u=a.nextNode();for(;u;)db(u,s)||l.push(u),u=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?pb:ub;for(let f of l)c(f,n,d);return r.innerHTML},yi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Us=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},mf=new WeakMap,fb=(e,t)=>{if(!e.styles)return;let n=mf.get(t);if(n||(n=new Set,mf.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},ic=new WeakMap,gb=(e,t)=>{if(!e.onAttach)return;let n=ic.get(t);if(n||(n=new Map,ic.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},yf=e=>{let t=ic.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},bi=(e,t)=>{fb(e,t),gb(e,t)};function lc(e,t=Nt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var zs=0,To=null;function cc(e=document){if(zs++,zs===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;To={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,zs=Math.max(0,zs-1),zs===0&&To)){let n=e.body,o=e.defaultView??window;n.style.overflow=To.originalOverflow,n.style.position=To.originalPosition,n.style.top=To.originalTop,n.style.width=To.originalWidth,o.scrollTo(0,To.scrollY),To=null}}}var js={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=e=>(e?.launcher?.mountMode??"floating")==="docked",Vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",vn=e=>{let t=e?.launcher?.dock;return{side:t?.side??js.side,width:t?.width??js.width,animate:t?.animate??js.animate,reveal:t?.reveal??js.reveal,maxHeight:t?.maxHeight??js.maxHeight}};var dc=e=>e==="followUp"?"follow-up":e,pc=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},mb=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},bf=new WeakSet,hb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yb=e=>{hb()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},uc=e=>{var S,k,P;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:u,chipsConfig:d,session:c,getTextarea:f,eventTarget:w}=e,g=o==="followUp",v=t.behavior,C=()=>{if(c.isStreaming())return;let H={suggestion:{...t},surface:o,source:r,behavior:v},F=w.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:H,bubbles:!0,composed:!0,cancelable:!0}));if(g&&w.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!F)return;for(let z of u)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let N=f();if(v==="fill"){N.value=t.prompt,N.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),N.focus();return}N.value="",c.sendMessage(t.prompt)},T=()=>{let H=b("button",`persona-suggestion persona-suggestion--${s}`);if(H.type="button",H.disabled=a,H.dataset.suggestionId=t.id,H.dataset.emphasis=t.emphasis,H.dataset.behavior=v,s==="chip"&&(d?.fontFamily&&(H.style.fontFamily=mb(d.fontFamily)),d?.fontWeight&&(H.style.fontWeight=d.fontWeight),d?.paddingX&&(H.style.paddingLeft=d.paddingX,H.style.paddingRight=d.paddingX),d?.paddingY&&(H.style.paddingTop=d.paddingY,H.style.paddingBottom=d.paddingY)),t.icon){let N=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);N&&(N.classList.add("persona-suggestion__icon"),t.iconColor&&(N.style.color=t.iconColor),H.appendChild(N))}let F=b("span","persona-suggestion__copy");if(F.appendChild(Ee("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&F.appendChild(Ee("span",{className:"persona-suggestion__description",text:t.description})),H.appendChild(F),s!=="chip"){let N=ae("arrow-right",16,"currentColor",1.8);N&&(N.classList.add("persona-suggestion__arrow"),H.appendChild(N))}return H.addEventListener("click",C),H},B=null;for(let H of u)if(H.renderSuggestion&&(B=H.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:T,select:C}),B))break;return B??(B=T()),(S=B.dataset).suggestionId||(S.suggestionId=t.id),(k=B.dataset).behavior||(k.behavior=v),(P=B.dataset).emphasis||(P.emphasis=t.emphasis),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",a?"true":"false"),B},qs=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let f=getComputedStyle(e).direction==="rtl",w=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),g=4,v=w<=g,C=w>=c-g,T=f?!C:!v,B=f?!v:!C;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",B)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return u?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),u?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,w,g,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let T=C?.source??"config",B=C?.surface??(T==="config"?"starter":"followUp"),S=B==="followUp",k=C?.variant??"chip",P=C?.behavior??"send",H=C?.overflow??"wrap",F=C?.config??{},N=C?.plugins??[],z=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,j=S?"followUps":"starters";!bf.has(F)&&F.debug===!0&&k!=="chip"&&F.suggestions?.[j]?.overflow!==void 0&&(bf.add(F),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${k}" variant manages its own stacking.`));let te=ue=>ue.map(pc).filter(X=>X!==null).map(X=>({...X,behavior:X.behavior??P})),A=te(c??[]);N.forEach(ue=>{ue.transformSuggestions&&(A=te(ue.transformSuggestions({suggestions:A.map(X=>({...X})),surface:B,source:T,config:F})))});let G=z===void 0?A:A.slice(0,z);if(!G.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(X=>X.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=dc(B),e.dataset.variant=k,e.dataset.overflow=H;let Q=document.createDocumentFragment(),ie=f.isStreaming();G.forEach((ue,X)=>{let ge=uc({item:ue,index:X,surface:B,source:T,variant:k,streaming:ie,config:F,plugins:N,chipsConfig:v,session:f,getTextarea:()=>w,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(pe=>{t.includes(pe)||(pe.disabled=ie,t.push(pe))})}),e.appendChild(Q),a(),l();let Y=JSON.stringify({normalized:G,surface:B,variant:k,source:T});Y!==o&&(o=Y,yb(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(ue=>({...ue})),surface:B,source:T,variant:k},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(ue=>ue.prompt)},bubbles:!0,composed:!0})))}}};var ln={"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 bb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",vi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=bb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",u=b("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,f=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ae(f,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,u.appendChild(v),_t({anchor:v,trigger:u,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:u}},vb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wi=(e,t={})=>{let{wrapperClassName:n=vb,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",u=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",f=a.borderWidth??"",w=a.borderColor??"",g=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",T=a.tooltipText??"Clear chat",B=a.showTooltip??!0,S=b("div",n),k=!!(f||w),P=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:k?`${f||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),H=ae(u,r,"currentColor",1);return H&&(H.style.display="block",P.appendChild(H)),S.appendChild(P),_t({anchor:P,trigger:S,text:()=>P.getAttribute("aria-label")??T,enabled:B}),{button:P,wrapper:S}};var Kt={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))"},fc={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},wb={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Jo=e=>{let{config:t,showClose:n=!0}=e,o=Ee("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,u=r.headerIconName,d=Ee("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(u){let H=parseFloat(s)||24,F=ae(u,H*.6,"currentColor",1);F?d.replaceChildren(F):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let H=b("img");H.src=t.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=s,H.style.width=s,d.replaceChildren(H)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Ee("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor,...fc}}),w=Ee("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor,...wb}});c.append(f,w),l?o.append(c):o.append(d,c);let g=r.clearChat??{},v=g.enabled??!0,C=g.placement??"inline",T=null,B=null;if(v){let F=wi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=F.button,B=F.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:P}=vi(t,{showClose:n,wrapperClassName:S});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:w,closeButton:k,closeButtonWrapper:P,clearChatButton:T,clearChatButtonWrapper:B}},Ks=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var xb=e=>{let t=Jo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Cb(e,t,n){if(t?.length)for(let o of t){let r=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Kt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=b("div","persona-relative");s.appendChild(r);let a=Dr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Ab=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=r?.titleMenu,d,c;if(u)d=Yu({label:a.title??"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=b("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,Object.assign(c.style,fc),c.textContent=a.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let P=r.onTitleClick;d.addEventListener("click",H=>{H.target.closest("button")||P()}),d.addEventListener("keydown",H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),P())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=a.closeButtonSize??"32px",w=b("div",""),g=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");g.style.height=f,g.style.width=f,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Kt.actionIconColor;let v=a.closeButtonIconName??"x",C=ae(v,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),w.appendChild(g);let T=b("div","persona-flex persona-items-center persona-gap-1");u||Cb(T,r?.trailingActions,r?.onAction??s),T.appendChild(w),l.appendChild(T);let B=b("div");B.style.display="none";let S=b("span");return S.style.display="none",{header:l,iconHolder:B,headerTitle:c,headerSubtitle:S,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},vf={default:xb,minimal:Ab},Sb=e=>vf[e]??vf.default,xi=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=b("div");l.style.display="none";let u=b("span"),d=b("span"),c=b("button");c.style.display="none";let f=b("div");return f.style.display="none",{header:a,iconHolder:l,headerTitle:u,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Sb(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ci=e=>{let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let u=t.ownerDocument?.defaultView;if(!u?.getComputedStyle)return o;let d=u.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let u=t.style.maxHeight;if(u!==s){let c=parseFloat(u);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let u=Math.min(t.scrollHeight,a());t.style.height=`${u}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},Ai=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",u=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,f=t.size??"40px",w=t.backgroundColor,g=t.textColor,v=b("div","persona-send-button-wrapper"),C=Ee("button",{className:Pn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&w||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,B=null;if(n){let P=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),H=t.iconStrokeWidth??2,F=g?.trim()||"currentColor";r?(T=ae(r,P,F,H),T?C.appendChild(T):C.textContent=o):C.textContent=o,B=ae(s,P,F,H)}else C.textContent=u;C.setAttribute("aria-label",a),v.appendChild(C),_t({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let S="send";return{button:C,wrapper:v,setMode:P=>{if(P===S)return;S=P;let H=P==="stop"?l:a;if(C.setAttribute("aria-label",H),n){if(T&&B){let F=P==="stop"?B:T;C.replaceChildren(F)}}else C.textContent=P==="stop"?d:u}}},Si=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",u=t.iconSize??a,d=parseFloat(u)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,w=b("div","persona-send-button-wrapper"),g=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:u,height:u,minWidth:u,minHeight:u,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ae(l,d,f||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",w.appendChild(g);let T=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return _t({anchor:g,trigger:w,text:()=>g.getAttribute("aria-label")??T,enabled:B}),{button:g,wrapper:w}},Ti=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Qn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,u=Math.round(l*.6),d=b("div","persona-send-button-wrapper"),c=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),f=ae(s,u,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return _t({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},Mi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=b("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Ei=()=>Ee("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Gs=e=>{let{config:t}=e,n=Ee("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=Ei(),r=Ee("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ci(t);a();let l=Ai(t),u=Si(t),d=Ti(t),c=Mi(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let f=Ee("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),u&&g.append(u.wrapper),g.append(l.wrapper),f.append(w,g),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.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:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:w,rightActions:g,setSendButtonMode:l.setMode}};var wf=()=>{let e=Ee("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ki=e=>{let{config:t}=e,n=Ee("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ei(),r=Mi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ci(t);s.style.maxHeight="100px",a();let l=Ai(t),u=Si(t),d=Ti(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ee("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let w=b("div","persona-widget-composer__right-actions persona-pill-composer__right");u&&w.append(u.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(f,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:f,rightActions:w,setSendButtonMode:l.setMode}};var Tb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Mb=(e,t)=>{if(!e)return null;let n=Tb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Eb=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},kb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},gc=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},mc=320,Sf=320,Lb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Pb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Rb=e=>{if(!e||e.length===0)return null;let t=Ee("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ee("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=b("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ee("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Hb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Hs(o.ref,{readonly:!0,render:t}))}return n},xf="\uE000",Cf="\uE001",Bb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${xf}${r}:${w}${Cf}`,a=t.map((w,g)=>w.kind==="text"?w.text:s(g)).join(""),l=n(a);if(!t.every((w,g)=>w.kind==="text"||l.includes(s(g)))){e.replaceChildren(Hb(t,o));return}e.innerHTML=l;let d=new RegExp(`${xf}${r}:(\\d+)${Cf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let w=c.nextNode();w;w=c.nextNode())f.push(w);for(let w of f){let g=w;for(let v=d.exec(g.data);v;v=d.exec(g.data)){let C=t[Number(v[1])],T=g.splitText(v.index);T.data=T.data.slice(v[0].length),C?.kind==="mention"&&T.parentNode?.insertBefore(Hs(C.ref,{readonly:!0,render:o}),T),g=T}}},Db=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,u)=>{let d=b("img");d.alt=l.alt?.trim()||`Attached image ${u+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${mc}px`,d.style.maxHeight=`${Sf}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}),kb(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}},Fb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!gc(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ob=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!gc(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,r.style.maxHeight=`${Sf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!gc(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ys=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},_b=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},$b=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Af=(e,t,n="div")=>{let o=b(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Xs=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Ub=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=b("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",u=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[u],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let g=(v,C,T)=>{let B=Wt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",T),B};return o&&w.appendChild(g("copy","Copy message","copy")),a&&w.appendChild(g("volume-2","Read aloud","read-aloud")),r&&w.appendChild(g("thumbs-up","Upvote","upvote")),s&&w.appendChild(g("thumbs-down","Downvote","downvote")),w},hc=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",u=a.avatar,d=a.timestamp,c=u?.show??!1,f=d?.show??!1,w=u?.position??"left",g=d?.position??"below",v=Xs(e.role,l),C=b("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Lb(e),B=e.content?.trim()??"",k=T.length>0&&B===Ga,P=mi(s?.widgetConfig?.features?.streamAnimation),H=s?.widgetConfig?.features?.streamAnimation?.plugins,F=e.role==="assistant"&&P.type!=="none"?Or(P.type,H):null,N=e.role==="assistant"&&F?.isAnimating?.(e)===!0,z=e.role==="assistant"&&F!==null&&(!!e.streaming||N);z&&F?.bubbleClass&&C.classList.add(F.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),z&&F&&(F.containerClass&&j.classList.add(F.containerClass),j.style.setProperty("--persona-stream-step",`${P.speed}ms`),j.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let te=z?hi(e.content??"",P.buffer,F,e,!!e.streaming):e.content??"",A=()=>{let ee=t({text:te,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&F?.wrap==="char"?$s(ee,"char",e.id,{skipTags:F.skipTags}):z&&F?.wrap==="word"?$s(ee,"word",e.id,{skipTags:F.skipTags}):ee},G=null;if(k?(G=document.createElement("div"),G.innerHTML=A(),G.style.display="none",j.appendChild(G)):e.contentSegments?.length?Bb(j,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):j.innerHTML=A(),z&&F?.useCaret&&!k&&B){let ee=yi(),me=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=me[me.length-1];if(we?.parentNode)we.parentNode.insertBefore(ee,we.nextSibling);else{let he=j.lastElementChild;he?he.appendChild(ee):j.appendChild(ee)}}if(f&&g==="inline"&&e.createdAt){let ee=Af(e,d,"span");ee.classList.add("persona-timestamp-inline");let me=j.lastElementChild;me?me.appendChild(ee):j.appendChild(ee)}if(T.length>0){let ee=Db(T,!k&&!!B,()=>{k&&G&&(G.style.display="")});ee?C.appendChild(ee):k&&G&&(G.style.display="")}let Q=Pb(e);if(Q.length>0){let ee=Fb(Q);ee&&C.appendChild(ee)}let ie=Ib(e);if(ie.length>0){let ee=Ob(ie);ee&&C.appendChild(ee)}let Y=Wb(e);if(Y.length>0){let ee=Nb(Y);ee&&C.appendChild(ee)}let ue=e.contentSegments?.length?null:Rb(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(j),f&&g==="below"&&e.createdAt){let ee=Af(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let X=e.role==="assistant"?Mb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(te&&te.trim()),me=P.placeholder==="skeleton",we=me&&P.buffer==="line"&ⅇif(ee)we&&C.appendChild(Us());else if(me)C.appendChild(Us());else{let he=_b("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(X&&e.stopReason&&!e.streaming&&(B||(j.style.display="none"),C.appendChild(Eb(e.stopReason,X))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Ub(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),pe=$b(u,e.role);return w==="right"||w==="left"&&e.role==="user"?Z.append(C,pe):Z.append(pe,C),Z};var zb=40,jb=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ae(t.name,zb);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Ee("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Ee("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Tf=(e,t,n={})=>{let o=Ee("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=b("h2","persona-welcome-title"),s=b("p","persona-welcome-subtitle");return{host:Ee("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},Nr=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Pi=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",jb(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Vb="data-persona-welcome-plugin",Mf="data-persona-welcome-overlay",Li="persona-welcome-overlay-active",yc=new WeakMap,Ef=(e,t,n)=>{n.setAttribute(Vb,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Mf,""),e.classList.contains(Li)||(yc.set(e,e.scrollTop),e.classList.add(Li),e.scrollTop=0)},kf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Mf),e.classList.contains(Li)&&(e.classList.remove(Li),e.scrollTop=yc.get(e)??e.scrollTop,yc.delete(e))},Lf=()=>{let e=Ee("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Ii=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Ee("div",{className:Xs("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Ee("div",{className:"persona-flex"},r)),e.hidden=!1},qb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Pf=(e,t)=>{if(qb()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Kb="Hello \u{1F44B}",Gb="I can answer questions and help you get things done here.",If=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,Yb=(e,t)=>{!e||e.debug!==!0||!t.length||If.has(e)||(If.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Zo=e=>{let t=e?.welcome,n=e?.copy,o=wn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":wn(t,"dismiss")?t.dismiss:"never",s=[];return wn(t,"title")&&wn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(t,"subtitle")&&wn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(t,"variant")&&wn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&wn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&wn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),Yb(e,s),{title:wn(t,"title")?t.title:n?.welcomeTitle??Kb,subtitle:wn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??Gb,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},_r=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Wf=e=>{let t=e?.launcher?.enabled??!0,n=Rt(e);if(Vs(e)){let c=e?.launcher?.composerBar??{},f=b("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Nt);let w=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",f.appendChild(w);let g=b("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Nt),{wrapper:f,panel:w,pillRoot:g}}if(n){let c=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},s=r.position&&ln[r.position]?ln[r.position]:ln["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Nt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??Jn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},bc=e=>{let t=Ee("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":dc(e)}});return t.hidden=!0,t},Rf=(e,t)=>{let n=bc("starter"),o=Tf(e,n,{flatShadow:Rt(e)}),r=Zo(e);Pi(o,r),Nr(t,o.host,_r(r,e?.initialMessages));let s=Lf();return Ii(s,r.message,e),{welcome:o,greetingHost:s}},Xb=(e,t)=>{let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=vi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let N=wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=N.button,l=N.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let u=Ee("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ee("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:f}=Rf(e,d),{host:w,title:g,subtitle:v}=c,C=c.starterSuggestions,T=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),B=bc("followUp"),S=xo(e,!0);S&&(T.style.maxWidth=S,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(w,f,T,B);let k=Ee("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"}}),P=ki({config:e}),{root:H,textNode:F}=wf();return n.append(u,r,d,k),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:C,transcriptSuggestions:B,composerOverlay:k,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,welcomeHost:w,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:g,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:u,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:H,peekTextNode:F}},Hf=(e,t=!0)=>{if(Vs(e))return Xb(e,t);let n=Ee("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?xi(e,o,{showClose:t}):Jo({config:e,showClose:t}),a=Ee("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{welcome:l,greetingHost:u}=Rf(e,a),{host:d,title:c,subtitle:f}=l,w=l.starterSuggestions,g=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),v=bc("followUp"),C=xo(e,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(d,u,g,v);let T=Gs({config:e}),B=e?.layout?.showFooter!==!1;r?Ks(n,s,e):(s.header.style.display="none",Ks(n,s,e)),n.append(a);let S=Ee("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 B||(T.footer.style.display="none"),n.append(T.footer),n.append(S),{container:n,body:a,messagesWrapper:g,starterSuggestions:w,transcriptSuggestions:v,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:u,introTitle:c,introSubtitle:f,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var vc=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
32
32
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
33
33
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
34
34
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -36,14 +36,14 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
36
36
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
37
37
|
</span>
|
|
38
38
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
39
|
-
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Dt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let E=a.title??"Chat Assistant";p.textContent=E,p.setAttribute("title",E)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let E=a.subtitle??"Here to help you get answers fast";d.textContent=E,d.setAttribute("title",E)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let E=a.agentIconSize??"40px";if(u.style.height=E,u.style.width=E,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let M=parseFloat(E)||24,_=ie(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",2);_?(u.appendChild(_),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let E=a.agentIconSize??"40px";w.style.height=E,w.style.width=E,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let E=a.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let M=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,M=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",a.callToActionIconName){let _=parseFloat(E)||24,G=Math.max(_-M,8),x=ie(a.callToActionIconName,G,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&Cn[a.position]?Cn[a.position]:Cn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",R="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?R:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??Vt));let B="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??B,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var au=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=ru(e),s=su(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},Cl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>xl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=xl(e,n);return{instance:r,element:r.element}};var Dh=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Fh=(e,t)=>{if(!e)return null;let n=Dh(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Nh=(e,t)=>{let n=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Oh=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Al=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Sl=320,du=320,_h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$h=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),zh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),jh=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uh=e=>{if(!e||e.length===0)return null;let t=Be("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Be("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Vh=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(is(o.ref,{readonly:!0,render:t}))}return n},iu="\uE000",lu="\uE001",qh=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${iu}${r}:${w}${lu}`,a=t.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!t.every((w,f)=>w.kind==="text"||l.includes(s(f)))){e.replaceChildren(Vh(t,o));return}e.innerHTML=l;let d=new RegExp(`${iu}${r}:(\\d+)${lu}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let f=w;for(let v=d.exec(f.data);v;v=d.exec(f.data)){let C=t[Number(v[1])],R=f.splitText(v.index);R.data=R.data.slice(v[0].length),C?.kind==="mention"&&R.parentNode?.insertBefore(is(C.ref,{readonly:!0,render:o}),R),f=R}}},Kh=(e,t,n)=>{if(e.length===0)return null;try{let o=h("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=h("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Sl}px`,d.style.maxHeight=`${du}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),Oh(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Gh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Al(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Sl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Qh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Al(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Sl}px`,r.style.maxHeight=`${du}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Xh=e=>{if(e.length===0)return null;try{let t=h("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Al(o.data))return;let r=h("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},xs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Jh=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:xs};if(t){let r=t(o);if(r!==null)return r}return xs()},Yh=(e,t)=>{let n=h("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=h("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},cu=(e,t,n="div")=>{let o=h(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Tl=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Zh=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=h("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let f=(v,C,R)=>{let B=Pt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",R),B};return o&&w.appendChild(f("copy","Copy message","copy")),a&&w.appendChild(f("volume-2","Read aloud","read-aloud")),r&&w.appendChild(f("thumbs-up","Upvote","upvote")),s&&w.appendChild(f("thumbs-down","Downvote","downvote")),w},Ml=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",v=Tl(e.role,l),C=h("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let R=_h(e),B=e.content?.trim()??"",E=R.length>0&&B===Ca,M=ja(s?.widgetConfig?.features?.streamAnimation),_=s?.widgetConfig?.features?.streamAnimation?.plugins,G=e.role==="assistant"&&M.type!=="none"?mr(M.type,_):null,x=e.role==="assistant"&&G?.isAnimating?.(e)===!0,j=e.role==="assistant"&&G!==null&&(!!e.streaming||x);j&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),j&&G&&(G.containerClass&&U.classList.add(G.containerClass),U.style.setProperty("--persona-stream-step",`${M.speed}ms`),U.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let oe=j?Ua(e.content??"",M.buffer,G,e,!!e.streaming):e.content??"",F=()=>{let Y=t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent});return j&&G?.wrap==="char"?ms(Y,"char",e.id,{skipTags:G.skipTags}):j&&G?.wrap==="word"?ms(Y,"word",e.id,{skipTags:G.skipTags}):Y},$=null;if(E?($=document.createElement("div"),$.innerHTML=F(),$.style.display="none",U.appendChild($)):e.contentSegments?.length?qh(U,e.contentSegments,Y=>t({text:Y,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):U.innerHTML=F(),j&&G?.useCaret&&!E&&B){let Y=Va(),pe=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=pe[pe.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(Y,xe.nextSibling);else{let ye=U.lastElementChild;ye?ye.appendChild(Y):U.appendChild(Y)}}if(u&&f==="inline"&&e.createdAt){let Y=cu(e,d,"span");Y.classList.add("persona-timestamp-inline");let pe=U.lastElementChild;pe?pe.appendChild(Y):U.appendChild(Y)}if(R.length>0){let Y=Kh(R,!E&&!!B,()=>{E&&$&&($.style.display="")});Y?C.appendChild(Y):E&&$&&($.style.display="")}let X=$h(e);if(X.length>0){let Y=Gh(X);Y&&C.appendChild(Y)}let me=zh(e);if(me.length>0){let Y=Qh(me);Y&&C.appendChild(Y)}let he=jh(e);if(he.length>0){let Y=Xh(he);Y&&C.appendChild(Y)}let Ae=e.contentSegments?.length?null:Uh(e.contextMentions);if(Ae&&C.appendChild(Ae),C.appendChild(U),u&&f==="below"&&e.createdAt){let Y=cu(e,d);Y.classList.add("persona-mt-1"),C.appendChild(Y)}let Z=e.role==="assistant"?Fh(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Y=!!(oe&&oe.trim()),pe=M.placeholder==="skeleton",xe=pe&&M.buffer==="line"&&Y;if(Y)xe&&C.appendChild(hs());else if(pe)C.appendChild(hs());else{let ye=Jh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(Z&&e.stopReason&&!e.streaming&&(B||(U.style.display="none"),C.appendChild(Nh(e.stopReason,Z))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Y=Zh(e,o,r);C.appendChild(Y)}if(!c||e.role==="system")return C;let ee=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=Yh(p,e.role);return w==="right"||w==="left"&&e.role==="user"?ee.append(C,le):ee.append(le,C),ee};var hr=new Set,ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ty=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
-
`):""},
|
|
41
|
-
`);let r=
|
|
42
|
-
`):""},kl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},ry=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=oy(e,o?.previewMaxLines??3),a=n?qd(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=Zi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=Zi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},uu=(e,t,n)=>{let o=yr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ie(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Ll=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&yr.has(e.id),{summary:p,previewText:d,isActive:c}=ry(e,t),u=h("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let F=h("span","");return F.setAttribute("data-tool-elapsed",v),F.textContent=Zr(n),F},R=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Zr(n),createElapsedElement:C});typeof R=="string"&&R.trim()?(f.textContent=R,w.appendChild(f)):R instanceof HTMLElement?w.appendChild(R):(f.textContent=p,w.appendChild(f));let B=s.loadingAnimation??"none",L=o.activeTextTemplate,E=o.completeTextTemplate,M=c?L:E,_=R instanceof HTMLElement,G=(F,$)=>{f.textContent="";let X=n.name?.trim()||"tool",me=va(F,X),he=0;for(let Ae of me){let Z=Ae.styles.length>0?(()=>{let ce=h("span",Ae.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(ce),ce})():f;if(Ae.isDuration&&c)Z.appendChild(C());else{let ce=Ae.isDuration?Zr(n):Ae.text;$?he=co(Z,ce,he):Z.appendChild(document.createTextNode(ce))}}};if(!_)if(c&&B!=="none"){let F=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),B==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),M&&G(M,!1);else if(f.classList.add(`persona-tool-loading-${B}`),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),M)G(M,!0);else{let $=f.textContent||p;f.textContent="",co(f,$,0)}}else M&&G(M,!1);let x=null;if(a){x=h("div","persona-flex persona-items-center");let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(x),u.append(w,X)}else u.append(w);let j=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let F=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});ny(j,F)||(j.textContent=d),j.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,j),r;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(U.style.display=l?"":"none",o.contentBackgroundColor&&(U.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(U.style.color=o.contentTextColor),o.contentPaddingX&&(U.style.paddingLeft=o.contentPaddingX,U.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(U.style.paddingTop=o.contentPaddingY,U.style.paddingBottom=o.contentPaddingY),n.name){let F=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?F.style.color=o.contentTextColor:o.headerTextColor&&(F.style.color=o.headerTextColor),F.textContent=n.name,U.appendChild(F)}if(n.args!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let X=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.args),F.append($,X),U.appendChild(F)}if(n.chunks&&n.chunks.length){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let X=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=n.chunks.join(""),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&n.result!==void 0){let F=h("div","persona-space-y-1"),$=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let X=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",kl(X,o),X.textContent=io(n.result),F.append($,X),U.appendChild(F)}if(n.status==="complete"&&typeof n.duration=="number"){let F=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(F.style.color=o.contentTextColor),F.textContent=`Duration: ${n.duration}ms`,U.appendChild(F)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=ie(l?"chevron-up":"chevron-down",16,F,2);$?x.appendChild($):x.textContent=l?"Hide":"Show"}U.style.display=l?"":"none",j.style.display=l?"none":j.textContent||j.childNodes.length?"":"none"})(),r.append(u,j,U),r};var Bo=new Map,oi=e=>{let n=(e.startsWith(Nn)?e.slice(Nn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},fu=e=>e?.approval!==!1?e?.approval:void 0,gu=(e,t)=>{let n=fu(t)?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},mu=(e,t,n)=>{let o=fu(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ie(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},hu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=gu(e,n);mu(o,s,n),r.style.display=s?"":"none"};var ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=h("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=h("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ie(p,20,d,2);c&&l.appendChild(c);let u=h("div","persona-flex-1 persona-min-w-0"),w=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",w.appendChild(f),!r){let x=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");x.setAttribute("data-approval-status",n.status),n.status==="approved"?(x.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",x.style.color="var(--persona-palette-colors-success-700, #15803d)",x.textContent="Approved"):n.status==="denied"?(x.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",x.style.color="var(--persona-palette-colors-error-700, #b91c1c)",x.textContent="Denied"):n.status==="timeout"&&(x.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",x.style.color="var(--persona-palette-colors-warning-700, #b45309)",x.textContent="Timeout"),w.appendChild(x)}u.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Nn)?Gr(n.toolName):void 0,R=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,L=R||(B?n.description:`The assistant wants to use \u201C${C??oi(n.toolName)}\u201D.`),E=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=L,u.appendChild(E),n.reason){let x=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");x.setAttribute("data-approval-reason","true"),o?.reasonColor?x.style.color=o.reasonColor:o?.descriptionColor&&(x.style.color=o.descriptionColor);let j=h("span","persona-font-medium");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,x.appendChild(j),x.appendChild(document.createTextNode(n.reason)),u.appendChild(x)}let M=o?.detailsDisplay??"collapsed",_=!!n.description&&!B,G=_||!!n.parameters;if(M!=="hidden"&&G){let x=gu(e.id,t),j=h("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");j.type="button",j.setAttribute("data-expand-header","true"),j.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span");U.setAttribute("data-approval-details-label","true");let oe=h("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),j.append(U,oe),mu(j,x,t),u.appendChild(j);let F=h("div");if(F.setAttribute("data-approval-details","true"),F.style.display=x?"":"none",_){let $=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,F.appendChild($)}if(n.parameters){let $=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=io(n.parameters),F.appendChild($)}u.appendChild(F)}if(r){let x=h("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let j=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");j.type="button",j.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",j.style.color=o?.approveButtonTextColor??"#ffffff",j.setAttribute("data-approval-action","approve");let U=ie("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);U&&(U.style.marginRight="4px",j.appendChild(U));let oe=document.createTextNode(o?.approveLabel??"Approve");j.appendChild(oe);let F=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");F.type="button",F.style.backgroundColor=o?.denyButtonColor??"transparent",F.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",F.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,F.setAttribute("data-approval-action","deny");let $=ie("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",F.appendChild($));let X=document.createTextNode(o?.denyLabel??"Deny");F.appendChild(X),x.append(j,F),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var sy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),yu=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Do=(e,t)=>{yu(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},ay=e=>e?.approval!==!1?e?.approval:void 0,iy=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Bo.get(e)??n==="expanded"},Pl=e=>{let t=h("span","persona-approval-kbd");return t.textContent=e,t},ly=(e,t)=>{let n=h("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Nn)?Gr(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??oi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},cy=e=>{let t=h("div","persona-approval-resolved"),n=ie("ban",15,"currentColor",2);n&&t.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=e.toolName?oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},dy=(e,t,n,o,r,s,a)=>{let l=h("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&iy(t.id,o),f=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:f)):C.setAttribute("data-static","true");let R=h("span","persona-approval-logo"),B=ie("shield-check",16,"currentColor",2);B&&R.appendChild(B),C.appendChild(R);let L=ly(n,o);if(u){let j=h("span","persona-approval-toggle");j.setAttribute("aria-hidden","true");let U=ie("chevron-down",14,"currentColor",2);U&&j.appendChild(U),L.append(" "),L.appendChild(j)}C.appendChild(L),l.appendChild(C);let E=h("div","persona-approval-body");if(u){let j=h("div","persona-approval-details");if(j.setAttribute("data-role","params"),j.hidden=!w,d){let U=h("p","persona-approval-desc");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,j.appendChild(U)}if(c){let U=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(U.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.textContent=io(n.parameters),j.appendChild(U)}E.appendChild(j)}if(n.reason){let j=h("p","persona-approval-reason");o?.reasonColor?j.style.color=o.reasonColor:o?.descriptionColor&&(j.style.color=o.descriptionColor);let U=h("span","persona-approval-reason-label");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,j.append(U,document.createTextNode(n.reason)),E.appendChild(j)}let M=h("div","persona-approval-actions"),_=null,G=j=>{o?.approveButtonColor&&(j.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(j.style.color=o.approveButtonTextColor)},x=h("button","persona-approval-deny");if(x.type="button",x.setAttribute("data-action","deny"),o?.denyButtonColor&&(x.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(x.style.color=o.denyButtonTextColor),x.append(o?.denyLabel??"Deny"),a){let j=h("div","persona-approval-split"),U=h("button","persona-approval-primary");U.type="button",U.setAttribute("data-action","always"),G(U),U.append(o?.approveLabel??"Always allow",Pl("\u23CE"));let oe=h("button","persona-approval-caret");oe.type="button",oe.setAttribute("data-action","toggle-menu"),oe.setAttribute("aria-label","More options"),G(oe);let F=ie("chevron-down",15,"currentColor",2);F&&oe.appendChild(F),j.append(U,oe),M.append(j,x),x.append(Pl("Esc"));let $=h("div","persona-approval-menu"),X=h("button","persona-approval-menu-item");X.type="button",X.append("Allow once",Pl("\u2318\u23CE")),$.appendChild(X),_=fd({anchor:j,content:$,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,_),X.addEventListener("click",()=>{Do(e,t.id),r()})}else{let j=h("button","persona-approval-primary persona-approval-primary--solo");j.type="button",j.setAttribute("data-action","allow"),G(j),j.append(o?.approveLabel??"Allow"),M.append(j,x)}return E.appendChild(M),l.appendChild(E),l.addEventListener("click",j=>{let U=j.target instanceof Element?j.target.closest("[data-action]"):null;if(!U)return;let oe=U.getAttribute("data-action");if(oe==="toggle-params"){let F=l.querySelector('[data-role="params"]');if(F){let $=F.hidden;F.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?v:f),Bo.set(t.id,$)}return}if(oe==="toggle-menu"){_?.toggle();return}if(oe==="always"){Do(e,t.id),r({remember:!0});return}if(oe==="allow"){Do(e,t.id),r();return}if(oe==="deny"){Do(e,t.id),s();return}}),l},bu=()=>{let e=sy();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let p=ay(a);if(l.status!=="pending"){if(Do(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return cy(l)}yu(e,o.id);let d=p?.enableAlwaysAllow===!0,c=dy(e,o,l,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=w=>{gd(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Do(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Do(e,o);e.latestPendingApprovalId=null}}};var vu=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,l,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(R=>R.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(v=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=v,C.disabled=w,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let v=JSON.stringify(r);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Cs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var As=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var py=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),uy=new Set(["step_start","execution_start"]),fy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),gy=new Set(["step_complete","agent_turn_complete"]),my=new Set(["flow_complete","agent_complete"]),wu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Cu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Fo=(e,t)=>{let n=e[t];return Cu(n)?n:void 0};function Il(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function hy(e,t){return typeof t.type=="string"?t.type:e}function yy(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function by(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function xu(e){let t=Fo(e,"result"),n=[Fo(e,"tokens"),Fo(e,"totalTokens"),t?Fo(t,"tokens"):void 0,Fo(e,"usage"),t?Fo(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=rn(o.output)??rn(o.outputTokens)??rn(o.completionTokens);if(r!==void 0)return r}return rn(e.outputTokens)??rn(e.completionTokens)??(t?rn(t.outputTokens)??rn(t.completionTokens):void 0)}function vy(e){let t=Fo(e,"result");return rn(e.executionTime)??rn(e.executionTimeMs)??rn(e.execution_time)??rn(e.duration)??(t?rn(t.executionTime)??rn(t.executionTimeMs):void 0)}function wy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ss=class{constructor(t=wy){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:si(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Cu(n)){wu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=hy(t,n),r=this.now();if(py.has(o)){this.startRun(r);return}if(uy.has(o)){this.run||this.startRun(r);return}if(fy.has(o)){if(!by(o,n))return;let s=yy(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Il(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(gy.has(o)){if(!this.run)return;let s=this.run,a=xu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+Il(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:si(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(my.has(o)){if(!this.run)return;let s=this.run,a=xu(n),l=a??s.exactOutputTokens+Il(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:si(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(wu.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:vy(n)??o-t.startedAt}};function br(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Cy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ay=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sy=100;function Ty(e,t){let n={...xy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Cy}function My(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Ey(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function ky(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Ly(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Py(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Iy(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Ry(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Wy(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Rl(e,t,n,o,r,s,a,l){let p=r.has(e.id),d=h("div","persona-border-b persona-border-persona-divider persona-text-xs");br(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=h("div",""),f=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ie(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let R=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";R.textContent=B==="relative"?My(e.timestamp,n):Ey(e.timestamp);let L=null;o.showSequenceNumbers!==!1&&(L=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(t+1));let E=Ty(e.type,o.badgeColors),M=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");M.style.backgroundColor=E.bg,M.style.color=E.text,M.style.borderColor=E.text+"50",M.textContent=e.type;let _=o.descriptionFields??Ay,G=ky(e.payload,_),x=null;G&&(x=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=G);let j=h("div","persona-flex-1 persona-min-w-0"),U=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),oe=ie("clipboard","12px","currentColor",1.5);return oe&&U.appendChild(oe),U.addEventListener("click",async F=>{F.stopPropagation(),await Ly(Py(e)),U.innerHTML="";let $=ie("check","12px","currentColor",1.5);$&&U.appendChild($),setTimeout(()=>{U.innerHTML="";let X=ie("clipboard","12px","currentColor",1.5);X&&U.appendChild(X)},1500)}),f.appendChild(v),f.appendChild(R),L&&f.appendChild(L),f.appendChild(M),x&&f.appendChild(x),f.appendChild(j),f.appendChild(U),w.appendChild(f),p&&w.appendChild(Wy(e,a,l)),w}}function Au(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return f();function f(){let v=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");br(C,v?.panel);let R=[],B="",L="",E=null,M=[],_={},G=0,x=_a(),j=0,U=0,oe=!1,F=null,$=!1,X=0,me=new Set,he=new Map,Ae="",Z="",ce=null,ee,le,Y,pe,xe=null,ye=null,ve=null;function je(){let H=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),z=h("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(br(z,v?.headerBar),a){ye=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",xe=h("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),xe.textContent="-- tok/s",ve=h("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ve.style.display="none",ve.style.pointerEvents="none";let Fe=ye,Rt=ve,di=()=>{if(!Rt.textContent)return;let Ls=Fe.getBoundingClientRect(),Ps=H.getBoundingClientRect();Rt.style.left=`${Ls.left-Ps.left}px`,Rt.style.top=`${Ls.bottom-Ps.top+4}px`,Rt.style.display="block"},go=()=>{Rt.style.display="none"};ye.addEventListener("mouseenter",di),ye.addEventListener("mouseleave",go),ye.appendChild(xe)}let J=h("div","persona-flex-1");ee=h("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let qe=h("option","");qe.value="",qe.textContent="All events (0)",ee.appendChild(qe),le=h("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let Je=ie("clipboard-copy","12px","currentColor",1.5);Je&&le.appendChild(Je);let rt=h("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),ye&&z.appendChild(ye),z.appendChild(J),z.appendChild(ee),z.appendChild(le);let V=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");br(V,v?.searchBar);let _e=ie("search","14px","var(--persona-muted, #9ca3af)",1.5),be=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");_e&&be.appendChild(_e),Y=h("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),br(Y,v?.searchInput),Y.type="text",Y.placeholder="Search event payloads...",pe=h("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),pe.type="button",pe.style.display="none";let $e=ie("x","12px","currentColor",2);return $e&&pe.appendChild($e),V.appendChild(be),V.appendChild(Y),V.appendChild(pe),H.appendChild(z),H.appendChild(V),ve&&H.appendChild(ve),H}let Me,De=s.find(H=>H.renderEventStreamToolbar);De?.renderEventStreamToolbar&&r?Me=De.renderEventStreamToolbar({config:r,defaultRenderer:()=>je(),eventCount:t.getSize(),filteredCount:0,onFilterChange:z=>{B=z,et(),se()},onSearchChange:z=>{L=z,et(),se()}})??je():Me=je();let Qe=h("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Qe.style.display="none";function Ve(){if(!a||!xe||!ye)return;let H=a(),z=Iy(H);xe.textContent=z;let J=Ry(H);ve&&(ve.textContent=J,J||(ve.style.display="none")),ye.setAttribute("aria-label",J?`Throughput: ${z}, ${J}`:`Throughput: ${z}`)}let Te=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Le=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Le.style.height="100%";let Xe=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");br(Xe,v?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Ht=ie(d,"14px","currentColor",2);Ht&&Xe.appendChild(Ht);let It=h("span","");It.textContent=c,Xe.appendChild(It);let qt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");qt.style.display="none",Te.appendChild(Le),Te.appendChild(qt),Te.appendChild(Xe),C.setAttribute("tabindex","0"),C.appendChild(Me),C.appendChild(Qe),C.appendChild(Te);function xt(){let H=t.getAll(),z={};for(let V of H)z[V.type]=(z[V.type]||0)+1;let J=Object.keys(z).sort(),qe=J.length!==M.length||!J.every((V,_e)=>V===M[_e]),Re=!qe&&J.some(V=>z[V]!==_[V]),Je=H.length!==Object.values(_).reduce((V,_e)=>V+_e,0);if(!qe&&!Re&&!Je||(M=J,_=z,!ee))return;let rt=ee.value;if(ee.options[0].textContent=`All events (${H.length})`,qe){for(;ee.options.length>1;)ee.remove(1);for(let V of J){let _e=h("option","");_e.value=V,_e.textContent=`${V} (${z[V]||0})`,ee.appendChild(_e)}rt&&J.includes(rt)?ee.value=rt:rt&&(ee.value="",B="")}else for(let V=1;V<ee.options.length;V++){let _e=ee.options[V];_e.textContent=`${_e.value} (${z[_e.value]||0})`}}function He(){let H=t.getAll();if(B&&(H=H.filter(z=>z.type===B)),L){let z=L.toLowerCase();H=H.filter(J=>J.type.toLowerCase().includes(z)||J.payload.toLowerCase().includes(z))}return H}function de(){return B!==""||L!==""}function et(){G=0,j=0,x.resume(),Xe.style.display="none"}function Ie(H){me.has(H)?me.delete(H):me.add(H),ce=H;let z=Le.scrollTop,J=x.isFollowing();$=!0,x.pause(),se(),Le.scrollTop=z,J&&x.resume(),$=!1}function fe(){return uo(Le,50)}function se(){U=Date.now(),oe=!1,Ve(),xt();let H=t.getEvictedCount();H>0?(Qe.textContent=`${H.toLocaleString()} older events truncated`,Qe.style.display=""):Qe.style.display="none",R=He();let z=R.length,J=t.getSize()>0;z===0&&J&&de()?(qt.textContent=L?`No events matching '${L}'`:"No events matching filter",qt.style.display="",Le.style.display="none"):(qt.style.display="none",Le.style.display=""),le&&(le.title=de()?`Copy Filtered (${z})`:"Copy All"),p&&!x.isFollowing()&&z>G&&(j+=z-G,It.textContent=c?`${c}${j>0?` (${j})`:""}`:"",Xe.style.display=""),G=z;let qe=t.getAll(),Re=qe.length>0?qe[0].timestamp:0,Je=new Set(R.map(_e=>_e.id));for(let _e of me)Je.has(_e)||me.delete(_e);let rt=B!==Ae||L!==Z,V=he.size===0&&R.length>0;if(rt||V||R.length===0){Le.innerHTML="",he.clear();let _e=document.createDocumentFragment();for(let be=0;be<R.length;be++){let $e=Rl(R[be],be,Re,u,me,Ie,s,r);he.set(R[be].id,$e),_e.appendChild($e)}Le.appendChild(_e),Ae=B,Z=L,ce=null}else{if(ce!==null){let be=he.get(ce);if(be&&be.parentNode===Le){let $e=R.findIndex(Fe=>Fe.id===ce);if($e>=0){let Fe=Rl(R[$e],$e,Re,u,me,Ie,s,r);Le.insertBefore(Fe,be),be.remove(),he.set(ce,Fe)}}ce=null}let _e=new Set(R.map(be=>be.id));for(let[be,$e]of he)_e.has(be)||($e.remove(),he.delete(be));for(let be=0;be<R.length;be++){let $e=R[be];if(!he.has($e.id)){let Fe=Rl($e,be,Re,u,me,Ie,s,r);he.set($e.id,Fe),Le.appendChild(Fe)}}}x.isFollowing()&&(Le.scrollTop=Le.scrollHeight)}function Pe(){if(Date.now()-U>=Sy){F!==null&&(cancelAnimationFrame(F),F=null),se();return}oe||(oe=!0,F=requestAnimationFrame(()=>{F=null,se()}))}let it=(H,z)=>{if(!le)return;le.innerHTML="";let J=ie(H,"12px","currentColor",1.5);J&&le.appendChild(J);let qe=h("span","persona-text-xs");qe.textContent="Copy All",le.appendChild(qe),setTimeout(()=>{le.innerHTML="";let Re=ie("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Je=h("span","persona-text-xs");Je.textContent="Copy All",le.appendChild(Je),le.disabled=!1},z)},ue=async()=>{if(le){le.disabled=!0;try{let H;de()?H=R:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let z=H.map(J=>{try{return JSON.parse(J.payload)}catch{return J.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),it("check",1500)}catch{it("x",1500)}}},Ce=()=>{ee&&(B=ee.value,et(),se())},te=()=>{!Y||!pe||(pe.style.display=Y.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{L=Y.value,et(),se()},150))},S=()=>{!Y||!pe||(Y.value="",L="",pe.style.display="none",E&&clearTimeout(E),et(),se())},D=()=>{if($)return;let H=Le.scrollTop,{action:z,nextLastScrollTop:J}=$a({following:x.isFollowing(),currentScrollTop:H,lastScrollTop:X,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});X=J,z==="resume"?(x.resume(),j=0,Xe.style.display="none"):z==="pause"&&(x.pause(),p&&(It.textContent=c,Xe.style.display=""))},y=H=>{let z=za({following:x.isFollowing(),deltaY:H.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});z==="pause"?(x.pause(),p&&(It.textContent=c,Xe.style.display="")):z==="resume"&&(x.resume(),j=0,Xe.style.display="none")},P=()=>{p&&(Le.scrollTop=Le.scrollHeight,x.resume(),j=0,Xe.style.display="none")},T=H=>{let z=H.target;if(!z||z.closest("button"))return;let J=z.closest("[data-event-id]");if(!J)return;let qe=J.getAttribute("data-event-id");qe&&Ie(qe)},I=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Y?.focus(),Y?.select();return}H.key==="Escape"&&(Y&&document.activeElement===Y?(S(),Y.blur(),C.focus()):o&&o())};le&&le.addEventListener("click",ue),ee&&ee.addEventListener("change",Ce),Y&&Y.addEventListener("input",te),pe&&pe.addEventListener("click",S),Le.addEventListener("scroll",D),Le.addEventListener("wheel",y,{passive:!0}),Le.addEventListener("click",T),Xe.addEventListener("click",P),C.addEventListener("keydown",I);function q(){E&&clearTimeout(E),F!==null&&(cancelAnimationFrame(F),F=null),oe=!1,he.clear(),le&&le.removeEventListener("click",ue),ee&&ee.removeEventListener("change",Ce),Y&&Y.removeEventListener("input",te),pe&&pe.removeEventListener("click",S),Le.removeEventListener("scroll",D),Le.removeEventListener("wheel",y),Le.removeEventListener("click",T),Xe.removeEventListener("click",P),C.removeEventListener("keydown",I)}return{element:C,update:Pe,destroy:q}}}function Su(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&t.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,v)=>{f.setAttribute("role","tab");let C=v===w;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||w<0&&v===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Tu(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),$?.hide()};w&&w.addEventListener("click",()=>{f(),t.onDismiss?.()});let v=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let R=h("span","persona-text-xs persona-font-medium persona-truncate");R.textContent=s;let B=Pt({icon:"x",label:a});B.addEventListener("click",()=>{f(),t.onDismiss?.()});let L="rendered",E=Ba({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:te=>{L=te==="source"?"source":"rendered",it()}}),M=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),_=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,j=!!(G&&x&&x.length>0),U=null,oe,F=null,$=null;if(r&&(_||G)&&!j){if(oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let te=ie("chevron-down",14,"currentColor",2);te&&oe.appendChild(te)}}else r&&j?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),oe=_?Wo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F=Pt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),U.append(oe,F)):r?oe=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(oe=Pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&oe.classList.add("persona-hidden"));let X=r?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),me=r?Pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:a}),he=Pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let Ae=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=e.features?.artifacts?.toolbarActions??[],ce=()=>{let te=Te.find(P=>P.id===Le)??Te[Te.length-1],S=te?.id??null,D=te?.artifactType==="markdown"?te.markdown??"":"",y=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:D,jsonPayload:y,id:S}},ee=async()=>{let te=Te.find(S=>S.id===Le)??Te[Te.length-1];try{await navigator.clipboard.writeText(fs(te))}catch{}};if(oe.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&j){let{markdown:S,jsonPayload:D,id:y}=ce();try{await te({actionId:"primary",artifactId:y,markdown:S,jsonPayload:D})}catch{}return}await ee()}),F&&x?.length){let te=()=>v.closest("[data-persona-root]")??document.body,S=()=>{$=fr({items:x.map(D=>({id:D.id,label:D.label})),onSelect:async D=>{let{markdown:y,jsonPayload:P,id:T}=ce(),I=n?.onDocumentToolbarCopyMenuSelect;try{I?await I({actionId:D,artifactId:T,markdown:y,jsonPayload:P}):D==="markdown"||D==="md"?await navigator.clipboard.writeText(y):D==="json"||D==="source"?await navigator.clipboard.writeText(P):await navigator.clipboard.writeText(y||P)}catch{}},anchor:U??F,position:"bottom-right",portal:te()})};v.isConnected?S():requestAnimationFrame(S),F.addEventListener("click",D=>{D.stopPropagation(),$?.toggle()})}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),me.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),U?M.append(U,X,me):M.append(oe,X,me),M.insertBefore(Ae,me),M.insertBefore(he,me),C.append(E.element,le,M);else{let te=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(oe,Ae,he,B),C.appendChild(R),C.appendChild(te)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Y=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Y.style.setProperty("--persona-artifact-tab-fade-size",p);let pe=e.features?.artifacts?.renderTabBar,xe=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Su(Y,{onSelect:te=>t.onSelect(Te[te].id)}),ve=te=>{let S=te.scrollWidth-te.clientWidth,D=S>1,y=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",c&&D&&y>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&D&&y<S-1)},je=0,Me=()=>{if(je)return;let te=()=>{je=0,ve(Y)};je=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};Y.addEventListener("scroll",()=>Me(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ve(Y)).observe(Y);let De=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Qe=()=>{De.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Qe):setTimeout(Qe,0)};if(l){for(let te of[Y,xe])te.style.paddingLeft=l,te.style.paddingRight=l;De.style.padding=l}v.appendChild(C),v.appendChild(Y),v.appendChild(xe),v.appendChild(De);let Te=[],Le=null,Xe=!1,Ht=!1,It=!0,qt=!1,xt=null,He="",de=null,et=!1,Ie=te=>te.artifactType==="markdown"&&!!te.file||r?L:"rendered",fe=te=>{r||(te&&!et?(C.insertBefore(E.element,R),et=!0):!te&&et&&(E.element.remove(),et=!1))},se=()=>Le&&Te.find(te=>te.id===Le)||Te[Te.length-1],Pe=()=>{let te=ps(se());if(!te){Ae.replaceChildren();return}let S=Z.filter(D=>D.visible===void 0||D.visible(te)).map(D=>gr(D,{documentChrome:r,onClick:()=>{let y=ps(se());if(y)try{Promise.resolve(D.onClick(y)).catch(()=>{})}catch{}}}));Ae.replaceChildren(...S)},it=()=>{Pe();let te=r&&Te.length<=1,S=!!pe;if(Y.classList.toggle("persona-hidden",te||S),xe.classList.toggle("persona-hidden",te||!S),S&&pe){let P=Te.map(T=>T.id).join("|")+" "+(Le??"");if(P!==He){He=P;let T=pe({records:Te,selectedId:Le,onSelect:t.onSelect});xe.firstElementChild!==T&&xe.replaceChildren(T)}}else{ye.beforeRender(),Y.replaceChildren();let P=[],T=-1;for(let[I,q]of Te.entries()){let H=h("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");H.type="button";let z=q.artifactType==="markdown"?q.file:void 0,J=z?Mn(z.path):q.title||q.id.slice(0,8),qe=z?.path||q.title||J;H.textContent=J,H.title=qe,H.setAttribute("aria-label",qe),q.id===Le&&(H.classList.add("persona-bg-persona-container","persona-border-persona-border"),T=I),H.addEventListener("click",()=>t.onSelect(q.id)),Y.appendChild(H),P.push(H)}if(ye.render(P,T),T>=0&&Le!==xt){xt=Le;let I=P[T];typeof I.scrollIntoView=="function"&&I.scrollIntoView({block:"nearest",inline:"nearest"})}ve(Y)}let D=Le&&Te.find(P=>P.id===Le)||Te[Te.length-1];if(!D){De.replaceChildren(),de=null,fe(!1);return}let y=D.artifactType==="markdown"?D.file:void 0;if(fe(!!y),r){let P=y?lo(y):D.artifactType==="markdown"?"MD":D.component??"Component",T=(D.title||"Document").trim(),I=y?Mn(y.path):T.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${I} \xB7 ${P}`}else R.textContent=y?Mn(y.path):s;de?(de.el.parentElement!==De&&De.replaceChildren(de.el),de.update(D)):(de=Na(D,{config:e,resolveViewMode:Ie}),De.replaceChildren(de.el)),De.classList.toggle("persona-artifact-content-flush",!!De.querySelector(".persona-code-pre"))},ue=()=>{let te=Te.length>0;if(v.classList.toggle("persona-hidden",!te),w){let y=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;te&&y&&Xe?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},Ce=()=>{qt=!1,it(),ue()};return{element:v,backdrop:w,update(te){let S=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,D=S!==Le;Te=te.artifacts,Le=S,Te.length>0&&(Xe=!0),qt=!0,It&&Ce(),D&&Qe()},setMobileOpen(te){Xe=te,!te&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):ue()},setExpanded(te){te!==Ht&&(Ht=te,Ve());let S=ie(te?"minimize":"maximize",16,"currentColor",2);S&&he.replaceChildren(S);let D=te?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",D),he.title=D},setExpandToggleVisible(te){he.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||oe.classList.toggle("persona-hidden",!te)},setCustomActions(te){Z=te,Pe()},setTabFade(te){let S=d(te);S.start===c&&S.end===u||(c=S.start,u=S.end,ve(Y))},setRenderTabBar(te){te!==pe&&(pe=te,He="",it())},setVisible(te){te!==It&&(It=te,te&&qt&&Ce())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Mu(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Hy(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Eu=["panel","seamless","detached"];function Wl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Eu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Hl(e){return!e||!Xt(e)?!1:Wl(e)==="detached"}function Ts(e,t){if(!Xt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Hy(e),Mu(e,t);return}let n=t.features?.artifacts?.layout,o=Wl(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Mu(e,t)}function Ms(e,t){for(let l of Eu)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=Wl(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ku(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var By=new Set(["__proto__","prototype","constructor"]),Dy=new Set(["collapsed","card","panel","inline"]),Lu=new Set(["markdown","component"]),Fy=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,No=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ii=e=>!By.has(e),Bl=e=>typeof e=="string"&&Dy.has(e),Oo=e=>Object.keys(e).length>0;function kn(e,t,n,o){e.push({path:t,code:n,message:o})}var Ny="Ignored because this key is not part of the persisted preference schema.",ai="Ignored an unsupported value.",Oy="Expected collapsed, panel, or inline.",_y='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Pu={kind:"mode",message:ai},vr={kind:"string",message:"Expected a CSS length string."},jn={kind:"boolean"},$y={paneWidth:vr,paneMaxWidth:vr,paneMinWidth:vr,expandedPanelWidth:vr,resizableMinWidth:vr,resizableMaxWidth:vr,expandLauncherPanelWhenOpen:jn,resizable:jn},zy={kind:"object",message:"Expected a preference object.",children:{showToolCalls:jn,showReasoning:jn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ai},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ai},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ai},expandable:jn,grouped:jn}},reasoningDisplay:{kind:"object",children:{expandable:jn,activePreview:jn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Pu,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Pu,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Lu,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Lu}}},filePreview:{kind:"object",children:{enabled:jn}},layout:{kind:"object",children:$y}}}}};function Iu(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:kn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:kn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:kn(o,n,"invalid_value",t.message);case"mode":return Bl(e)?un(e):kn(o,n,"invalid_value",t.message);case"modeMap":{if(!No(e))return kn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let p=r?a:er(a);ii(a)&&(r?r.has(a):Fy.test(p))?Bl(l)?s[p]=un(l):kn(o,`${n}.${a}`,"invalid_value",Oy):kn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":_y)}return Oo(s)?s:void 0}case"object":{if(t.bareMode&&Bl(e))return un(e);if(!No(e))return kn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!ii(l)||!r.includes(l))&&kn(o,s(l),"unknown_key",Ny);let a={};for(let l of r){let p=t.children[l],d=Iu(e[l],p,s(l),o);if(p.deprecated&&e[l]!==void 0&&kn(o,s(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,u=a[c];a[c]=No(u)&&No(d)?{...u,...d}:d}return Oo(a)?a:void 0}}}function jy(e){let t=[];return{preferences:(e===null?void 0:Iu(e,zy,"",t))??{},issues:t}}function wr(e){if(Array.isArray(e))return e.map(wr);if(!No(e))return e;let t={};for(let[n,o]of Object.entries(e))ii(n)&&o!==void 0&&(t[n]=wr(o));return t}function Ru(e,t){let n=wr(e);for(let[o,r]of Object.entries(t)){if(!ii(o)||r===void 0)continue;let s=n[o];n[o]=No(s)&&No(r)?Ru(s,r):wr(r)}return n}function Uy(e){let t={},n;for(let r of e){let s=jy(r).preferences;n=Wu(n,s.artifacts?.display),t=Ru(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Vy(e,t){if(t===void 0)return e===void 0?void 0:wr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Oo(r)?{byMediaType:r}:{}};return Oo(s)?s:void 0}function Wu(e,t){if(t===void 0)return e===void 0?void 0:wr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Vy(n.files,t.files),a={...o?{default:o}:{},...Oo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Oo(a)?a:void 0}function qy(e={},t){let n=Uy(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Wu(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Dl(e){let t=e.preferences;return!t||!Oo(t)?e:{...e,features:qy(e.features??{},[t])}}function Ky(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Gy(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Qy(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Xy(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Fl(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Hu(e,t,n,o,r,s){let a=Ky(r,200),l=Xy(t,n,o,200);l=Math.max(a,l);let p=Gy(s);return p!==null&&(l=Math.min(l,p)),Qy(e,a,l)}var Bu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Nl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Bu[a]??Bu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),d=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=h("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${v.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=v.label,C.appendChild(R);let B=v.type??"text",L;B==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=B),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${t.id}-${a}-${v.name}`,L.name=v.name,L.placeholder=v.placeholder??"",v.required&&(L.required=!0),C.appendChild(L),c.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",R=new FormData(c),B={};R.forEach((L,E)=>{B[E]=L}),B.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let L=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let E=await L.json();w.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(L){w.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ol=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},_l=new Ol;var Du=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jy=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Fu=(e,t,n)=>{if(!Du(e)||!Du(t)||Jy.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Fu(e[r],t[r],s)}return o};function Nu(e,t){let n=Fu(e,t,"");return ka(n)}var Ou=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Yy=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Zy=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},zl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Yy(e),n=Zy(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},$l=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:$l(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=$l(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:$l(n.text)}}},_u=e=>Array.isArray(e)?e.map(t=>String(t)):[],jl=e=>{let t=new Set(_u(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(_u(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let p={action:l,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var eb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},tb=e=>e.map(t=>({...t,streaming:!1})),nb=e=>e.map(t=>({...t,status:"complete"})),$u=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?eb(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?tb(n.messages):void 0,artifacts:n.artifacts?nb(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as $A,STR as zA,OBJ as jA}from"partial-json";function zu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function ju(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ul(e){let t=ju(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Uu(e){let t=ju(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var ob=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vu(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=ob}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,f.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),w.appendChild(f);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-csat",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){let x=document.createElement("button");x.type="button",x.className="persona-feedback-rating-btn persona-feedback-star-btn",x.setAttribute("role","radio"),x.setAttribute("aria-checked","false"),x.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${d[G-1]}`),x.title=d[G-1],x.dataset.rating=String(G),x.innerHTML=`
|
|
39
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Rt(s),u=n.querySelector("[data-role='launcher-title']");if(u){let k=a.title??"Chat Assistant";u.textContent=k,u.setAttribute("title",k)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let k=a.subtitle??"Here to help you get answers fast";d.textContent=k,d.setAttribute("title",k)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let k=a.agentIconSize??"40px";if(f.style.height=k,f.style.width=k,a.agentIconBackgroundColor?(f.style.backgroundColor=a.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",a.agentIconName){let P=parseFloat(k)||24,H=ae(a.agentIconName,P*.6,"var(--persona-text-inverse, #ffffff)",2);H?(f.appendChild(H),f.style.display=""):(f.textContent=a.agentIconText??"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=a.agentIconText??"\u{1F4AC}",f.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let k=a.agentIconSize??"40px";w.style.height=k,w.style.width=k,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let k=a.callToActionIconSize??"32px";g.style.height=k,g.style.width=k,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let P=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,P=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let H=parseFloat(k)||24,F=Math.max(H-P,8),N=ae(a.callToActionIconName,F,"currentColor",2);N?g.appendChild(N):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&ln[a.position]?ln[a.position]:ln["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??Nt));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))";n.style.border=a.border??B,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:S,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},Qb="teaser-dismissed",Df=new Set,Bf=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Qb}`},Jb=(e,t)=>{if(Df.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Zb=(e,t)=>{if(Df.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},ev=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,tv=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Rt(e??{})?null:t},Ff=(e,t)=>{let n=b("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,u=null,d=!1,c=!1,f=!1,w=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{u!==null&&(clearTimeout(u),u=null)},C=()=>{!s||!d||(d=!1,s.hidden=!0)},T=Y=>{v(),f=!0,C(),Zb(Bf(o),Y&&g())},B=Y=>{!r||f||T(Y==="user"&&d)},S=()=>{u=null,!(!s||f||w)&&(c=!0,d=!0,s.hidden=!1,!(ev()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},k=()=>{!r||!s||f||c||w||Jb(Bf(o),g())||(v(),u=setTimeout(S,Math.max(0,r.delayMs??0)))},P=()=>{T(g()),t()},H=Y=>{Y.stopPropagation(),T(g())},N=vc(e,()=>{B("user"),t()}),z=()=>{v(),l?.removeEventListener("click",P),a?.removeEventListener("click",H),s?.remove(),s=null,l=null,a=null,d=!1},j=()=>{l=Ee("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",P),a=Ee("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",H),s=Ee("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,N.element)},te=()=>{let Y=o.launcher?.position??"bottom-right",ue=ln[Y]??ln["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",N.element.style.position="";return}n.className=Pn("persona-launcher-surface",ue),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??Nt),N.element.style.position="static"},A=Y=>{let ue=tv(Y);if(r=ue,!ue){z();return}s||j(),l.textContent=ue.text,a.hidden=ue.dismissible===!1,a.setAttribute("aria-label",ue.dismissLabel??"Dismiss message"),k()},G=Y=>{o=Y,N.update(Y),A(Y),te()},Q=(Y,ue="user")=>{w=Y,Y&&B(ue)},ie=()=>{z(),N.destroy(),n.remove()};return n.appendChild(N.element),e&&(A(e),te()),{element:n,launcher:N,get teaser(){return s?{element:s,show:S,dismiss:T}:null},setPanelOpen:Q,update:G,destroy:ie}};var Of=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Wf(e),s=Hf(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},u={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:u,composer:d,replaceHeader:w=>(u.element.replaceWith(w.header),u.element=w.header,u.iconHolder=w.iconHolder,u.headerTitle=w.headerTitle,u.headerSubtitle=w.headerSubtitle,u.closeButton=w.closeButton,u.closeButtonWrapper=w.closeButtonWrapper,u.clearChatButton=w.clearChatButton,u.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},wc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>vc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Ff(e,n);return{instance:r,element:r.element}};var nv=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},ov=(e,t,n)=>`${nv(e)}plugin:${t}:${n}`,Nf=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>ov(e(),r,a);return{get:a=>{let l=s(a),u=o();if(u)try{return u.getItem(l)}catch{n=!0}return t.get(l)??null},set:(a,l)=>{let u=s(a),d=o();if(d)try{d.setItem(u,l);return}catch{n=!0}t.set(u,l)},remove:a=>{let l=s(a);t.delete(l);let u=o();if(u)try{u.removeItem(l)}catch{n=!0}}}}};var $r=new Set,rv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
+
`):""},_f=(e,t)=>{let n=$r.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},xc=(e,t)=>{let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&$r.has(e.id),l=n.status!=="complete",u=sv(e,r.previewMaxLines??3),d=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");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=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",g=t?.reasoning??{},v=String(n.startedAt??Date.now()),C=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",v),ie.textContent=ja(n),ie},T=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:w,previewText:u,isActive:l,config:t??{},elapsed:ja(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(f.textContent=T,c.appendChild(f)):T instanceof HTMLElement?c.appendChild(T):(f.textContent=w,c.appendChild(f));let B=b("span","persona-text-xs persona-text-persona-primary");B.textContent=lu(n),c.appendChild(B);let S=r.loadingAnimation??"none",k=g.activeTextTemplate,P=g.completeTextTemplate,H=l?k:P,F=T instanceof HTMLElement,N=(ie,Y)=>{f.textContent="";let ue=Va(ie,""),X=0;for(let ge of ue){let Z=ge.styles.length>0?(()=>{let pe=b("span",ge.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(pe),pe})():f;if(ge.isDuration&&l)Z.appendChild(C());else{let pe=ge.isDuration?ja(n):ge.text;Y?X=Ao(Z,pe,X):Z.appendChild(document.createTextNode(pe))}}};if(!F&&H)if(B.style.display="none",f.style.display="",l&&S!=="none"){let ie=g.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),S==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),N(H,!1)):(f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),N(H,!0))}else N(H,!1);else if(!F&&l&&S!=="none"){f.style.display="";let ie=g.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),S==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`);else{f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Y=f.textContent||w;f.textContent="",Ao(f,Y,0)}n.status==="complete"&&(f.style.display="none")}else F||(n.status==="complete"?f.style.display="none":f.style.display="");let z=null;if(s){z=b("div","persona-flex persona-items-center");let Y=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show";let ue=b("div","persona-flex persona-items-center persona-ml-auto");ue.append(z),d.append(c,ue)}else d.append(c);let j=b("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&&u){let ie=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:u,isActive:l,config:t??{}});rv(j,ie)||(j.textContent=u),j.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,j),o;let te=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");te.style.display=a?"":"none";let A=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=A||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),te.appendChild(G),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Y=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show"}te.style.display=a?"":"none",j.style.display=a?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(d,j,te),o};var Ur=new Set,av=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),iv=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
41
|
+
`);let r=wo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
+
`):""},Cc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},lv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=iv(e,o?.previewMaxLines??3),a=n?cu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",u=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&u.activeTextTemplate?d=$l(n,u.activeTextTemplate,d):!l&&u.completeTextTemplate&&(d=$l(n,u.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},$f=(e,t,n)=>{let o=Ur.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Ac=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ur.has(e.id),{summary:u,previewText:d,isActive:c}=lv(e,t),f=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");f.type="button",a&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let w=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let A=b("span","");return A.setAttribute("data-tool-elapsed",v),A.textContent=Ms(n),A},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:u,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ms(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,w.appendChild(g)):T instanceof HTMLElement?w.appendChild(T):(g.textContent=u,w.appendChild(g));let B=s.loadingAnimation??"none",S=o.activeTextTemplate,k=o.completeTextTemplate,P=c?S:k,H=T instanceof HTMLElement,F=(A,G)=>{g.textContent="";let Q=n.name?.trim()||"tool",ie=Va(A,Q),Y=0;for(let ue of ie){let X=ue.styles.length>0?(()=>{let ge=b("span",ue.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(ge),ge})():g;if(ue.isDuration&&c)X.appendChild(C());else{let ge=ue.isDuration?Ms(n):ue.text;G?Y=Ao(X,ge,Y):X.appendChild(document.createTextNode(ge))}}};if(!H)if(c&&B!=="none"){let A=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),P&&F(P,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),P)F(P,!0);else{let G=g.textContent||u;g.textContent="",Ao(g,G,0)}}else P&&F(P,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(N),f.append(w,Q)}else f.append(w);let z=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let A=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});av(z,A)||(z.textContent=d),z.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(f,z),r;let j=b("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 A=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?A.style.color=o.contentTextColor:o.headerTextColor&&(A.style.color=o.headerTextColor),A.textContent=n.name,j.appendChild(A)}if(n.args!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.args),A.append(G,Q),j.appendChild(A)}if(n.chunks&&n.chunks.length){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=n.chunks.join(""),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&n.result!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.result),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&typeof n.duration=="number"){let A=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(A.style.color=o.contentTextColor),A.textContent=`Duration: ${n.duration}ms`,j.appendChild(A)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),N){N.innerHTML="";let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show"}j.style.display=l?"":"none",z.style.display=l?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(f,z,j),r};var er=new Map,Wi=e=>{let n=(e.startsWith(Yn)?e.slice(Yn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Uf=e=>e?.approval!==!1?e?.approval:void 0,zf=(e,t)=>{let n=Uf(t)?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},jf=(e,t,n)=>{let o=Uf(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Vf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=zf(e,n);jf(o,s,n),r.style.display=s?"":"none"};var Ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let u=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(u,20,d,2);c&&l.appendChild(c);let f=b("div","persona-flex-1 persona-min-w-0"),w=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",w.appendChild(g),!r){let N=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");N.setAttribute("data-approval-status",n.status),n.status==="approved"?(N.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",N.style.color="var(--persona-palette-colors-success-700, #15803d)",N.textContent="Approved"):n.status==="denied"?(N.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",N.style.color="var(--persona-palette-colors-error-700, #b91c1c)",N.textContent="Denied"):n.status==="timeout"&&(N.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",N.style.color="var(--persona-palette-colors-warning-700, #b45309)",N.textContent="Timeout"),w.appendChild(N)}f.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Yn)?ws(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,S=T||(B?n.description:`The assistant wants to use \u201C${C??Wi(n.toolName)}\u201D.`),k=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=S,f.appendChild(k),n.reason){let N=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");N.setAttribute("data-approval-reason","true"),o?.reasonColor?N.style.color=o.reasonColor:o?.descriptionColor&&(N.style.color=o.descriptionColor);let z=b("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,N.appendChild(z),N.appendChild(document.createTextNode(n.reason)),f.appendChild(N)}let P=o?.detailsDisplay??"collapsed",H=!!n.description&&!B,F=H||!!n.parameters;if(P!=="hidden"&&F){let N=zf(e.id,t),z=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");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span");j.setAttribute("data-approval-details-label","true");let te=b("span","persona-inline-flex persona-items-center");te.setAttribute("data-approval-details-chevron","true"),z.append(j,te),jf(z,N,t),f.appendChild(z);let A=b("div");if(A.setAttribute("data-approval-details","true"),A.style.display=N?"":"none",H){let G=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,A.appendChild(G)}if(n.parameters){let G=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=wo(n.parameters),A.appendChild(G)}f.appendChild(A)}if(r){let N=b("div","persona-flex persona-gap-2 persona-mt-2");N.setAttribute("data-approval-buttons","true");let z=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");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let j=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);j&&(j.style.marginRight="4px",z.appendChild(j));let te=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(te);let A=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");A.type="button",A.style.backgroundColor=o?.denyButtonColor??"transparent",A.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",A.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,A.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",A.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");A.appendChild(Q),N.append(z,A),f.appendChild(N)}return a.append(l,f),s.appendChild(a),s};var cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},tr=(e,t)=>{qf(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},dv=e=>e?.approval!==!1?e?.approval:void 0,pv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},Sc=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uv=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Yn)?ws(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Wi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let u=document.createElement("strong");if(u.textContent=a,n.appendChild(u),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},fv=e=>{let t=b("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?Wi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},gv=(e,t,n,o,r,s,a)=>{let l=b("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let u=o?.detailsDisplay??"collapsed",d=!!n.description&&u!=="hidden",c=n.parameters!=null&&u!=="hidden",f=d||c,w=f&&pv(t.id,o),g=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=b("button","persona-approval-head");C.type="button",f?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:g)):C.setAttribute("data-static","true");let T=b("span","persona-approval-logo"),B=ae("shield-check",16,"currentColor",2);B&&T.appendChild(B),C.appendChild(T);let S=uv(n,o);if(f){let z=b("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let j=ae("chevron-down",14,"currentColor",2);j&&z.appendChild(j),S.append(" "),S.appendChild(z)}C.appendChild(S),l.appendChild(C);let k=b("div","persona-approval-body");if(f){let z=b("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!w,d){let j=b("p","persona-approval-desc");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,z.appendChild(j)}if(c){let j=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(j.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.textContent=wo(n.parameters),z.appendChild(j)}k.appendChild(z)}if(n.reason){let z=b("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span","persona-approval-reason-label");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(j,document.createTextNode(n.reason)),k.appendChild(z)}let P=b("div","persona-approval-actions"),H=null,F=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},N=b("button","persona-approval-deny");if(N.type="button",N.setAttribute("data-action","deny"),o?.denyButtonColor&&(N.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(N.style.color=o.denyButtonTextColor),N.append(o?.denyLabel??"Deny"),a){let z=b("div","persona-approval-split"),j=b("button","persona-approval-primary");j.type="button",j.setAttribute("data-action","always"),F(j),j.append(o?.approveLabel??"Always allow",Sc("\u23CE"));let te=b("button","persona-approval-caret");te.type="button",te.setAttribute("data-action","toggle-menu"),te.setAttribute("aria-label","More options"),F(te);let A=ae("chevron-down",15,"currentColor",2);A&&te.appendChild(A),z.append(j,te),P.append(z,N),N.append(Sc("Esc"));let G=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Sc("\u2318\u23CE")),G.appendChild(Q),H=Pp({anchor:z,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,H),Q.addEventListener("click",()=>{tr(e,t.id),r()})}else{let z=b("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),F(z),z.append(o?.approveLabel??"Allow"),P.append(z,N)}return k.appendChild(P),l.appendChild(k),l.addEventListener("click",z=>{let j=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!j)return;let te=j.getAttribute("data-action");if(te==="toggle-params"){let A=l.querySelector('[data-role="params"]');if(A){let G=A.hidden;A.hidden=!G,C.setAttribute("aria-expanded",G?"true":"false"),C.setAttribute("aria-label",G?v:g),er.set(t.id,G)}return}if(te==="toggle-menu"){H?.toggle();return}if(te==="always"){tr(e,t.id),r({remember:!0});return}if(te==="allow"){tr(e,t.id),r();return}if(te==="deny"){tr(e,t.id),s();return}}),l},Kf=()=>{let e=cv();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 u=dv(a);if(l.status!=="pending"){if(tr(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return fv(l)}qf(e,o.id);let d=u?.enableAlwaysAllow===!0,c=gv(e,o,l,u,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=w=>{Ip(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),tr(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])tr(e,o);e.latestPendingApprovalId=null}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hv=new Set(["step_start","execution_start"]),yv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bv=new Set(["step_complete","agent_turn_complete"]),vv=new Set(["flow_complete","agent_complete"]),Gf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Xf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,nr=(e,t)=>{let n=e[t];return Xf(n)?n:void 0};function Tc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Hi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function wv(e,t){return typeof t.type=="string"?t.type:e}function xv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Cv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Yf(e){let t=nr(e,"result"),n=[nr(e,"tokens"),nr(e,"totalTokens"),t?nr(t,"tokens"):void 0,nr(e,"usage"),t?nr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(e.outputTokens)??cn(e.completionTokens)??(t?cn(t.outputTokens)??cn(t.completionTokens):void 0)}function Av(e){let t=nr(e,"result");return cn(e.executionTime)??cn(e.executionTimeMs)??cn(e.execution_time)??cn(e.duration)??(t?cn(t.executionTime)??cn(t.executionTimeMs):void 0)}function Sv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Sv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Hi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Xf(n)){Gf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=wv(t,n),r=this.now();if(mv.has(o)){this.startRun(r);return}if(hv.has(o)){this.run||this.startRun(r);return}if(yv.has(o)){if(!Cv(o,n))return;let s=xv(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+Tc(a.visibleCharCount),u=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Hi(l,u),outputTokens:l,durationMs:u,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(bv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,u=s.exactOutputTokens+Tc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Hi(u,d),outputTokens:u,durationMs:d,source:l?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n),l=a??s.exactOutputTokens+Tc(s.visibleCharCount),u=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Hi(l,d),outputTokens:l,durationMs:d,source:u},this.run=null;return}if(Gf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Av(n)??o-t.startedAt}};function zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Tv={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)"}},Mv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],kv=100;function Lv(e,t){let n={...Tv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Mv}function Pv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Iv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Wv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Rv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Hv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Bv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Dv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Fv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=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]"),u=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=o,l.appendChild(u),l}}function Mc(e,t,n,o,r,s,a,l){let u=r.has(e.id),d=b("div","persona-border-b persona-border-persona-divider persona-text-xs");zr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:u,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(f()),d;function f(){let w=b("div",""),g=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");g.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ae(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let T=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";T.textContent=B==="relative"?Pv(e.timestamp,n):Iv(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let k=Lv(e.type,o.badgeColors),P=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");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=e.type;let H=o.descriptionFields??Ev,F=Wv(e.payload,H),N=null;F&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=F);let z=b("div","persona-flex-1 persona-min-w-0"),j=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"),te=ae("clipboard","12px","currentColor",1.5);return te&&j.appendChild(te),j.addEventListener("click",async A=>{A.stopPropagation(),await Rv(Hv(e)),j.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&j.appendChild(G),setTimeout(()=>{j.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&j.appendChild(Q)},1500)}),g.appendChild(v),g.appendChild(T),S&&g.appendChild(S),g.appendChild(P),N&&g.appendChild(N),g.appendChild(z),g.appendChild(j),w.appendChild(g),u&&w.appendChild(Fv(e,a,l)),w}}function Qf(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,u=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",f=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return g();function g(){let v=f.classNames,C=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");zr(C,v?.panel);let T=[],B="",S="",k=null,P=[],H={},F=0,N=ui(),z=0,j=0,te=!1,A=null,G=!1,Q=0,ie=new Set,Y=new Map,ue="",X="",ge=null,Z,pe,ee,me,we=null,he=null,ke=null;function Ne(){let $=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=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(zr(K,v?.headerBar),a){he=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",we=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"),we.textContent="-- tok/s",ke=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"),ke.style.display="none",ke.style.pointerEvents="none";let xt=he,dn=ke,ra=()=>{if(!dn.textContent)return;let pn=xt.getBoundingClientRect(),it=$.getBoundingClientRect();dn.style.left=`${pn.left-it.left}px`,dn.style.top=`${pn.bottom-it.top+4}px`,dn.style.display="block"},oe=()=>{dn.style.display="none"};he.addEventListener("mouseenter",ra),he.addEventListener("mouseleave",oe),he.appendChild(we)}let ce=b("div","persona-flex-1");Z=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let je=b("option","");je.value="",je.textContent="All events (0)",Z.appendChild(je),pe=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"),pe.type="button",pe.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&pe.appendChild(Pe);let Ve=b("span","persona-event-copy-all persona-text-xs");Ve.textContent="Copy All",pe.appendChild(Ve),he&&K.appendChild(he),K.appendChild(ce),K.appendChild(Z),K.appendChild(pe);let $e=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");zr($e,v?.searchBar);let Re=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),Ce=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");Re&&Ce.appendChild(Re),ee=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"),zr(ee,v?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",me=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),$e.appendChild(Ce),$e.appendChild(ee),$e.appendChild(me),$.appendChild(K),$.appendChild($e),ke&&$.appendChild(ke),$}let Ue,Qe=s.find($=>$.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Ue=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:K=>{B=K,Le(),Te()},onSearchChange:K=>{S=K,Le(),Te()}})??Ne():Ue=Ne();let Oe=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");Oe.style.display="none";function _e(){if(!a||!we||!he)return;let $=a(),K=Bv($);we.textContent=K;let ce=Dv($);ke&&(ke.textContent=ce,ce||(ke.style.display="none")),he.setAttribute("aria-label",ce?`Throughput: ${K}, ${ce}`:`Throughput: ${K}`)}let Ae=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Se=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Se.style.height="100%";let ze=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");zr(ze,v?.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Gt=ae(d,"14px","currentColor",2);Gt&&ze.appendChild(Gt);let gt=b("span","");gt.textContent=c,ze.appendChild(gt);let Ht=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ht.style.display="none",Ae.appendChild(Se),Ae.appendChild(Ht),Ae.appendChild(ze),C.setAttribute("tabindex","0"),C.appendChild(Ue),C.appendChild(Oe),C.appendChild(Ae);function xn(){let $=t.getAll(),K={};for(let $e of $)K[$e.type]=(K[$e.type]||0)+1;let ce=Object.keys(K).sort(),je=ce.length!==P.length||!ce.every(($e,Re)=>$e===P[Re]),de=!je&&ce.some($e=>K[$e]!==H[$e]),Pe=$.length!==Object.values(H).reduce(($e,Re)=>$e+Re,0);if(!je&&!de&&!Pe||(P=ce,H=K,!Z))return;let Ve=Z.value;if(Z.options[0].textContent=`All events (${$.length})`,je){for(;Z.options.length>1;)Z.remove(1);for(let $e of ce){let Re=b("option","");Re.value=$e,Re.textContent=`${$e} (${K[$e]||0})`,Z.appendChild(Re)}Ve&&ce.includes(Ve)?Z.value=Ve:Ve&&(Z.value="",B="")}else for(let $e=1;$e<Z.options.length;$e++){let Re=Z.options[$e];Re.textContent=`${Re.value} (${K[Re.value]||0})`}}function Cn(){let $=t.getAll();if(B&&($=$.filter(K=>K.type===B)),S){let K=S.toLowerCase();$=$.filter(ce=>ce.type.toLowerCase().includes(K)||ce.payload.toLowerCase().includes(K))}return $}function et(){return B!==""||S!==""}function Le(){F=0,z=0,N.resume(),ze.style.display="none"}function ye($){ie.has($)?ie.delete($):ie.add($),ge=$;let K=Se.scrollTop,ce=N.isFollowing();G=!0,N.pause(),Te(),Se.scrollTop=K,ce&&N.resume(),G=!1}function tt(){return eo(Se,50)}function Te(){j=Date.now(),te=!1,_e(),xn();let $=t.getEvictedCount();$>0?(Oe.textContent=`${$.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",T=Cn();let K=T.length,ce=t.getSize()>0;K===0&&ce&&et()?(Ht.textContent=S?`No events matching '${S}'`:"No events matching filter",Ht.style.display="",Se.style.display="none"):(Ht.style.display="none",Se.style.display=""),pe&&(pe.title=et()?`Copy Filtered (${K})`:"Copy All"),u&&!N.isFollowing()&&K>F&&(z+=K-F,gt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",ze.style.display=""),F=K;let je=t.getAll(),de=je.length>0?je[0].timestamp:0,Pe=new Set(T.map(Re=>Re.id));for(let Re of ie)Pe.has(Re)||ie.delete(Re);let Ve=B!==ue||S!==X,$e=Y.size===0&&T.length>0;if(Ve||$e||T.length===0){Se.innerHTML="",Y.clear();let Re=document.createDocumentFragment();for(let Ce=0;Ce<T.length;Ce++){let nt=Mc(T[Ce],Ce,de,f,ie,ye,s,r);Y.set(T[Ce].id,nt),Re.appendChild(nt)}Se.appendChild(Re),ue=B,X=S,ge=null}else{if(ge!==null){let Ce=Y.get(ge);if(Ce&&Ce.parentNode===Se){let nt=T.findIndex(xt=>xt.id===ge);if(nt>=0){let xt=Mc(T[nt],nt,de,f,ie,ye,s,r);Se.insertBefore(xt,Ce),Ce.remove(),Y.set(ge,xt)}}ge=null}let Re=new Set(T.map(Ce=>Ce.id));for(let[Ce,nt]of Y)Re.has(Ce)||(nt.remove(),Y.delete(Ce));for(let Ce=0;Ce<T.length;Ce++){let nt=T[Ce];if(!Y.has(nt.id)){let xt=Mc(nt,Ce,de,f,ie,ye,s,r);Y.set(nt.id,xt),Se.appendChild(xt)}}}N.isFollowing()&&(Se.scrollTop=Se.scrollHeight)}function ve(){if(Date.now()-j>=kv){A!==null&&(cancelAnimationFrame(A),A=null),Te();return}te||(te=!0,A=requestAnimationFrame(()=>{A=null,Te()}))}let re=($,K)=>{if(!pe)return;pe.innerHTML="";let ce=ae($,"12px","currentColor",1.5);ce&&pe.appendChild(ce);let je=b("span","persona-text-xs");je.textContent="Copy All",pe.appendChild(je),setTimeout(()=>{pe.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&pe.appendChild(de);let Pe=b("span","persona-text-xs");Pe.textContent="Copy All",pe.appendChild(Pe),pe.disabled=!1},K)},xe=async()=>{if(pe){pe.disabled=!0;try{let $;et()?$=T:n?($=await n(),$.length===0&&($=t.getAll())):$=t.getAll();let K=$.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),re("check",1500)}catch{re("x",1500)}}},An=()=>{Z&&(B=Z.value,Le(),Te())},ne=()=>{!ee||!me||(me.style.display=ee.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{S=ee.value,Le(),Te()},150))},M=()=>{!ee||!me||(ee.value="",S="",me.style.display="none",k&&clearTimeout(k),Le(),Te())},I=()=>{if(G)return;let $=Se.scrollTop,{action:K,nextLastScrollTop:ce}=fi({following:N.isFollowing(),currentScrollTop:$,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,K==="resume"?(N.resume(),z=0,ze.style.display="none"):K==="pause"&&(N.pause(),u&&(gt.textContent=c,ze.style.display=""))},h=$=>{let K=gi({following:N.isFollowing(),deltaY:$.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});K==="pause"?(N.pause(),u&&(gt.textContent=c,ze.style.display="")):K==="resume"&&(N.resume(),z=0,ze.style.display="none")},W=()=>{u&&(Se.scrollTop=Se.scrollHeight,N.resume(),z=0,ze.style.display="none")},L=$=>{let K=$.target;if(!K||K.closest("button"))return;let ce=K.closest("[data-event-id]");if(!ce)return;let je=ce.getAttribute("data-event-id");je&&ye(je)},R=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),ee?.focus(),ee?.select();return}$.key==="Escape"&&(ee&&document.activeElement===ee?(M(),ee.blur(),C.focus()):o&&o())};pe&&pe.addEventListener("click",xe),Z&&Z.addEventListener("change",An),ee&&ee.addEventListener("input",ne),me&&me.addEventListener("click",M),Se.addEventListener("scroll",I),Se.addEventListener("wheel",h,{passive:!0}),Se.addEventListener("click",L),ze.addEventListener("click",W),C.addEventListener("keydown",R);function q(){k&&clearTimeout(k),A!==null&&(cancelAnimationFrame(A),A=null),te=!1,Y.clear(),pe&&pe.removeEventListener("click",xe),Z&&Z.removeEventListener("change",An),ee&&ee.removeEventListener("input",ne),me&&me.removeEventListener("click",M),Se.removeEventListener("scroll",I),Se.removeEventListener("wheel",h),Se.removeEventListener("click",L),ze.removeEventListener("click",W),C.removeEventListener("keydown",R)}return{element:C,update:ve,destroy:q}}}function Jf(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},u=f=>{let w=f;return s.findIndex(g=>g===w||g.contains(w))},d=f=>{let w=u(f.target);if(w<0)return;let g=w;if(f.key===r)g=Math.min(w+1,s.length-1);else if(f.key===o)g=Math.max(w-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==w&&t.onSelect(g)},c=f=>{let w=u(f.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(f,w){if(s=f,f.forEach((g,v)=>{g.setAttribute("role","tab");let C=v===w;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||w<0&&v===0?0:-1}),a){let g=(w>=0?f[w]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Zf(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),u=n?.tabFadeSize?.trim(),d=ne=>({start:ne===!1?!1:typeof ne=="object"&&ne?ne.start!==!1:!0,end:ne===!1?!1:typeof ne=="object"&&ne?ne.end!==!1:!0}),{start:c,end:f}=d(n?.tabFade),w=typeof document<"u"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),G?.hide()};w&&w.addEventListener("click",()=>{g(),t.onDismiss?.()});let v=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");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let T=b("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let B=Wt({icon:"x",label:a});B.addEventListener("click",()=>{g(),t.onDismiss?.()});let S="rendered",k=ii({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:ne=>{S=ne==="source"?"source":"rendered",re()}}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=n?.documentToolbarShowCopyLabel===!0,F=n?.documentToolbarShowCopyChevron===!0,N=n?.documentToolbarCopyMenuItems,z=!!(F&&N&&N.length>0),j=null,te,A=null,G=null;if(r&&(H||F)&&!z){if(te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F){let ne=ae("chevron-down",14,"currentColor",2);ne&&te.appendChild(ne)}}else r&&z?(j=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=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(te,A)):r?te=Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(te=Wt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&te.classList.add("persona-hidden"));let Q=r?Wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wt({icon:"refresh-cw",label:"Refresh"}),ie=r?Wt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Wt({icon:"x",label:a}),Y=Wt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Y.classList.add("persona-hidden");let ue=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),X=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ne=Ae.find(W=>W.id===Se)??Ae[Ae.length-1],M=ne?.id??null,I=ne?.artifactType==="markdown"?ne.markdown??"":"",h=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:I,jsonPayload:h,id:M}},Z=async()=>{let ne=Ae.find(M=>M.id===Se)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(Ns(ne))}catch{}};if(te.addEventListener("click",async()=>{let ne=n?.onDocumentToolbarCopyMenuSelect;if(ne&&z){let{markdown:M,jsonPayload:I,id:h}=ge();try{await ne({actionId:"primary",artifactId:h,markdown:M,jsonPayload:I})}catch{}return}await Z()}),A&&N?.length){let ne=()=>v.closest("[data-persona-root]")??document.body,M=()=>{G=Dr({items:N.map(I=>({id:I.id,label:I.label})),onSelect:async I=>{let{markdown:h,jsonPayload:W,id:L}=ge(),R=n?.onDocumentToolbarCopyMenuSelect;try{R?await R({actionId:I,artifactId:L,markdown:h,jsonPayload:W}):I==="markdown"||I==="md"?await navigator.clipboard.writeText(h):I==="json"||I==="source"?await navigator.clipboard.writeText(W):await navigator.clipboard.writeText(h||W)}catch{}},anchor:j??A,position:"bottom-right",portal:ne()})};v.isConnected?M():requestAnimationFrame(M),A.addEventListener("click",I=>{I.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),ie.addEventListener("click",()=>{g(),t.onDismiss?.()});let pe=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),j?P.append(j,Q,ie):P.append(te,Q,ie),P.insertBefore(ue,ie),P.insertBefore(Y,ie),C.append(k.element,pe,P);else{let ne=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ne.append(te,ue,Y,B),C.appendChild(T),C.appendChild(ne)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ee=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");u&&ee.style.setProperty("--persona-artifact-tab-fade-size",u);let me=e.features?.artifacts?.renderTabBar,we=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=Jf(ee,{onSelect:ne=>t.onSelect(Ae[ne].id)}),ke=ne=>{let M=ne.scrollWidth-ne.clientWidth,I=M>1,h=Math.abs(ne.scrollLeft);ne.classList.toggle("persona-artifact-tab-fade-start",c&&I&&h>1),ne.classList.toggle("persona-artifact-tab-fade-end",f&&I&&h<M-1)},Ne=0,Ue=()=>{if(Ne)return;let ne=()=>{Ne=0,ke(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ne):setTimeout(ne,0)};ee.addEventListener("scroll",()=>Ue(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(ee)).observe(ee);let Qe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Oe=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Oe):setTimeout(Oe,0)};if(l){for(let ne of[ee,we])ne.style.paddingLeft=l,ne.style.paddingRight=l;Qe.style.padding=l}v.appendChild(C),v.appendChild(ee),v.appendChild(we),v.appendChild(Qe);let Ae=[],Se=null,ze=!1,Gt=!1,gt=!0,Ht=!1,xn=null,Cn="",et=null,Le=!1,ye=ne=>ne.artifactType==="markdown"&&!!ne.file||r?S:"rendered",tt=ne=>{r||(ne&&!Le?(C.insertBefore(k.element,T),Le=!0):!ne&&Le&&(k.element.remove(),Le=!1))},Te=()=>Se&&Ae.find(ne=>ne.id===Se)||Ae[Ae.length-1],ve=()=>{let ne=Fs(Te());if(!ne){ue.replaceChildren();return}let M=X.filter(I=>I.visible===void 0||I.visible(ne)).map(I=>Fr(I,{documentChrome:r,onClick:()=>{let h=Fs(Te());if(h)try{Promise.resolve(I.onClick(h)).catch(()=>{})}catch{}}}));ue.replaceChildren(...M)},re=()=>{ve();let ne=r&&Ae.length<=1,M=!!me;if(ee.classList.toggle("persona-hidden",ne||M),we.classList.toggle("persona-hidden",ne||!M),M&&me){let W=Ae.map(L=>L.id).join("|")+" "+(Se??"");if(W!==Cn){Cn=W;let L=me({records:Ae,selectedId:Se,onSelect:t.onSelect});we.firstElementChild!==L&&we.replaceChildren(L)}}else{he.beforeRender(),ee.replaceChildren();let W=[],L=-1;for(let[R,q]of Ae.entries()){let $=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");$.type="button";let K=q.artifactType==="markdown"?q.file:void 0,ce=K?Bn(K.path):q.title||q.id.slice(0,8),je=K?.path||q.title||ce;$.textContent=ce,$.title=je,$.setAttribute("aria-label",je),q.id===Se&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=R),$.addEventListener("click",()=>t.onSelect(q.id)),ee.appendChild($),W.push($)}if(he.render(W,L),L>=0&&Se!==xn){xn=Se;let R=W[L];typeof R.scrollIntoView=="function"&&R.scrollIntoView({block:"nearest",inline:"nearest"})}ke(ee)}let I=Se&&Ae.find(W=>W.id===Se)||Ae[Ae.length-1];if(!I){Qe.replaceChildren(),et=null,tt(!1);return}let h=I.artifactType==="markdown"?I.file:void 0;if(tt(!!h&&Yo(h)!=="other"),r){let W=h?Co(h):I.artifactType==="markdown"?"MD":I.component??"Component",L=(I.title||"Document").trim(),R=h?Bn(h.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${R} \xB7 ${W}`}else T.textContent=h?Bn(h.path):s;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(I)):(et=di(I,{config:e,resolveViewMode:ye}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ne=Ae.length>0;if(v.classList.toggle("persona-hidden",!ne),w){let h=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ne&&h&&ze?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},An=()=>{Ht=!1,re(),xe()};return{element:v,backdrop:w,update(ne){let M=ne.selectedId??ne.artifacts[ne.artifacts.length-1]?.id??null,I=M!==Se;Ae=ne.artifacts,Se=M,Ae.length>0&&(ze=!0),Ht=!0,gt&&An(),I&&Oe()},setMobileOpen(ne){ze=ne,!ne&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ne){ne!==Gt&&(Gt=ne,_e());let M=ae(ne?"minimize":"maximize",16,"currentColor",2);M&&Y.replaceChildren(M);let I=ne?"Collapse artifacts panel":"Expand artifacts panel";Y.setAttribute("aria-label",I),Y.title=I},setExpandToggleVisible(ne){Y.classList.toggle("persona-hidden",!ne)},setCopyButtonVisible(ne){r||te.classList.toggle("persona-hidden",!ne)},setCustomActions(ne){X=ne,ve()},setTabFade(ne){let M=d(ne);M.start===c&&M.end===f||(c=M.start,f=M.end,ke(ee))},setRenderTabBar(ne){ne!==me&&(me=ne,Cn="",re())},setVisible(ne){ne!==gt&&(gt=ne,ne&&Ht&&An())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function eg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Ov(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var tg=["panel","seamless","detached"];function Ec(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&tg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function kc(e){return!e||!Jt(e)?!1:Ec(e)==="detached"}function ea(e,t){if(!Jt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Ov(e),eg(e,t);return}let n=t.features?.artifacts?.layout,o=Ec(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let u=n?.documentToolbarToggleActiveBorderColor?.trim();u?e.style.setProperty("--persona-artifact-doc-toggle-active-border",u):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),eg(e,t)}function ta(e,t){for(let l of tg)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=Ec(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ng(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Nv=new Set(["__proto__","prototype","constructor"]),_v=new Set(["collapsed","card","panel","inline"]),og=new Set(["markdown","component"]),$v=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Di=e=>!Nv.has(e),Lc=e=>typeof e=="string"&&_v.has(e),rr=e=>Object.keys(e).length>0;function Fn(e,t,n,o){e.push({path:t,code:n,message:o})}var Uv="Ignored because this key is not part of the persisted preference schema.",Bi="Ignored an unsupported value.",zv="Expected collapsed, panel, or inline.",jv='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',rg={kind:"mode",message:Bi},jr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},Vv={paneWidth:jr,paneMaxWidth:jr,paneMinWidth:jr,expandedPanelWidth:jr,resizableMinWidth:jr,resizableMaxWidth:jr,expandLauncherPanelWhenOpen:to,resizable:to},qv={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Bi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Bi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Bi},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:rg,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:rg,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:og,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:og}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:Vv}}}}};function sg(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Fn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Fn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Fn(o,n,"invalid_value",t.message);case"mode":return Lc(e)?yn(e):Fn(o,n,"invalid_value",t.message);case"modeMap":{if(!or(e))return Fn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let u=r?a:Ar(a);Di(a)&&(r?r.has(a):$v.test(u))?Lc(l)?s[u]=yn(l):Fn(o,`${n}.${a}`,"invalid_value",zv):Fn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":jv)}return rr(s)?s:void 0}case"object":{if(t.bareMode&&Lc(e))return yn(e);if(!or(e))return Fn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Di(l)||!r.includes(l))&&Fn(o,s(l),"unknown_key",Uv);let a={};for(let l of r){let u=t.children[l],d=sg(e[l],u,s(l),o);if(u.deprecated&&e[l]!==void 0&&Fn(o,s(l),"deprecated_key",u.deprecated),d===void 0)continue;let c=u.alias??l,f=a[c];a[c]=or(f)&&or(d)?{...f,...d}:d}return rr(a)?a:void 0}}}function Kv(e){let t=[];return{preferences:(e===null?void 0:sg(e,qv,"",t))??{},issues:t}}function Vr(e){if(Array.isArray(e))return e.map(Vr);if(!or(e))return e;let t={};for(let[n,o]of Object.entries(e))Di(n)&&o!==void 0&&(t[n]=Vr(o));return t}function ag(e,t){let n=Vr(e);for(let[o,r]of Object.entries(t)){if(!Di(o)||r===void 0)continue;let s=n[o];n[o]=or(s)&&or(r)?ag(s,r):Vr(r)}return n}function Gv(e){let t={},n;for(let r of e){let s=Kv(r).preferences;n=ig(n,s.artifacts?.display),t=ag(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Yv(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...rr(r)?{byMediaType:r}:{}};return rr(s)?s:void 0}function ig(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Yv(n.files,t.files),a={...o?{default:o}:{},...rr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return rr(a)?a:void 0}function Xv(e={},t){let n=Gv(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=ig(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Pc(e){let t=e.preferences;return!t||!rr(t)?e:{...e,features:Xv(e.features??{},[t])}}function Qv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Jv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Zv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ew(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ic(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function lg(e,t,n,o,r,s){let a=Qv(r,200),l=ew(t,n,o,200);l=Math.max(a,l);let u=Jv(s);return u!==null&&(l=Math.min(l,u)),Zv(e,a,l)}var cg={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"}},Wc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=cg[a]??cg.init;s.classList.add("persona-form-card","persona-space-y-4");let u=b("div","persona-space-y-1"),d=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,u.appendChild(d),l.description){let v=b("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,u.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${v.name}`;let T=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=v.label,C.appendChild(T);let B=v.type??"text",S;B==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=B),S.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",S.id=`${t.id}-${a}-${v.name}`,S.name=v.name,S.placeholder=v.placeholder??"",v.required&&(S.required=!0),C.appendChild(S),c.appendChild(C)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=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");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(w),f.appendChild(g),c.appendChild(f),s.replaceChildren(u,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",T=new FormData(c),B={};T.forEach((S,k)=>{B[k]=S}),B.type=a,g.disabled=!0,w.textContent="Submitting\u2026";try{let S=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let k=await S.json();w.textContent=k.message??"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(S){w.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Rc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Hc=new Rc;var dg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tw=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),pg=(e,t,n)=>{if(!dg(e)||!dg(t)||tw.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=pg(e[r],t[r],s)}return o};function ug(e,t){let n=pg(e,t,"");return ei(n)}var fg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var nw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ow=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Dc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=nw(e),n=ow(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Bc=e=>typeof e=="string"?e:e==null?"":String(e),na={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Bc(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Bc(n.text)}}},gg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fc=e=>{let t=new Set(gg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let u={action:l,message:s.message};e.emit("action:detected",u);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",u)},f=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var rw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},sw=e=>e.map(t=>({...t,streaming:!1})),aw=e=>e.map(t=>({...t,status:"complete"})),mg=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?rw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?sw(n.messages):void 0,artifacts:n.artifacts?aw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as rM,STR as sM,OBJ as aM}from"partial-json";function hg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function yg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Oc(e){let t=yg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function bg(e){let t=yg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vg(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,ratingLabels:d=iw}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let f=null,w=document.createElement("div");w.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,g.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),w.appendChild(g);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 F=1;F<=5;F++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${F} star${F>1?"s":""}: ${d[F-1]}`),N.title=d[F-1],N.dataset.rating=String(F),N.innerHTML=`
|
|
43
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
44
44
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
45
45
|
</svg>
|
|
46
|
-
`,x.addEventListener("click",()=>{u=G,B.forEach((j,U)=>{let oe=U<G;j.classList.toggle("selected",oe),j.setAttribute("aria-checked",U===G-1?"true":"false")})}),B.push(x),R.appendChild(x)}w.appendChild(R);let L=null;if(p){let G=document.createElement("div");G.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),G.appendChild(L),w.appendChild(G)}let E=document.createElement("div");E.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),c.remove()});let _=document.createElement("button");return _.type="button",_.className="persona-feedback-btn persona-feedback-btn-submit",_.textContent=a,_.addEventListener("click",async()=>{if(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let G=L?.value.trim()||void 0;await t(u,G),c.remove()}catch(G){_.disabled=!1,_.textContent=a,console.error("[CSAT Feedback] Failed to submit:",G)}}),E.appendChild(M),E.appendChild(_),w.appendChild(E),c.appendChild(w),c}function qu(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let R=document.createElement("p");R.className="persona-feedback-subtitle",R.textContent=r,v.appendChild(R),f.appendChild(v);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=c,L.appendChild(E),L.appendChild(M);let _=document.createElement("div");_.className="persona-feedback-numbers";let G=[];for(let F=0;F<=10;F++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${F} out of 10`),$.textContent=String(F),$.dataset.rating=String(F),F<=6?$.classList.add("persona-feedback-detractor"):F<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{w=F,G.forEach((X,me)=>{X.classList.toggle("selected",me===F),X.setAttribute("aria-checked",me===F?"true":"false")})}),G.push($),_.appendChild($)}B.appendChild(L),B.appendChild(_),f.appendChild(B);let x=null;if(p){let F=document.createElement("div");F.className="persona-feedback-comment-container",x=document.createElement("textarea"),x.className="persona-feedback-comment",x.placeholder=s,x.rows=3,x.setAttribute("aria-label","Additional comments"),F.appendChild(x),f.appendChild(F)}let j=document.createElement("div");j.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=l,U.addEventListener("click",()=>{n?.(),u.remove()});let oe=document.createElement("button");return oe.type="button",oe.className="persona-feedback-btn persona-feedback-btn-submit",oe.textContent=a,oe.addEventListener("click",async()=>{if(w===null){_.classList.add("persona-feedback-shake"),setTimeout(()=>_.classList.remove("persona-feedback-shake"),500);return}oe.disabled=!0,oe.textContent="Submitting...";try{let F=x?.value.trim()||void 0;await t(w,F),u.remove()}catch(F){oe.disabled=!1,oe.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),j.appendChild(U),j.appendChild(oe),f.appendChild(j),u.appendChild(f),u}var xr="persona-chat-history",rb=30*1e3,sb=641,ab={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function ib(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=ab[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function li(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function lb(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function cb(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Vl=e=>!e||typeof e!="object"?{}:{...e},Ku=e=>e.map(t=>({...t,streaming:!1})),Gu=(e,t,n)=>{let o=e?.markdown?ca(e.markdown):null,r=da(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Fn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?bd(a):a,u=o(c);d=r&&p?r(u):u}else d=oo(a);return d}};function Qu(e){let t=h("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ie(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=h("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var db=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},pb=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:db(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Xu=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ka(t),r=o.features;o=Dl(o);let s=_l.getForInstance(o.plugins),{plugin:a,teardown:l}=bu();o.components&&zn.registerAll(o.components);let p=Ou(),c=o.persistState===!1?null:o.storageAdapter??$u(),u={},w=null,f=!1,v=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:m,open:b}=g;return b&&(f=!0),m}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")w=i.then(g=>v(g??{messages:[],metadata:{}}));else{let m=v(i??{messages:[],metadata:{}});m.metadata&&(u=Vl(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=v({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let C=()=>u,R=i=>{u=i({...u})??{},Si()},B=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick],E=jl({parsers:B,handlers:L,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,G=o.autoFocusInput??!1,x=_,j=M,U=o.layout?.header?.layout,oe=!1,F=()=>vs(o),$=()=>M||F(),X=F()?!1:M?_:!0,me=!1,he=null,Ae=()=>{me=!0,he&&clearTimeout(he),he=setTimeout(()=>{me&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),me=!1)},1e4)},Z=Gu(o,E,Ae),ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Y=o.features?.scrollToBottom??{},pe=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ve=le?new As(ye):null,je=o.features?.eventStream?.maxEvents??2e3,Me=le?new Cs(je,ve):null,De=le?new Ss:null,Qe=null,Ve=!1,Te=null,Le=0;ve?.open().then(()=>Me?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Xe={onCopy:i=>{p.emit("message:copy",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},It=i=>i==="idle"?Ht.idleText??Lt.idle:i==="connecting"?Ht.connectingText??Lt.connecting:i==="connected"?Ht.connectedText??Lt.connected:i==="error"?Ht.errorText??Lt.error:i==="paused"?Ht.pausedText??Lt.paused:i==="resuming"?Ht.resumingText??Lt.resuming:Lt[i];function qt(i,g,m,b){if(b==="idle"&&m.idleLink){i.textContent="";let A=document.createElement("a");A.href=m.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=g,A.style.color="inherit",A.style.textDecoration="none",i.appendChild(A)}else i.textContent=g}let xt=au({config:o,showClose:$()}),{wrapper:He,panel:de,pillRoot:et}=xt.shell,Ie=xt.panelElements,{container:fe,body:se,messagesWrapper:Pe,suggestions:it,textarea:ue,sendButton:Ce,sendButtonWrapper:te,composerForm:S,statusText:D,introTitle:y,introSubtitle:P,closeButton:T,iconHolder:I,headerTitle:q,headerSubtitle:H,header:z,footer:J,actionsRow:qe,rightActions:Re}=Ie,Je=Ie.leftActions,rt=Ie.setSendButtonMode,V=Ie.micButton,_e=Ie.micButtonWrapper,be=Ie.attachmentButton,$e=Ie.attachmentButtonWrapper,Fe=Ie.attachmentInput,Rt=Ie.attachmentPreviewsContainer;fe.classList.add("persona-relative"),se.classList.add("persona-relative");let di=12,go=()=>Y.label??"",Ls=()=>Y.iconName??"arrow-down",Ps=()=>Y.enabled!==!1,sn=()=>pe.mode??"anchor-top",Un=()=>sn()==="follow"||sn()==="anchor-top"&&Rr,Yl=()=>pe.anchorTopOffset??16,cf=()=>pe.restorePosition??"bottom",Zl=()=>pe.pauseOnInteraction===!0,ec=()=>pe.showActivityWhilePinned!==!1,tc=()=>pe.announce===!0,Tt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Ar=h("span","persona-flex persona-items-center"),pi=h("span",""),mo=h("span","");mo.setAttribute("data-persona-scroll-to-bottom-count",""),mo.style.display="none",Tt.append(Ar,pi,mo),fe.appendChild(Tt);let Vn=h("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",se.appendChild(Vn);let ho=h("div","persona-sr-only");ho.setAttribute("aria-live","polite"),ho.setAttribute("aria-atomic","true"),ho.setAttribute("role","status"),ho.setAttribute("data-persona-live-region",""),Object.assign(ho.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(ho);let Sr=null,Is=null,nc=i=>{!tc()||!i||(Is=i,Sr===null&&(Sr=setTimeout(()=>{Sr=null,Is&&tc()&&(ho.textContent=Is),Is=null},400)))},_o=()=>{let g=J.style.display==="none"?0:J.offsetHeight;Tt.style.bottom=`${g+di}px`};_o();let oc=()=>{let i=!!go();Tt.setAttribute("aria-label",go()||"Jump to latest"),Tt.title=go(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Ar.innerHTML="";let g=ie(Ls(),"14px","currentColor",2);g?(Ar.appendChild(g),Ar.style.display=""):Ar.style.display="none",pi.textContent=go(),pi.style.display=i?"":"none"};oc();let Ct=null,Zt=null,rc=null,sc=s.find(i=>i.renderHeader);if(sc?.renderHeader){let i=sc.renderHeader({config:o,defaultRenderer:()=>{let g=Ho({config:o,showClose:$()});return ws(fe,g,o),g.header},onClose:()=>dt(!1,"user")});if(i){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),z=i,xt.header.element=i)}}let ui=()=>{if(!Me)return;if(Ve=!0,!Qe&&Me&&(Qe=Au({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Tr(),config:o,plugins:s,getThroughput:()=>De?.getMetric()??{status:"idle"}})),Qe&&(se.style.display="none",J.parentNode?.insertBefore(Qe.element,J),Qe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Qt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(m=>m&&tt.classList.add(m))}let i=()=>{if(!Ve)return;let g=Date.now();g-Le>=200&&(Qe?.update(),Le=g),Te=requestAnimationFrame(i)};Le=0,Te=requestAnimationFrame(i),tn(),p.emit("eventStream:opened",{timestamp:Date.now()})},Tr=()=>{if(Ve){if(Ve=!1,Qe&&Qe.element.remove(),se.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&tt.classList.remove(g))}Te!==null&&(cancelAnimationFrame(Te),Te=null),tn(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){let i=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");tt=h("button",g),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let m=ie("activity","18px","currentColor",1.5);m&&tt.appendChild(m);let b=Ie.clearChatButtonWrapper,A=Ie.closeButtonWrapper,k=b||A;k&&k.parentNode===z?z.insertBefore(tt,k):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}let df=i=>{let g=o.attachments;if(!g?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let A=i.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(m,A):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let A=h("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??_n).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(A)}},ac=s.find(i=>i.renderComposer);if(ac?.renderComposer){let i=o.composer,g=ac.renderComposer({config:o,defaultRenderer:()=>ni({config:o}).footer,onSubmit:m=>{if(!O||O.isStreaming())return;let b=m.trim(),A=Ct?.hasAttachments()??!1;if(!b&&!A)return;Dc();let k;A&&(k=[],k.push(...Ct.getContentParts()),b&&k.push(ar(b))),O.sendMessage(b,{contentParts:k}),A&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{rc?.()}:void 0});g&&(xt.replaceComposer(g),J=xt.composer.footer)}let pf=i=>{let g=(...ge)=>{for(let re of ge){let we=i.querySelector(re);if(we)return we}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),A=i.querySelector("[data-persona-composer-submit]"),k=i.querySelector("[data-persona-composer-mic]"),Q=i.querySelector("[data-persona-composer-status]");m&&(S=m),b&&(ue=b),A&&(Ce=A),k&&(V=k,_e=k.parentElement),Q&&(D=Q);let N=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(it=N);let K=g("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(be=K,$e=K.parentElement),Fe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Rt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(qe=ae),Je=g(".persona-widget-composer__left-actions")};df(J),pf(J);let qn=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(qn&&(Pe.style.maxWidth=qn,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%"),qn&&S&&!F()&&(S.style.maxWidth=qn,S.style.marginLeft="auto",S.style.marginRight="auto"),qn&&it&&!F()&&(it.style.maxWidth=qn,it.style.marginLeft="auto",it.style.marginRight="auto"),qn&&Rt&&!F()&&(Rt.style.maxWidth=qn,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Rt){Ct=as.fromConfig(o.attachments),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,g=Qu(i);fe.appendChild(g)}let uf=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&ue&&(Zt=fp({config:o,textarea:ue,anchor:S??ue,getMessages:()=>O.getMessages(),liveRegionHost:fe}),Zt)){let i=ue;i.parentElement?.insertBefore(Zt.contextRow,i);let g=Zt.affordanceButtons;for(let m=g.length-1;m>=0;m--){let b=g[m];Je?Je.insertBefore(b,Je.firstChild):S?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},g=b=>{switch(b){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Pe;case"footer-top":return it;case"composer":return S;case"footer-bottom":return D;default:return null}},m=(b,A)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")z.insertBefore(A,z.firstChild);else if(b==="header-right")z.appendChild(A);else{let k=z.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(A,k.nextSibling):z.appendChild(A)}break;case"body-top":{let k=se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");k?k.replaceWith(A):se.insertBefore(A,se.firstChild);break}case"body-bottom":se.appendChild(A);break;case"footer-top":it.replaceWith(A);break;case"footer-bottom":D.replaceWith(A);break;default:break}};for(let[b,A]of Object.entries(i))if(A)try{let k=A({config:o,defaultContent:()=>g(b)});k&&m(b,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,k)}})();let ic=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let k=m.getAttribute("data-bubble-type");if(k==="reasoning")hr.has(A)?hr.delete(A):hr.add(A),pu(A,b);else if(k==="tool")yr.has(A)?yr.delete(A):yr.add(A),uu(A,b,o);else if(k==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=Bo.get(A)??N;Bo.set(A,!K),hu(A,b,o)}wo.delete(A)};Pe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ic(i))}),Pe.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let m=Pe.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let A=b.toString(),k=$p(A);!k||k===A||(g.setData("text/plain",k),i.preventDefault())});let fi=new Map,lc=null,cc="idle",ff={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},gf=(i,g)=>{let{icon:m,label:b}=ff[g];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",g==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",g!=="idle"),i.classList.toggle("persona-message-action-loading",g==="loading");let A=ie(m,14,"currentColor",2);A&&(i.innerHTML="",i.appendChild(A))},dc=()=>{Pe.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let b=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;gf(g,b&&b===lc?cc:"idle")})};Pe.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let A=b.getAttribute("data-actions-for");if(!A)return;let k=m.getAttribute("data-action");if(k==="copy"){let N=O.getMessages().find(K=>K.id===A);if(N&&Xe.onCopy){let K=N.content||"";navigator.clipboard.writeText(K).then(()=>{m.classList.add("persona-message-action-success");let ae=ie("check",14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let ge=ie("copy",14,"currentColor",2);ge&&(m.innerHTML="",m.appendChild(ge))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),Xe.onCopy(N)}}else if(k==="read-aloud")O.toggleReadAloud(A);else if(k==="upvote"||k==="downvote"){let N=(fi.get(A)??null)===k,K=k==="upvote"?"thumbs-up":"thumbs-down";if(N){fi.delete(A),m.classList.remove("persona-message-action-active");let ae=ie(K,14,"currentColor",2);ae&&(m.innerHTML="",m.appendChild(ae))}else{let ae=k==="upvote"?"downvote":"upvote",ge=b.querySelector(`[data-action="${ae}"]`);if(ge){ge.classList.remove("persona-message-action-active");let nt=ie(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ge.innerHTML="",ge.appendChild(nt))}fi.set(A,k),m.classList.add("persona-message-action-active");let re=ie(K,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(re)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=O.getMessages().find(pt=>pt.id===A);Ue&&Xe.onFeedback&&Xe.onFeedback({type:k,messageId:Ue.id,message:Ue})}}}),Pe.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let A=b.getAttribute("data-message-id");if(!A)return;let k=m.getAttribute("data-approval-action");if(!k)return;let Q=k==="approve"?"approved":"denied",K=O.getMessages().find(ge=>ge.id===A);if(!K?.approval)return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?O.resolveWebMcpApproval(A,Q):O.resolveApproval(K.approval,Q)});let Ye=null,Mr=null,Er=()=>{},kr="none",Rs=null,mn={artifacts:[],selectedId:null},Ln=!1,hn=!1,Lr=!1,$o=!1,pc=()=>$o||mn.artifacts.some(i=>ro(o.features?.artifacts,i)==="panel"),Ws=()=>mn.artifacts.length>0&&!Ln&&pc(),lt={current:null},gi=(i,g)=>{let m=O.getArtifactById(g),b=m?.markdown,A=m?.title||"artifact",k=m?.file,Q=m?.artifactType??"markdown";if(!b){let ae=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let re=O.getMessages().find(we=>we.id===ae);if(re?.rawContent)try{let we=JSON.parse(re.rawContent);b=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(k=we.props.file),!m&&typeof we?.props?.artifactType=="string"&&(Q=we.props.artifactType)}catch{}}}return{markdown:b,title:A,file:k,artifactType:Q}};Pe.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:k,title:Q,file:N}=gi(m,b);if(!k)return;let{filename:K,mime:ae,content:ge}=Ap({title:Q,markdown:k,file:N}),re=new Blob([ge],{type:ae}),we=URL.createObjectURL(re),Ue=document.createElement("a");Ue.href=we,Ue.download=K,Ue.click(),URL.revokeObjectURL(we)}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let A=m.closest("[data-artifact-inline]"),k=A?null:m.closest("[data-open-artifact]"),Q=A?A.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,K=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===b);if(!K)return;let{markdown:ae,title:ge,file:re,artifactType:we}=gi(m,Q??""),Ue={artifactId:Q,title:ge,artifactType:we,markdown:ae,file:re};try{Promise.resolve(K.onClick(Ue)).catch(()=>{})}catch{}}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let A=O.getArtifactById(b),k="";if(A)k=fs(A);else{let{markdown:Q,file:N,artifactType:K}=gi(m,b);K==="markdown"&&(k=fs({id:b,artifactType:"markdown",status:"complete",markdown:Q??"",...N?{file:N}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let Q=ie("check",16,"currentColor",2);Q&&(m.replaceChildren(Q),setTimeout(()=>{let N=ie("copy",16,"currentColor",2);N&&m.replaceChildren(N)},1500))}).catch(()=>{})}),Pe.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(Ln=!1,$o=!0,hn=!0,Lr=!0,O.selectArtifact(b),Pn())}),Pe.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let m=g.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),Ln=!1,$o=!0,O.selectArtifact(b),Pn())}),Pe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let zo=Ie.composerOverlay,jo=(i,g,m)=>{let b=g.trim();if(!b||!lt.current)return;let A=i.getAttribute("data-tool-call-id")??"",k=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:k,source:m.source},bubbles:!0,composed:!0})),rr(zo,A);let Q=lt.current.getMessages().find(N=>N.toolCall?.id===A);Q?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(Q,m.structured??b):lt.current.sendMessage(b)},yo=i=>{let g=lt.current;if(!g)return;let m=i.getAttribute("data-tool-call-id")??"",b=g.getMessages().find(A=>A.toolCall?.id===m);b&&g.persistAskUserQuestionProgress(b,{answers:fa(i,b),currentIndex:fn(i)})},uc=i=>Object.entries(i).map(([g,m])=>`${g}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),mi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=fn(i),m=or(i);if(g>=m-1)return;let b=lt.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(ma(i,b,o,g+1),yo(i))};zo.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;let A=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),A==="dismiss"){let k=b.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k);let Q=lt.current?.getMessages().find(N=>N.toolCall?.id===k);Q?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(Q),lt.current?.resolveAskUserQuestion(Q,"(dismissed)"));return}if(A==="pick"){let k=m.getAttribute("data-option-label");if(!k)return;let Q=b.getAttribute("data-multi-select")==="true",N=so(b);if(N&&Q){let K=Po(b)[fn(b)],ae=new Set(Array.isArray(K)?K:[]);ae.has(k)?ae.delete(k):ae.add(k),ao(b,Array.from(ae)),yo(b);return}if(N){ao(b,k),yo(b),mi(b);return}if(Q){let K=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",K?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!K);let ae=b.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=Xi(b).length===0);return}jo(b,k,{source:"pick",values:[k]});return}if(A==="submit-multi"){let k=Xi(b);if(k.length===0)return;jo(b,k.join(", "),{source:"multi",values:k});return}if(A==="open-free-text"){let k=b.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let Q=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Q.trim())return;if(so(b)){ao(b,Q.trim()),yo(b),mi(b);return}jo(b,Q,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let re=Po(b)[fn(b)];(typeof re!="string"||re!==K)&&ao(b,K)}let ae=A==="next"?1:-1,ge=fn(b)+ae;ma(b,Q,o,ge),yo(b);return}if(A==="submit-all"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(re=>re.toolCall?.id===k);if(!Q)return;let K=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&ao(b,K);let ae=fa(b,Q);lt.current.persistAskUserQuestionProgress(Q,{answers:ae,currentIndex:fn(b)});let ge=uc(ae);jo(b,ge||"(submitted)",{source:"submit-all",structured:ae});return}if(A==="skip"){if(!lt.current)return;let k=b.getAttribute("data-tool-call-id")??"",Q=lt.current.getMessages().find(we=>we.toolCall?.id===k);if(!Q)return;let N=so(b),K=fn(b),ae=or(b),ge=K>=ae-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),rr(zo,k),Q.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(Q),lt.current.resolveAskUserQuestion(Q,"(dismissed)"));return}ao(b,"");let re=b.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),ge){let we=fa(b,Q),Ue=uc(we);jo(b,Ue||"(skipped)",{source:"submit-all",structured:we});return}ma(b,Q,o,K+1),yo(b);return}}),zo.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let A=m.value;if(A.trim()){if(so(b)){ao(b,A.trim()),yo(b),mi(b);return}jo(b,A,{source:"free-text"})}});let fc=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let m=zo.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),k=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];k&&(i.preventDefault(),k.click())};document.addEventListener("keydown",fc);let Kn=null,yt=null,Pr=null,Hs=null,hi=()=>{},gc=!1,Bs="",Ds="";function yi(){Hs?.(),Hs=null}let mc=()=>{if(!Kn||!yt)return;let i=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,m=g.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){yt.style.removeProperty("position"),yt.style.removeProperty("left"),yt.style.removeProperty("top"),yt.style.removeProperty("bottom"),yt.style.removeProperty("width"),yt.style.removeProperty("z-index");return}let b=Kn.firstElementChild;if(!b||b===yt)return;let A=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${A}px`,yt.style.zIndex="5";let k=Fl(Kn,g),Q=b.offsetWidth+k/2-A/2;yt.style.left=`${Math.max(0,Q)}px`},Fs=()=>{},mf=()=>{let i=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>m?!1:M||Dt(o)},Ns=()=>!Xt(o)||!Ws()||e.classList.contains("persona-artifact-narrow-host")||mf()||(e.ownerDocument.defaultView??window).innerWidth<sb?"none":Hl(o)?"detached":"welded",Pn=()=>{if(!Ye||!Xt(o))return;Ts(e,o),Ms(e,o),Fs();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=de.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let m=Ws();Ye.setVisible(m),Ye.update(mn),Ln?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1):mn.artifacts.length>0&&pc()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),hn=!1,Lr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(b),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Lr&&(hn=!1),hn!==gc){let k=Ye.element;hn?(Bs=k.style.width,Ds=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(Bs&&(k.style.width=Bs),Ds&&(k.style.maxWidth=Ds),Bs="",Ds=""),gc=hn}e.classList.toggle("persona-artifact-expanded",hn),Ye.setExpanded(hn);let A=Ns();A!==kr&&(kr=A,Er()),hi()};if(Xt(o)){de.style.position="relative";let i=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(fe),Ye=Tu(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{Ln=!0,Pn()},onToggleExpand:()=>{let m=!hn,b=mn.selectedId??mn.artifacts[mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(hn=m,m||(Lr=!1),Pn())}}),Ye.element.classList.add("persona-hidden"),Kn=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&de.appendChild(Ye.backdrop),de.appendChild(g),hi=()=>{if(!Kn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!yt){let b=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let A=e.ownerDocument,k=A.defaultView??window,Q=N=>{if(!Ye||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;N.preventDefault(),yi();let K=N.clientX,ae=Ye.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,re=Ue=>{let pt=Kn.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),nn=Fl(Kn,k),At=nt?0:b.getBoundingClientRect().width||6,Et=ae-(Ue.clientX-K),W=Hu(Et,pt,nn,At,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ye.element.style.width=`${W}px`,Ye.element.style.maxWidth="none",mc()},we=()=>{A.removeEventListener("pointermove",re),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),Hs=null;try{b.releasePointerCapture(N.pointerId)}catch{}};Hs=we,A.addEventListener("pointermove",re),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{b.setPointerCapture(N.pointerId)}catch{}};b.addEventListener("pointerdown",Q),yt=b,Kn.insertBefore(b,Ye.element),Pr=()=>{b.removeEventListener("pointerdown",Q)}}if(yt){let b=Ws();yt.classList.toggle("persona-hidden",!b),mc()}},Fs=()=>{if(!M||!Ye||(o.launcher?.sidebarMode??!1)||Dt(o)&&gn(o).reveal==="emerge")return;let b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(A&&b.innerWidth<=k||!ku(o,M))return;let Q=o.launcher?.width??o.launcherWidth??$n,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Ws()?(de.style.width=N,de.style.maxWidth=N):(de.style.width=Q,de.style.maxWidth=Q)},typeof ResizeObserver<"u"&&(Mr=new ResizeObserver(()=>{Pn()}),Mr.observe(de))}else de.appendChild(fe);F()&&et&&(Ie.peekBanner&&et.appendChild(Ie.peekBanner),et.appendChild(J)),e.appendChild(He),et&&e.appendChild(et);let Os=()=>{if(F()){de.style.width="100%",de.style.maxWidth="100%";let St=o.launcher?.composerBar??{},Yt=He.dataset.state==="expanded",oa=St.expandedSize??"anchored";if(!(Yt&&oa!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let qr=o.theme?.components?.panel,ra=dr(o),Jo=(Hn,ko)=>Hn==null||Hn===""?ko:Gt(ra,Hn)??Hn,sa="1px solid var(--persona-border)",Oi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Eo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Jo(qr?.border,sa),fe.style.borderRadius=Jo(qr?.borderRadius,Eo),fe.style.boxShadow=Jo(qr?.shadow,Oi),fe.style.overflow="hidden";return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,Q=dr(o),N=(St,Yt)=>St==null||St===""?Yt:Gt(Q,St)??St,K=e.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,re=K.innerWidth<=ge,we=ae&&re&&M,Ue=i&&ae&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",nn=o.launcher?.zIndex??Vt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Et="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ee=A&&!we&&!Ue;Ee?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ne=Ee?At:g||we?"none":At,Se=Ee?Et:we?"none":g?nt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":b?"none":Et;i&&!we&&!Ee&&(Se="none",Ne="none");let wt=Ee?W:g||we?"0":W,ut=N(k?.border,Ne),Bt=N(k?.shadow,Se),ft=N(k?.borderRadius,wt),Jt=Ns(),kt=Jt==="detached",ke=Jt==="welded";e.classList.toggle("persona-artifact-detached-split",kt),e.classList.toggle("persona-artifact-welded-split",ke);let Oe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&Hl(o)&&b&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let ct=kt||vt?"none":Bt,gt=kt?At:ke?"none":ut,Ze=kt?W:ft;vt&&(gt="none",Ze="0");let We=k?.borderRadius!=null&&k.borderRadius!=="",ht=vt&&!We?"0":ft,zt=se.scrollTop;e.style.cssText="",He.style.cssText="",de.style.cssText="",fe.style.cssText="",se.style.cssText="",J.style.cssText="",Ve&&(se.style.display="none"),(m||b)&&(e.style.minWidth="0");let pn=()=>{if(zt<=0)return;(se.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(se.scrollTop===zt)return;let Yt=se.scrollHeight-se.clientHeight;Yt<=0||(se.scrollTop=Math.min(zt,Yt))})};if(we){He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),He.style.cssText=`
|
|
46
|
+
`,N.addEventListener("click",()=>{f=F,B.forEach((z,j)=>{let te=j<F;z.classList.toggle("selected",te),z.setAttribute("aria-checked",j===F-1?"true":"false")})}),B.push(N),T.appendChild(N)}w.appendChild(T);let S=null;if(u){let F=document.createElement("div");F.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"),F.appendChild(S),w.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=l,P.addEventListener("click",()=>{n?.(),c.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=S?.value.trim()||void 0;await t(f,F),c.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",F)}}),k.appendChild(P),k.appendChild(H),w.appendChild(k),c.appendChild(w),c}function wg(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let w=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,v.appendChild(T),g.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 k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=d;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,S.appendChild(k),S.appendChild(P);let H=document.createElement("div");H.className="persona-feedback-numbers";let F=[];for(let A=0;A<=10;A++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${A} out of 10`),G.textContent=String(A),G.dataset.rating=String(A),A<=6?G.classList.add("persona-feedback-detractor"):A<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{w=A,F.forEach((Q,ie)=>{Q.classList.toggle("selected",ie===A),Q.setAttribute("aria-checked",ie===A?"true":"false")})}),F.push(G),H.appendChild(G)}B.appendChild(S),B.appendChild(H),g.appendChild(B);let N=null;if(u){let A=document.createElement("div");A.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),A.appendChild(N),g.appendChild(A)}let z=document.createElement("div");z.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?.(),f.remove()});let te=document.createElement("button");return te.type="button",te.className="persona-feedback-btn persona-feedback-btn-submit",te.textContent=a,te.addEventListener("click",async()=>{if(w===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}te.disabled=!0,te.textContent="Submitting...";try{let A=N?.value.trim()||void 0;await t(w,A),f.remove()}catch(A){te.disabled=!1,te.textContent=a,console.error("[NPS Feedback] Failed to submit:",A)}}),z.appendChild(j),z.appendChild(te),g.appendChild(z),f.appendChild(g),f}var qr="persona-chat-history",lw=30*1e3,cw=641,dw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function pw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=dw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Fi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function uw(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nc=e=>!e||typeof e!="object"?{}:{...e},xg=e=>e.map(t=>({...t,streaming:!1})),Cg=(e,t,n)=>{let o=e?.markdown?Ba(e.markdown):null,r=Da(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let u=Gn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Bp(a):a,f=o(c);d=r&&u?r(f):f}else d=mo(a);return d}};function Ag(e){let t=b("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var gw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},mw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:gw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Sg=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ei(t),r=o.features;o=Pc(o);let s=Hc.getForInstance(o.plugins),a=!1,l=Nf(()=>o),{plugin:u,teardown:d}=Kf();o.components&&Zn.registerAll(o.components);let c=fg(),w=o.persistState===!1?null:o.storageAdapter??mg(),g={},v=null,C=!1,T=i=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(i);if(p&&typeof p=="object"&&"state"in p){let{state:m,open:y}=p;return y&&(C=!0),m}return p}catch(p){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return i};if(w?.load)try{let i=w.load();if(i&&typeof i.then=="function")v=i.then(p=>T(p??{messages:[],metadata:{}}));else{let m=T(i??{messages:[],metadata:{}});m.metadata&&(g=Nc(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let B=()=>g,S=i=>{g=i({...g})??{},nl()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick],H=Fc({parsers:k,handlers:P,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null});H.syncFromMetadata();let F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,j=N,te=F,A=o.layout?.header?.layout,G=!1,Q=()=>Vs(o),ie=()=>F||Q(),Y=Q()?!1:F?N:!0,ue=!1,X=null,ge=()=>{ue=!0,X&&clearTimeout(X),X=setTimeout(()=>{ue&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ue=!1)},1e4)},Z=Cg(o,H,ge),pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,we=o.features?.scrollToBottom??{},he=o.features?.scrollBehavior??{},Ne=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ue=me?new Js(Ne):null,Qe=o.features?.eventStream?.maxEvents??2e3,Oe=me?new Qs(Qe,Ue):null,_e=me?new Zs:null,Ae=null,Se=!1,ze=null,Gt=0;Ue?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",p)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",p)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},xn=i=>i==="idle"?Ht.idleText??It.idle:i==="connecting"?Ht.connectingText??It.connecting:i==="connected"?Ht.connectedText??It.connected:i==="error"?Ht.errorText??It.error:i==="paused"?Ht.pausedText??It.paused:i==="resuming"?Ht.resumingText??It.resuming:It[i];function Cn(i,p,m,y){if(y==="idle"&&m.idleLink){i.textContent="";let x=document.createElement("a");x.href=m.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=p,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=p}let et=Of({config:o,showClose:ie()}),{wrapper:Le,panel:ye,pillRoot:tt}=et.shell,Te=et.panelElements,{container:ve,body:re,messagesWrapper:xe,starterSuggestions:An,transcriptSuggestions:ne,suggestions:M,textarea:I,sendButton:h,sendButtonWrapper:W,composerForm:L,statusText:R,welcomeHost:q,welcomeIconHolder:$,greetingHost:K,introTitle:ce,introSubtitle:je,closeButton:de,iconHolder:Pe,headerTitle:Ve,headerSubtitle:$e,header:Re,footer:Ce,actionsRow:nt,rightActions:xt}=Te,dn=Te.leftActions,ra=Te.setSendButtonMode,oe=Te.micButton,pn=Te.micButtonWrapper,it=Te.attachmentButton,un=Te.attachmentButtonWrapper,St=Te.attachmentInput,Sn=Te.attachmentPreviewsContainer;ve.classList.add("persona-relative"),re.classList.add("persona-relative");let Dg=12,Gr=()=>we.label??"",Fg=()=>we.iconName??"arrow-down",Og=()=>we.enabled!==!1,nn=()=>he.mode??"anchor-top",no=()=>nn()==="follow"||nn()==="anchor-top"&&rs,Yr=()=>he.anchorTopOffset??16,Ng=()=>he.restorePosition??"bottom",qc=()=>he.pauseOnInteraction===!0,Kc=()=>he.showActivityWhilePinned!==!1,Gc=()=>he.announce===!0,Ni=()=>he.scrollbar??"on-scroll",Et=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");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let Xr=b("span","persona-flex persona-items-center"),_i=b("span",""),Mo=b("span","");Mo.setAttribute("data-persona-scroll-to-bottom-count",""),Mo.style.display="none",Et.append(Xr,_i,Mo),ve.appendChild(Et);let fn=b("div","persona-stream-anchor-spacer");fn.setAttribute("aria-hidden","true"),fn.setAttribute("data-persona-anchor-spacer",""),fn.style.flexShrink="0",fn.style.pointerEvents="none",fn.style.height="0px",fn.style.display="none",re.appendChild(fn);let Eo=b("div","persona-sr-only");Eo.setAttribute("aria-live","polite"),Eo.setAttribute("aria-atomic","true"),Eo.setAttribute("role","status"),Eo.setAttribute("data-persona-live-region",""),Object.assign(Eo.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"}),ve.appendChild(Eo);let Qr=null,sa=null,Yc=i=>{!Gc()||!i||(sa=i,Qr===null&&(Qr=setTimeout(()=>{Qr=null,sa&&Gc()&&(Eo.textContent=sa),sa=null},400)))},ko=()=>{let p=Ce.style.display==="none"?0:Ce.offsetHeight;Et.style.bottom=`${p+Dg}px`};ko();let Xc=()=>{let i=!!Gr();Et.setAttribute("aria-label",Gr()||"Jump to latest"),Et.title=Gr(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Xr.innerHTML="";let p=ae(Fg(),"14px","currentColor",2);p?(Xr.appendChild(p),Xr.style.display=""):Xr.style.display="none",_i.textContent=Gr(),_i.style.display=i?"":"none"};Xc();let yt=null,Yt=null,Qc=null,Jc=s.find(i=>i.renderHeader);if(Jc?.renderHeader){let i=Jc.renderHeader({config:o,defaultRenderer:()=>{let p=Jo({config:o,showClose:ie()});return Ks(ve,p,o),p.header},onClose:()=>lt(!1,"user")});if(i){let p=ve.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(i),Re=i,et.header.element=i)}}let $i=()=>{if(!Oe)return;if(Se=!0,!Ae&&Oe&&(Ae=Qf({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Jr(),config:o,plugins:s,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",Ce.parentNode?.insertBefore(Ae.element,Ce),Ae.update()),Je){Je.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let p=o.features?.eventStream?.classNames?.toggleButtonActive;p&&p.split(/\s+/).forEach(m=>m&&Je.classList.add(m))}let i=()=>{if(!Se)return;let p=Date.now();p-Gt>=200&&(Ae?.update(),Gt=p),ze=requestAnimationFrame(i)};Gt=0,ze=requestAnimationFrame(i),$t(),c.emit("eventStream:opened",{timestamp:Date.now()})},Jr=()=>{if(Se){if(Se=!1,Ae&&Ae.element.remove(),re.style.display="",Je){Je.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(p=>p&&Je.classList.remove(p))}ze!==null&&(cancelAnimationFrame(ze),ze=null),$t(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Je=null;if(me){let i=o.features?.eventStream?.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"+(i?.toggleButton?" "+i.toggleButton:"");Je=b("button",p),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&Je.appendChild(m);let y=Te.clearChatButtonWrapper,x=Te.closeButtonWrapper,E=y||x;E&&E.parentNode===Re?Re.insertBefore(Je,E):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}let Zc=i=>{let p=o.attachments;if(!p?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(m,x):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=b("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(p.allowedTypes??Qn).join(","),x.multiple=(p.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",p.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ui=s.find(i=>i.renderComposer),zi=!1,ed=i=>{if(!Ui?.renderComposer)return null;let p=o.composer,m=a?_.isStreaming():!1;return Ui.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Dm(),storage:l(Ui.id),onSubmit:y=>{if(!_||_.isStreaming())return;let x=y.trim(),E=yt?.hasAttachments()??!1;if(!x&&!E)return;tp();let U;E&&(U=[],U.push(...yt.getContentParts()),x&&U.push(Lr(x))),_.sendMessage(x,{contentParts:U}),E&&yt.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{St?.click()},models:p?.models,selectedModelId:p?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Qc?.()}:void 0})},td=ed(()=>Gs({config:o}).footer);td&&(et.replaceComposer(td),Ce=et.composer.footer,zi=!0);let nd=i=>{let p=(...fe)=>{for(let le of fe){let be=i.querySelector(le);if(be)return be}return null},m=i.querySelector("[data-persona-composer-form]"),y=i.querySelector("[data-persona-composer-input]"),x=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),U=i.querySelector("[data-persona-composer-status]");m&&(L=m),y&&(I=y),x&&(h=x),E&&(oe=E,pn=E.parentElement),U&&(R=U);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(M=O);let V=p("[data-persona-composer-attachment-button]",".persona-attachment-button");V&&(it=V,un=V.parentElement),St=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Sn=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let J=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");J&&(nt=J),dn=p(".persona-widget-composer__left-actions")};Zc(Ce),nd(Ce);let Zr=xo(o,Q());Zr&&(xe.style.maxWidth=Zr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=Zr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",An.style.maxWidth=Zr,ne.style.maxWidth=Zr,ne.style.marginLeft="auto",ne.style.marginRight="auto",ne.style.width="100%");let od=()=>{let i=xo(o,Q());if(!(!i||Q()))for(let p of[L,M,Sn,R])p&&(p.style.maxWidth=i,p.style.marginLeft="auto",p.style.marginRight="auto")};od();let rd=()=>{!o.attachments?.enabled||!St||!Sn||(yt?yt.remountPreviews(Sn):(yt=Rs.fromConfig(o.attachments),yt.setPreviewsContainer(Sn)),St.addEventListener("change",i=>{let p=i.target;yt?.handleFileSelect(p.files),p.value=""}),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(Ag(o.attachments.dropOverlay)))};rd();let _g=()=>Yt?.prefetch(),sd=()=>{if(!(!o.contextMentions?.enabled||!I)&&(Yt=Pu({config:o,textarea:I,anchor:L??I,getMessages:()=>_.getMessages(),liveRegionHost:ve}),Yt)){let i=I;i.parentElement?.insertBefore(Yt.contextRow,i);let p=Yt.affordanceButtons;for(let m=p.length-1;m>=0;m--){let y=p[m];dn?dn.insertBefore(y,dn.firstChild):L?.appendChild(y)}}};sd(),(()=>{let i=o.layout?.slots??{},p=y=>{switch(y){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return M;case"composer":return L;case"footer-bottom":return R;default:return null}},m=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")Re.insertBefore(x,Re.firstChild);else if(y==="header-right")Re.appendChild(x);else{let E=Re.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(x,E.nextSibling):Re.appendChild(x)}break;case"body-top":{let E=re.querySelector("[data-persona-intro-card]");E?E.replaceWith(x):re.insertBefore(x,re.firstChild);break}case"body-bottom":re.appendChild(x);break;case"footer-top":M.replaceWith(x);break;case"footer-bottom":R.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let E=x({config:o,defaultContent:()=>p(y)});E&&m(y,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,E)}})();let ad=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let y=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-bubble-type");if(E==="reasoning")$r.has(x)?$r.delete(x):$r.add(x),_f(x,y);else if(E==="tool")Ur.has(x)?Ur.delete(x):Ur.add(x),$f(x,y,o);else if(E==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=er.get(x)??O;er.set(x,!V),Vf(x,y,o)}Bo.delete(x)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("keydown",i=>{let p=i.target;(i.key==="Enter"||i.key===" ")&&p.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("copy",i=>{let{clipboardData:p}=i;if(!p)return;let m=xe.getRootNode(),y=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),E=rf(x);!E||E===x||(p.setData("text/plain",E),i.preventDefault())});let ji=new Map,id=null,ld="idle",$g={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ug=(i,p)=>{let{icon:m,label:y}=$g[p];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",p==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",p!=="idle"),i.classList.toggle("persona-message-action-loading",p==="loading");let x=ae(m,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},cd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{let y=p.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Ug(p,y&&y===id?ld:"idle")})};xe.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest("[data-actions-for]");if(!y)return;let x=y.getAttribute("data-actions-for");if(!x)return;let E=m.getAttribute("data-action");if(E==="copy"){let O=_.getMessages().find(V=>V.id===x);if(O&>.onCopy){let V=O.content||"";navigator.clipboard.writeText(V).then(()=>{m.classList.add("persona-message-action-success");let J=ae("check",14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let fe=ae("copy",14,"currentColor",2);fe&&(m.innerHTML="",m.appendChild(fe))},2e3)}).catch(J=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",J)}),gt.onCopy(O)}}else if(E==="read-aloud")_.toggleReadAloud(x);else if(E==="upvote"||E==="downvote"){let O=(ji.get(x)??null)===E,V=E==="upvote"?"thumbs-up":"thumbs-down";if(O){ji.delete(x),m.classList.remove("persona-message-action-active");let J=ae(V,14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J))}else{let J=E==="upvote"?"downvote":"upvote",fe=y.querySelector(`[data-action="${J}"]`);if(fe){fe.classList.remove("persona-message-action-active");let ct=ae(J==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(fe.innerHTML="",fe.appendChild(ct))}ji.set(x,E),m.classList.add("persona-message-action-active");let le=ae(V,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(le)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ge=_.getMessages().find(mt=>mt.id===x);Ge&>.onFeedback&>.onFeedback({type:E,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest(".persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-approval-action");if(!E)return;let U=E==="approve"?"approved":"denied",V=_.getMessages().find(fe=>fe.id===x);if(!V?.approval)return;let J=y.querySelector("[data-approval-buttons]");J&&J.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,U):_.resolveApproval(V.approval,U)});let Ye=null,es=null,Lo=()=>{},ts="none",aa=null,Tn={artifacts:[],selectedId:null},On=!1,Mn=!1,ns=!1,sr=!1,dd=()=>sr||Tn.artifacts.some(i=>ho(o.features?.artifacts,i)==="panel"),ia=()=>Tn.artifacts.length>0&&!On&&dd(),st={current:null},Vi=(i,p)=>{let m=_.getArtifactById(p),y=m?.markdown,x=m?.title||"artifact",E=m?.file,U=m?.artifactType??"markdown";if(!y){let J=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(J){let le=_.getMessages().find(be=>be.id===J);if(le?.rawContent)try{let be=JSON.parse(le.rawContent);y=be?.props?.markdown,x=be?.props?.title||x,be?.props?.file&&typeof be.props.file=="object"&&(E=be.props.file),!m&&typeof be?.props?.artifactType=="string"&&(U=be.props.artifactType)}catch{}}}return{markdown:y,title:x,file:E,artifactType:U}};xe.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:E,title:U,file:O}=Vi(m,y);if(!E)return;let{filename:V,mime:J,content:fe}=_u({title:U,markdown:E,file:O}),le=new Blob([fe],{type:J}),be=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=be,Ge.download=V,Ge.click(),URL.revokeObjectURL(be)}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-artifact-custom-action");if(!y)return;let x=m.closest("[data-artifact-inline]"),E=x?null:m.closest("[data-open-artifact]"),U=x?x.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,V=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(mt=>mt.id===y);if(!V)return;let{markdown:J,title:fe,file:le,artifactType:be}=Vi(m,U??""),Ge={artifactId:U,title:fe,artifactType:be,markdown:J,file:le};try{Promise.resolve(V.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-copy-artifact");if(!y)return;let x=_.getArtifactById(y),E="";if(x)E=Ns(x);else{let{markdown:U,file:O,artifactType:V}=Vi(m,y);V==="markdown"&&(E=Ns({id:y,artifactType:"markdown",status:"complete",markdown:U??"",...O?{file:O}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let U=ae("check",16,"currentColor",2);U&&(m.replaceChildren(U),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&m.replaceChildren(O)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(On=!1,sr=!0,Mn=!0,ns=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("click",i=>{let p=i.target;if(p.closest("[data-download-artifact]")||p.closest("[data-artifact-custom-action]"))return;let m=p.closest("[data-open-artifact]");if(!m)return;let y=m.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),On=!1,sr=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let p=i.target;!p.hasAttribute("data-open-artifact")&&!p.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),p.click())});let ar=Te.composerOverlay,ir=(i,p,m)=>{let y=p.trim();if(!y||!st.current)return;let x=i.getAttribute("data-tool-call-id")??"",E=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:y,answers:m.structured,values:m.values??(m.source==="multi"?y.split(", "):[y]),isFreeText:E,source:m.source},bubbles:!0,composed:!0})),Er(ar,x);let U=st.current.getMessages().find(O=>O.toolCall?.id===x);U?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(U,m.structured??y):st.current.sendMessage(y)},Po=i=>{let p=st.current;if(!p)return;let m=i.getAttribute("data-tool-call-id")??"",y=p.getMessages().find(x=>x.toolCall?.id===m);y&&p.persistAskUserQuestionProgress(y,{answers:Na(i,y),currentIndex:bn(i)})},pd=i=>Object.entries(i).map(([p,m])=>`${p}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),qi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let p=bn(i),m=Mr(i);if(p>=m-1)return;let y=st.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&($a(i,y,o,p+1),Po(i))};ar.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;let x=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let E=y.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E);let U=st.current?.getMessages().find(O=>O.toolCall?.id===E);U?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(U),st.current?.resolveAskUserQuestion(U,"(dismissed)"));return}if(x==="pick"){let E=m.getAttribute("data-option-label");if(!E)return;let U=y.getAttribute("data-multi-select")==="true",O=yo(y);if(O&&U){let V=Ko(y)[bn(y)],J=new Set(Array.isArray(V)?V:[]);J.has(E)?J.delete(E):J.add(E),bo(y,Array.from(J)),Po(y);return}if(O){bo(y,E),Po(y),qi(y);return}if(U){let V=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",V?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!V);let J=y.querySelector('[data-ask-user-action="submit-multi"]');J&&(J.disabled=Nl(y).length===0);return}ir(y,E,{source:"pick",values:[E]});return}if(x==="submit-multi"){let E=Nl(y);if(E.length===0)return;ir(y,E.join(", "),{source:"multi",values:E});return}if(x==="open-free-text"){let E=y.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let U=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!U.trim())return;if(yo(y)){bo(y,U.trim()),Po(y),qi(y);return}ir(y,U,{source:"free-text"});return}if(x==="next"||x==="back"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let le=Ko(y)[bn(y)];(typeof le!="string"||le!==V)&&bo(y,V)}let J=x==="next"?1:-1,fe=bn(y)+J;$a(y,U,o,fe),Po(y);return}if(x==="submit-all"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&bo(y,V);let J=Na(y,U);st.current.persistAskUserQuestionProgress(U,{answers:J,currentIndex:bn(y)});let fe=pd(J);ir(y,fe||"(submitted)",{source:"submit-all",structured:J});return}if(x==="skip"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(be=>be.toolCall?.id===E);if(!U)return;let O=yo(y),V=bn(y),J=Mr(y),fe=V>=J-1;if(!O){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E),U.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(U),st.current.resolveAskUserQuestion(U,"(dismissed)"));return}bo(y,"");let le=y.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),fe){let be=Na(y,U),Ge=pd(be);ir(y,Ge||"(skipped)",{source:"submit-all",structured:be});return}$a(y,U,o,V+1),Po(y);return}}),ar.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let x=m.value;if(x.trim()){if(yo(y)){bo(y,x.trim()),Po(y),qi(y);return}ir(y,x,{source:"free-text"})}});let ud=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let p=i.target;if(p?.tagName==="INPUT"||p?.tagName==="TEXTAREA"||p?.isContentEditable)return;let m=ar.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),E=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",ud);let oo=null,bt=null,os=null,la=null,Ki=()=>{},fd=!1,ca="",da="";function Gi(){la?.(),la=null}let gd=()=>{if(!oo||!bt)return;let i=e.classList.contains("persona-artifact-welded-split"),p=e.ownerDocument.defaultView??window,m=p.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let y=oo.firstElementChild;if(!y||y===bt)return;let x=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${x}px`,bt.style.zIndex="5";let E=Ic(oo,p),U=y.offsetWidth+E/2-x/2;bt.style.left=`${Math.max(0,U)}px`},pa=()=>{},zg=()=>{let i=e.ownerDocument.defaultView??window,p=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!p||i.innerWidth>m?!1:F||Rt(o)},ua=()=>!Jt(o)||!ia()||e.classList.contains("persona-artifact-narrow-host")||zg()||(e.ownerDocument.defaultView??window).innerWidth<cw?"none":kc(o)?"detached":"welded",Nn=()=>{if(!Ye||!Jt(o))return;ea(e,o),ta(e,o),pa();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,p=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=i);let m=ia();Ye.setVisible(m),Ye.update(Tn),On?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1):Tn.artifacts.length>0&&dd()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(y),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!ns&&(Mn=!1),Mn!==fd){let E=Ye.element;Mn?(ca=E.style.width,da=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(ca&&(E.style.width=ca),da&&(E.style.maxWidth=da),ca="",da=""),fd=Mn}e.classList.toggle("persona-artifact-expanded",Mn),Ye.setExpanded(Mn);let x=ua();x!==ts&&(ts=x,Lo()),Ki()};if(Jt(o)){ye.style.position="relative";let i=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");i.appendChild(ve),Ye=Zf(o,{onSelect:m=>st.current?.selectArtifact(m),onDismiss:()=>{On=!0,Nn()},onToggleExpand:()=>{let m=!Mn,y=Tn.selectedId??Tn.artifacts[Tn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:y,expanded:m})!==!0&&(Mn=m,m||(ns=!1),Nn())}}),Ye.element.classList.add("persona-hidden"),oo=p,p.appendChild(i),p.appendChild(Ye.element),Ye.backdrop&&ye.appendChild(Ye.backdrop),ye.appendChild(p),Ki=()=>{if(!oo||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let y=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");y.setAttribute("role","separator"),y.setAttribute("aria-orientation","vertical"),y.setAttribute("aria-label","Resize artifacts panel"),y.tabIndex=0;let x=e.ownerDocument,E=x.defaultView??window,U=O=>{if(!Ye||O.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;O.preventDefault(),Gi();let V=O.clientX,J=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,le=Ge=>{let mt=oo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),sn=Ic(oo,E),At=ct?0:y.getBoundingClientRect().width||6,Lt=J-(Ge.clientX-V),D=lg(Lt,mt,sn,At,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${D}px`,Ye.element.style.maxWidth="none",gd()},be=()=>{x.removeEventListener("pointermove",le),x.removeEventListener("pointerup",be),x.removeEventListener("pointercancel",be),la=null;try{y.releasePointerCapture(O.pointerId)}catch{}};la=be,x.addEventListener("pointermove",le),x.addEventListener("pointerup",be),x.addEventListener("pointercancel",be);try{y.setPointerCapture(O.pointerId)}catch{}};y.addEventListener("pointerdown",U),bt=y,oo.insertBefore(y,Ye.element),os=()=>{y.removeEventListener("pointerdown",U)}}if(bt){let y=ia();bt.classList.toggle("persona-hidden",!y),gd()}},pa=()=>{if(!F||!Ye||(o.launcher?.sidebarMode??!1)||Rt(o)&&vn(o).reveal==="emerge")return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E||!ng(o,F))return;let U=o.launcher?.width??o.launcherWidth??Jn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ia()?(ye.style.width=O,ye.style.maxWidth=O):(ye.style.width=U,ye.style.maxWidth=U)},typeof ResizeObserver<"u"&&(es=new ResizeObserver(()=>{Nn()}),es.observe(ye))}else ye.appendChild(ve);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(Ce)),e.appendChild(Le),tt&&e.appendChild(tt);let Yi=()=>{if(Q()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},tn=Le.dataset.state==="expanded",Pa=Mt.expandedSize??"anchored";if(!(tn&&Pa!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let bs=o.theme?.components?.panel,Ia=Rr(o),vr=(qn,Vo)=>qn==null||qn===""?Vo:Qt(Ia,qn)??qn,Wa="1px solid var(--persona-border)",kl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",jo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=vr(bs?.border,Wa),ve.style.borderRadius=vr(bs?.borderRadius,jo),ve.style.boxShadow=vr(bs?.shadow,kl),ve.style.overflow="hidden";return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=i||p||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,U=Rr(o),O=(Mt,tn)=>Mt==null||Mt===""?tn:Qt(U,Mt)??Mt,V=e.ownerDocument.defaultView??window,J=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,le=V.innerWidth<=fe,be=J&&le&&F,Ge=i&&J&&le,mt=o.launcher?.position??"bottom-left",ct=mt==="bottom-left"||mt==="top-left",sn=o.launcher?.zIndex??Nt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",D="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=x&&!be&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let De=Ie?At:p||be?"none":At,Me=Ie?Lt:be?"none":p?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":y?"none":Lt;i&&!be&&!Ie&&(Me="none",De="none");let Ct=Ie?D:p||be?"0":D,dt=O(E?.border,De),Ft=O(E?.shadow,Me),pt=O(E?.borderRadius,Ct),en=ua(),Pt=en==="detached",We=en==="welded";e.classList.toggle("persona-artifact-detached-split",Pt),e.classList.toggle("persona-artifact-welded-split",We);let Fe="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)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&kc(o)&&y&&!i;e.classList.toggle("persona-artifact-chat-flush",wt);let at=Pt||wt?"none":Ft,ut=Pt?At:We?"none":dt,Xe=Pt?D:pt;wt&&(ut="none",Xe="0");let He=E?.borderRadius!=null&&E.borderRadius!=="",ht=wt&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",ye.style.cssText="",ve.style.cssText="",re.style.cssText="",Ce.style.cssText="",Se&&(re.style.display="none"),(m||y)&&(e.style.minWidth="0");let hn=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let tn=re.scrollHeight-re.clientHeight;tn<=0||(re.scrollTop=Math.min(jt,tn))})};if(be){Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Le.style.cssText=`
|
|
47
47
|
position: fixed !important;
|
|
48
48
|
inset: 0 !important;
|
|
49
49
|
width: 100% !important;
|
|
@@ -53,9 +53,9 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
53
53
|
padding: 0 !important;
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
|
-
z-index: ${
|
|
56
|
+
z-index: ${sn} !important;
|
|
57
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
58
|
-
`,
|
|
58
|
+
`,ye.style.cssText=`
|
|
59
59
|
position: relative !important;
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
68
|
padding: 0 !important;
|
|
69
69
|
box-shadow: none !important;
|
|
70
70
|
border-radius: 0 !important;
|
|
71
|
-
`,
|
|
71
|
+
`,ve.style.cssText=`
|
|
72
72
|
display: flex !important;
|
|
73
73
|
flex-direction: column !important;
|
|
74
74
|
flex: 1 1 0% !important;
|
|
@@ -79,33 +79,33 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
79
79
|
overflow: hidden !important;
|
|
80
80
|
border-radius: 0 !important;
|
|
81
81
|
border: none !important;
|
|
82
|
-
`,
|
|
82
|
+
`,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ce.style.flexShrink="0",G=!0,hn();return}let La=o?.launcher?.width??o?.launcherWidth??Jn;if(!p&&!i)y&&m?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=La,ye.style.maxWidth=La);else if(i)if(vn(o).reveal==="emerge"&&!x){let tn=vn(o).width;ye.style.width=tn,ye.style.maxWidth=tn}else ye.style.width="100%",ye.style.maxWidth="100%";if(pa(),ye.style.boxShadow=at,ye.style.borderRadius=ht,Pt?ye.style.border="none":We&&(ye.style.border=dt),ve.style.border=ut,ve.style.borderRadius=Xe,ve.style.boxShadow=Pt&&!wt?Fe:"",wt&&(ve.style.background="transparent",re.style.background="transparent",Ce.style.background="transparent",Ce.style.borderTop="none"),We){let Mt=o.features?.artifacts?.layout;aa=Mt?.unifiedSplitOuterRadius?.trim()||Mt?.paneBorderRadius?.trim()||pt}else aa=null;if(i&&!be&&!Ie&&!Pt&&!We&&E?.border===void 0&&(ve.style.border="none",vn(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),i&&!be&&We&&E?.border===void 0&&(vn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",y&&(Le.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",Pt||(ye.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ce.style.flexShrink="0"),y&&(Ie||Pt||wt)&&!i&&(wt||(Le.style.padding="var(--persona-panel-inset)"),Le.style.background="var(--persona-panel-canvas-bg)"),Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!i&&(ln[mt]??ln["bottom-right"]).split(" ").forEach(tn=>Le.classList.add(tn)),p){let Mt=o.launcher?.sidebarWidth??"420px";x?Le.style.cssText=`
|
|
83
83
|
position: fixed !important;
|
|
84
84
|
top: var(--persona-panel-inset) !important;
|
|
85
85
|
bottom: var(--persona-panel-inset) !important;
|
|
86
|
-
width: ${
|
|
86
|
+
width: ${Mt} !important;
|
|
87
87
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
88
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
89
89
|
margin: 0 !important;
|
|
90
90
|
padding: 0 !important;
|
|
91
91
|
display: flex !important;
|
|
92
92
|
flex-direction: column !important;
|
|
93
|
-
z-index: ${
|
|
94
|
-
${
|
|
95
|
-
`:
|
|
93
|
+
z-index: ${sn} !important;
|
|
94
|
+
${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
+
`:Le.style.cssText=`
|
|
96
96
|
position: fixed !important;
|
|
97
97
|
top: 0 !important;
|
|
98
98
|
bottom: 0 !important;
|
|
99
|
-
width: ${
|
|
99
|
+
width: ${Mt} !important;
|
|
100
100
|
height: 100vh !important;
|
|
101
101
|
max-height: 100vh !important;
|
|
102
102
|
margin: 0 !important;
|
|
103
103
|
padding: 0 !important;
|
|
104
104
|
display: flex !important;
|
|
105
105
|
flex-direction: column !important;
|
|
106
|
-
z-index: ${
|
|
107
|
-
${
|
|
108
|
-
`,
|
|
106
|
+
z-index: ${sn} !important;
|
|
107
|
+
${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
|
+
`,ye.style.cssText=`
|
|
109
109
|
position: relative !important;
|
|
110
110
|
display: flex !important;
|
|
111
111
|
flex-direction: column !important;
|
|
@@ -116,10 +116,10 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
116
116
|
min-height: 0 !important;
|
|
117
117
|
margin: 0 !important;
|
|
118
118
|
padding: 0 !important;
|
|
119
|
-
box-shadow: ${
|
|
119
|
+
box-shadow: ${at} !important;
|
|
120
120
|
border-radius: ${ht} !important;
|
|
121
|
-
${
|
|
122
|
-
`,
|
|
121
|
+
${Pt?"border: none !important;":We?`border: ${dt} !important;`:""}
|
|
122
|
+
`,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),ve.style.cssText=`
|
|
123
123
|
display: flex !important;
|
|
124
124
|
flex-direction: column !important;
|
|
125
125
|
flex: 1 1 0% !important;
|
|
@@ -128,16 +128,16 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
min-height: 0 !important;
|
|
129
129
|
max-height: 100% !important;
|
|
130
130
|
overflow: hidden !important;
|
|
131
|
-
border-radius: ${
|
|
132
|
-
border: ${
|
|
133
|
-
${
|
|
134
|
-
${
|
|
135
|
-
`,
|
|
131
|
+
border-radius: ${Xe} !important;
|
|
132
|
+
border: ${ut} !important;
|
|
133
|
+
${Pt&&!wt?`box-shadow: ${Fe} !important;`:""}
|
|
134
|
+
${wt?"background: transparent !important;":""}
|
|
135
|
+
`,Ce.style.cssText=`
|
|
136
136
|
flex-shrink: 0 !important;
|
|
137
137
|
border-top: none !important;
|
|
138
138
|
padding: 8px 16px 12px 16px !important;
|
|
139
|
-
${
|
|
140
|
-
`}if(!b&&!i){let St="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",oa=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;He.style.cssText+=St+Yt+oa}pn()};Os(),cs(e,o),Ts(e,o),Ms(e,o),Er=()=>{Os(),cs(e,o),Ts(e,o),Ms(e,o),Rs?e.style.setProperty("--persona-artifact-welded-outer-radius",Rs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let ze=[];ze.push(()=>{document.removeEventListener("keydown",fc)}),ze.push(()=>{Sr!==null&&clearTimeout(Sr)});let An=null,Sn=null;ze.push(()=>{An?.(),An=null,Sn?.(),Sn=null}),Mr&&ze.push(()=>{Mr?.disconnect(),Mr=null}),ze.push(()=>{Pr?.(),Pr=null,yi(),yt&&(yt.remove(),yt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&ze.push(()=>{Te!==null&&(cancelAnimationFrame(Te),Te=null),Qe?.destroy(),Qe=null,Me?.destroy(),Me=null,ve=null});let bo=null,hc=()=>{bo&&(bo(),bo=null),o.colorScheme==="auto"&&(bo=Ia(()=>{cs(e,o)}))};hc(),ze.push(()=>{bo&&(bo(),bo=null)}),ze.push(l);let _s=o.features?.streamAnimation;if(_s?.type&&_s.type!=="none"){let i=mr(_s.type,_s.plugins);i&&(qa(i,e),ze.push(()=>eu(e)))}let $s=vu(it),vo=null,O,bi=i=>{if(!O)return;let g=i??O.getMessages(),m=o.features?.suggestReplies?.enabled!==!1?zd(g):null;m?$s.render(m,O,ue,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(b=>b.role==="user")?$s.render([],O,ue,g):$s.render(o.suggestionChips,O,ue,g,o.suggestionChipsConfig)},yn=!1,wo=Up(),Uo=new Map,xo=new Map,Gn=new Map,vi=0,hf=Fn()!==null,en=_a(),an=0,Qn=null,ln=!1,zs=!1,Xn=0,bn=null,Co=null,wi=!1,js=!1,Ir=null,Rr=!0,Us=!1,Vs=null,qs=!1,Ao=()=>{qs=!0},xi=null,yf=4,Ks=24,bf=80,Ci=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},yc=o.voiceRecognition?.autoResume??!1,In=i=>{p.emit("voice:state",{active:Ge.active,source:i,timestamp:Date.now()})},vn=()=>{R(i=>({...i,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},vf=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Vl(u.voiceState),g=!!i.active,m=Number(i.timestamp??0);Ge.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-m<rb&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("restore"),O.isVoiceActive()&&Qo()}):Ys("restore"))},1e3)},wf=()=>O?Ku(O.getMessages()).filter(i=>!i.__skipPersist):[],Gs=null,bc=(i,g)=>{typeof console<"u"&&console.error(i,g)},Ai=(i,g)=>{let m=()=>{try{let Q=i();return!Q||typeof Q.then!="function"?null:Promise.resolve(Q).catch(N=>{bc(g,N)})}catch(Q){return bc(g,Q),null}},b=Gs,A=b?b.then(()=>m()??void 0):m();if(!A)return;let k=A.finally(()=>{Gs===k&&(Gs=null)});Gs=k};function Si(i){if(!c?.save)return;let m={messages:i?Ku(i):O?wf():[],metadata:u,artifacts:mn.artifacts,selectedArtifactId:mn.selectedId};Ai(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Vo=null,vc=()=>He.querySelector("#persona-scroll-container")||se,Wr=()=>{Vo!==null&&(cancelAnimationFrame(Vo),Vo=null),ln=!1},wc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!1,Wr()},xf=()=>yn&&Mi()&&(sn()!=="anchor-top"||ec()),Ti=()=>{let i=go()||"Jump to latest",g=xf();Tt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Xn>0?(mo.textContent=String(Xn),mo.style.display="",Tt.setAttribute("aria-label",`${i} (${Xn} new)`)):(mo.textContent="",mo.style.display="none",Tt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},xc=()=>{Xn!==0&&(Xn=0,Ti())},Mi=()=>Un()?!en.isFollowing():!uo(se,Ks),tn=()=>{if(!Ps()||Ve){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==fe&&fe.appendChild(Tt),_o();let g=En(se)>0&&Mi();g?Ti():xc(),Tt.style.display=g?"":"none"},Hr=()=>{en.pause()&&(wc(),tn())},Jn=()=>{en.resume(),xc(),tn()},Yn=(i=!1)=>{Un()&&en.isFollowing()&&(!i&&!yn||(Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),zs=!0,Qn=requestAnimationFrame(()=>{Qn=null,zs=!1,en.isFollowing()&&Cf(vc(),i?220:140)})))},Cc=(i,g,m,b=()=>!0)=>{let A=i.scrollTop,k=g(),Q=k-A;if(Wr(),Math.abs(Q)<1){ln=!0,i.scrollTop=k,an=i.scrollTop,ln=!1;return}let N=performance.now();ln=!0;let K=ge=>1-Math.pow(1-ge,3),ae=ge=>{if(!b()){Wr();return}let re=g();re!==k&&(k=re,Q=k-A);let we=ge-N,Ue=Math.min(we/m,1),pt=K(Ue),nt=A+Q*pt;i.scrollTop=nt,an=i.scrollTop,Ue<1?Vo=requestAnimationFrame(ae):(i.scrollTop=k,an=i.scrollTop,Vo=null,ln=!1)};Vo=requestAnimationFrame(ae)},Cf=(i,g=500)=>{let m=En(i)-i.scrollTop;if(Math.abs(m)<1){an=i.scrollTop;return}if(Math.abs(m)>=bf){Wr(),ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1;return}Cc(i,()=>En(i),g,()=>en.isFollowing())},Ac=()=>{let i=vc();ln=!0,i.scrollTop=En(i),an=i.scrollTop,ln=!1,tn()},Sc=i=>{let g=0,m=i;for(;m&&m!==se;)g+=m.offsetTop,m=m.offsetParent;return g},Af=()=>{let i=se.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??se.ownerDocument.getSelection()},Qs=()=>Qp(Af(),se),Tc=()=>{if(cf()!=="last-user-turn")return!1;let i=O?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(k=>k.role==="user");if(!g)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=se.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let A=Math.min(Math.max(0,Sc(b)-Yl()),En(se));return ln=!0,se.scrollTop=A,an=se.scrollTop,ln=!1,sn()==="follow"&&!uo(se,Ks)&&en.pause(),tn(),!0},Mc=i=>{Vn.style.height=`${Math.max(0,Math.round(i))}px`,bn&&(bn.spacerHeight=Math.max(0,i))},Br=()=>{Co!==null&&(cancelAnimationFrame(Co),Co=null),Wr(),bn=null,Vn.style.height="0px"},Ec=i=>{Co!==null&&cancelAnimationFrame(Co),Co=requestAnimationFrame(()=>{Co=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=se.querySelector(`[data-message-id="${g}"]`);if(!m)return;let b=Sc(m),A=bn?.spacerHeight??0,k=se.scrollHeight-A,{targetScrollTop:Q,spacerHeight:N}=Xp({anchorOffsetTop:b,topOffset:Yl(),viewportHeight:se.clientHeight,contentHeight:k});bn={initialSpacerHeight:N,contentHeightAtAnchor:k,spacerHeight:N},Mc(N),Cc(se,()=>Q,220)})},Sf=()=>{if(Un()){if(!en.isFollowing()||uo(se,1))return;Yn(!yn);return}if(bn&&bn.initialSpacerHeight>0){let i=se.scrollHeight-bn.spacerHeight,g=Jp({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:i});g!==bn.spacerHeight&&Mc(g)}tn()},Tf=i=>{let g=sn();g==="follow"?(Jn(),Yn(!0)):g==="anchor-top"&&(Rr=!1,Us=!0,qs=!1,Vs=i,Ec(i))},Mf=()=>{if(sn()==="anchor-top"){if(Us){Rr=!1;return}Rr=!0,Br(),Jn(),Yn(!0)}},Ef=i=>{if(sn()!=="anchor-top"||!Us||qs||Qs())return;let g=Ir===null;for(let m of i){if(!g){m.id===Ir&&(g=!0);continue}if(Gp(m)){if(m.id===Vs)return;Vs=m.id,Ec(m.id);return}}},kf=i=>{let g=new Map;i.forEach(m=>{let b=Ci.get(m.id);g.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(p.emit("assistant:message",m),!js&&(sn()!=="anchor-top"||ec())&&Mi()&&(Xn+=1,Ti(),tn(),nc(Xn===1?"1 new message below.":`${Xn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),Ci.clear(),g.forEach((m,b)=>{Ci.set(b,m)})},Xs=(i,g)=>{let m=g==="user"?"user":"assistant",b=o.layout?.messages?.[m],A=b?.width??"content",k=b?.maxWidth??(A==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${g}`,`persona-message-width-${A}`),i.classList.toggle("persona-justify-end",g==="user"),i.setAttribute("data-message-role",g),i.setAttribute("data-message-width",A),i.style.setProperty("--persona-message-row-max-width",k)},So=(i,g)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Xs(m,g),m},Lf=(i,g,m)=>{let b=document.createElement("div"),k=(()=>{let W=s.find(Ee=>Ee.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Q=(W,Ee)=>Ee==null?!1:typeof Ee=="string"?(W.textContent=Ee,!0):(W.appendChild(Ee),!0),N=new Set,K=new Map,ae=new Set,ge=s.some(W=>W.renderAskUserQuestion),re=[],we=[],Ue=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(g.forEach(W=>{N.add(W.id),K.set(W.id,W.role);let Ee=ge&&Lo(W),Ne=pt&&W.variant==="approval"&&!!W.approval,Se=!Ee&&W.role==="assistant"&&!W.variant&&Ue&&Ul(W);!Ne&&Gn.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id)),!Se&&xo.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),xo.delete(W.id));let wt=Lo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=jp(W,vi)+wt,Bt=Ee||Ne||Se?null:Vp(wo,W.id,ut);if(Bt){b.appendChild(Bt.cloneNode(!0)),Lo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let ft=null,Jt=s.find(Oe=>!!(W.variant==="reasoning"&&Oe.renderReasoning||W.variant==="tool"&&Oe.renderToolCall||!W.variant&&Oe.renderMessage)),kt=o.layout?.messages;if(Lo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(W.id),i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(Yi(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(W)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=s.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Oe&<.current){let _t=Uo.get(W.id),$t=_t!==ut,vt=null;if($t){let{payload:Ze,complete:We}=nr(W),ht=W.id,zt=()=>lt.current?.getMessages().find(pn=>pn.id===ht);vt=Oe.renderAskUserQuestion({message:W,payload:Ze,complete:We,resolve:pn=>{let Vr=zt();Vr&<.current?.resolveAskUserQuestion(Vr,pn)},dismiss:()=>{let pn=zt();pn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(pn),lt.current?.resolveAskUserQuestion(pn,"(dismissed)"))},config:o})}let ct=_t!=null;if($t&&vt===null&&!ct){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}let gt=So(W.id,W.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),re.push({messageId:W.id,fingerprint:ut,bubble:vt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ae.add(W.toolCall.id),ga(W,o,Ie.composerOverlay));return}}else if(Ne){let Oe=s.find(ct=>typeof ct.renderApproval=="function")??a,$t=Gn.get(W.id)!==ut,vt=null;if($t&&Oe?.renderApproval){let ct=W.id,gt=(Ze,We)=>{let ht=lt.current?.getMessages().find(zt=>zt.id===ct);ht?.approval&&(ht.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(ht.id,Ze):lt.current?.resolveApproval(ht.approval,Ze,We))};vt=Oe.renderApproval({message:W,defaultRenderer:()=>ri(W,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if($t&&vt===null)i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id),ft=ri(W,o);else{let ct=So(W.id,W.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),b.appendChild(ct),nt.push({messageId:W.id,fingerprint:ut,bubble:vt});return}}else if(Jt)if(W.variant==="reasoning"&&W.reasoning&&Jt.renderReasoning){if(!ce)return;ft=Jt.renderReasoning({message:W,defaultRenderer:()=>El(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Jt.renderToolCall){if(!ee)return;ft=Jt.renderToolCall({message:W,defaultRenderer:()=>Ll(W,o),config:o})}else Jt.renderMessage&&(ft=Jt.renderMessage({message:W,defaultRenderer:()=>{let Oe=Ml(W,m,kt,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o});return W.role!=="user"&&Nl(Oe,W,o,O),Oe},config:o}));if(!ft&&Se){let Oe=Uu(W);if(Oe){let _t=xo.get(W.id),$t=_t!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&zn.getOptions(Oe.component)?.bubbleChrome!==!1,ct=null;if($t){let gt=zu(Oe,{config:o,message:W,transform:m});if(gt&&Oe.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),We=Ze?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(We):We,zt=We?i.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Ze&&zt&&zt!==Ze&&Np(zt)&&(Ze===gt?gt=zt:Ze.replaceWith(zt))}if(gt)if(vt){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-mb-3 persona-text-sm persona-leading-relaxed",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${W.id}`,Ze.setAttribute("data-message-id",W.id),Ze.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let We=document.createElement("div");We.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",We.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ze.appendChild(We)}Ze.appendChild(gt),ct=Ze}}if(ct||_t!=null){let gt=So(W.id,W.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),we.push({messageId:W.id,fingerprint:ut,bubble:ct});return}}}if(!ft)if(W.variant==="reasoning"&&W.reasoning){if(!ce)return;ft=El(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!ee)return;ft=Ll(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;ft=ri(W,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&W.role==="user"?ft=Oe.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Oe?.renderAssistantMessage&&W.role==="assistant"?ft=Oe.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ft=Ml(W,m,Oe,o.messageActions,Xe,{loadingIndicatorRenderer:k,widgetConfig:o}),W.role!=="user"&&ft&&Nl(ft,W,o,O)}let ke=So(W.id,W.role);ke.appendChild(ft),qp(wo,W.id,ut,ke),b.appendChild(ke)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ee=>{let Ne=Ee.getAttribute("data-persona-ask-sheet-for");Ne&&!ae.has(Ne)&&rr(Ie.composerOverlay,Ne)}),o.features?.toolCallDisplay?.grouped){let W=[],Ee=[],Ne=o.features.toolCallDisplay.groupedMode==="summary";g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&ee){Ee.push(Se);return}Se.variant==="reasoning"&&!ce||((Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),Ee=[])}),(Ee.length>1||Ne&&Ee.length>0)&&W.push(Ee),W.forEach(Se=>{let wt=Se.map(Oe=>Array.from(b.children).find(_t=>_t instanceof HTMLElement&&_t.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(wt.length<(Ne?1:2))return;let ut=So(`tool-group-${Se[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Jt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,kt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:Jt,config:o});Q(ft,kt)||(ft.textContent=Jt);let ke=document.createElement("div");ke.className="persona-tool-group-stack persona-flex persona-flex-col",ke.id=`tool-group-stack-${Se[0].id}`,ke.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(ft),Ne||Bt.appendChild(ke),ut.appendChild(Bt),wt[0].before(ut),wt.forEach((Oe,_t)=>{if(Ne){Oe.remove();return}Oe.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),_t<wt.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),ke.appendChild($t)})})}Kp(wo,N);let nn=g.some(W=>W.role==="assistant"&&W.streaming),At=g[g.length-1],Et=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(yn&&g.some(W=>W.role==="user")&&!nn&&!Et){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:xs},Ee=s.find(Se=>Se.renderLoadingIndicator),Ne=null;if(Ee?.renderLoadingIndicator&&(Ne=Ee.renderLoadingIndicator(W)),Ne===null&&o.loadingIndicator?.render&&(Ne=o.loadingIndicator.render(W)),Ne===null&&(Ne=xs()),Ne){let Se=document.createElement("div"),wt=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Se.className=wt?Tl("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),wt&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(Ne);let Bt=So("typing-indicator","assistant");Bt.appendChild(Se),b.appendChild(Bt)}}if(!yn&&g.length>0){let W=g[g.length-1],Ee={config:o,lastMessage:W,messageCount:g.length},Ne=s.find(wt=>wt.renderIdleIndicator),Se=null;if(Ne?.renderIdleIndicator&&(Se=Ne.renderIdleIndicator(Ee)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Ee)),Se){let wt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;wt.className=ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),wt.setAttribute("data-idle-indicator","true"),wt.appendChild(Se);let Bt=So("idle-indicator","assistant");Bt.appendChild(wt),b.appendChild(Bt)}}if(Cd(b),Oa(i,b),zi(i),re.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of re){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Uo.set(W,Ee)))}if(Uo.size>0)for(let W of Uo.keys())N.has(W)||Uo.delete(W);if(we.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of we){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),xo.set(W,Ee)))}if(xo.size>0)for(let W of xo.keys())N.has(W)||xo.delete(W);if(nt.length>0)for(let{messageId:W,fingerprint:Ee,bubble:Ne}of nt){let Se=i.querySelector(`#wrapper-${W}`);Se&&(Xs(Se,K.get(W)??"assistant"),Ne!==null&&(Se.replaceChildren(Ne),Se.setAttribute("data-bubble-fp",Ee),Gn.set(W,Ee)))}if(Gn.size>0)for(let W of Gn.keys())N.has(W)||Gn.delete(W)},Dr=(i,g,m)=>{Lf(i,g,m),dc()},Fr=null,Pf=()=>{if(Fr)return;let i=m=>{let b=m.composedPath();b.includes(He)||et&&b.includes(et)||dt(!1,"user")};Fr=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},kc=()=>{if(!Fr)return;(e.ownerDocument??document).removeEventListener("pointerdown",Fr,!0),Fr=null};ze.push(()=>kc());let Nr=null,If=()=>{if(Nr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};Nr=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Lc=()=>{if(!Nr)return;(e.ownerDocument??document).removeEventListener("keydown",Nr,!0),Nr=null};ze.push(()=>Lc());let Or=!1,Pc=new Set,Rf=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},qo=()=>{if(!F())return;let i=Ie.peekBanner,g=Ie.peekTextNode;if(!i||!g)return;if(X){i.classList.remove("persona-pill-peek--visible");return}let m=O?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Et=m[At];if(Et.role==="assistant"&&Et.content){b=Et;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let A=b.content,k=!!b.streaming,Q=Rf(),N=ja(Q),K=N.type!=="none"?mr(N.type,Q?.plugins):null,ae=K?.isAnimating?.(b)===!0,ge=K!==null&&(k||ae);ge&&K&&!Pc.has(K.name)&&(qa(K,e),Pc.add(K.name));let re=ge&&K?.containerClass?K.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==re&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),re&&we!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),ge?(g.style.setProperty("--persona-stream-step",`${N.speed}ms`),g.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ue=ge?Ua(A,N.buffer,K,b,k):A;if(ge&&N.placeholder==="skeleton"&&k&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Et=hs();Et.classList.add("persona-pill-peek__skeleton"),At.appendChild(Et),Oa(g,At)}else{let At=Math.max(0,Ue.length-100),Et=Ue.length>100?Ue.slice(-100):Ue,W=oo(Et);if(!ge||!K){let Ee=Ue.length>100?`\u2026${Et}`:Et;g.textContent!==Ee&&(g.textContent=Ee)}else{let Ee=W;(K.wrap==="char"||K.wrap==="word")&&(Ee=ms(W,K.wrap,`peek-${b.id}`,{skipTags:K.skipTags,startIndex:At}));let Ne=document.createElement("div");if(Ne.innerHTML=Ee,K.useCaret&&Et.length>0){let Se=Va(),wt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=wt[wt.length-1];ut?.parentNode?ut.parentNode.insertBefore(Se,ut.nextSibling):Ne.appendChild(Se)}Oa(g,Ne),K.onAfterRender?.({container:g,bubble:i,messageId:b.id,message:b,speed:N.speed,duration:N.duration})}}let nn=yn||Or;i.classList.toggle("persona-pill-peek--visible",nn)};if(F()){let i=Ie.peekBanner;if(i){let b=A=>{A.preventDefault(),A.stopPropagation(),dt(!0,"user")};i.addEventListener("pointerdown",b),ze.push(()=>{i.removeEventListener("pointerdown",b)})}let g=()=>{Or||(Or=!0,qo())},m=()=>{Or&&(Or=!1,qo())};de.addEventListener("pointerenter",g),de.addEventListener("pointerleave",m),ze.push(()=>{de.removeEventListener("pointerenter",g),de.removeEventListener("pointerleave",m)}),et&&(et.addEventListener("pointerenter",g),et.addEventListener("pointerleave",m),ze.push(()=>{et.removeEventListener("pointerenter",g),et.removeEventListener("pointerleave",m)}))}let Wf=i=>{let g=o.launcher?.composerBar??{},m=g.expandedSize??"anchored",b=g.bottomOffset??"16px",A=g.collapsedMaxWidth,k=g.expandedMaxWidth??"880px",Q=g.expandedTopOffset??"5vh",N=g.modalMaxWidth??"880px",K=g.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",re=He.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",et){let we=et.style;we.bottom=b,we.width=A??""}if(i&&m!=="fullscreen"){if(m==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=N,re.maxWidth=ae,re.maxHeight=K,re.height=K;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${b} + ${ge})`,re.top=Q,re.width=k,re.maxWidth=ae}},_r=()=>{if(!$())return;if(F()){let ae=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=X?"expanded":"collapsed";He.dataset.state=ge,He.dataset.expandedSize=ae,et&&(et.dataset.state=ge,et.dataset.expandedSize=ae),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Wf(X),fe.style.display=X?"flex":"none",Os(),X?(Pf(),If()):(kc(),Lc()),qo();return}let i=Dt(o),g=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=m,k=b&&A&&M,Q=gn(o).reveal;X?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-95","persona-opacity-0"),de.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Kt&&(Kt.style.display="none")):(i?i&&(Q==="overlay"||Q==="push")&&!k?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),de.classList.remove("persona-scale-100","persona-opacity-100"),de.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=i?"none":"":Kt&&(Kt.style.display=i?"none":""))},dt=(i,g="user")=>{if(!$()||X===i)return;let m=X;X=i,_r();let b=(()=>{let k=o.launcher?.sidebarMode??!1,Q=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,ae=Q.innerWidth<=K,ge=Dt(o)&&N&&ae,re=F()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||N&&ae&&M||ge||re})();if(X&&b){if(!An){let k=e.getRootNode(),Q=k instanceof ShadowRoot?k.host:e.closest(".persona-host");Q&&(An=vl(Q,o.launcher?.zIndex??Vt))}Sn||(Sn=wl(e.ownerDocument))}else X||(An?.(),An=null,Sn?.(),Sn=null);X&&(jr(),Tc()||(sn()==="follow"?Yn(!0):Ac()));let A={open:X,source:g,timestamp:Date.now()};X&&!m?p.emit("widget:opened",A):!X&&m&&p.emit("widget:closed",A),p.emit("widget:state",{open:X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()})},Ei=i=>{rt(i?"stop":"send"),V&&(V.disabled=i),$s.buttons.forEach(g=>{g.disabled=i}),J.dataset.personaComposerStreaming=i?"true":"false",J.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},ki=()=>{Ge.active||ue&&ue.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ki(),200)});let Ic=()=>{y.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",P.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",ue.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=se.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(se.classList.remove("persona-gap-3"),se.classList.add("persona-gap-6")):(se.classList.remove("persona-gap-6"),se.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!O?.isStreaming()&&(Ce.textContent=o.copy?.sendButtonLabel??"Send"),ue.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ue.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{R(g=>({...g,sessionId:i}))}});let To=null,Hf=()=>{To==null&&(To=setInterval(()=>{let i=Pe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(To),To=null;return}let g=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=ya(g-b))})},100))},Li=(i,g)=>{if(Object.is(i,g))return!0;if(i===null||g===null||typeof i!="object"||typeof g!="object")return!1;if(Array.isArray(i)||Array.isArray(g))return!Array.isArray(i)||!Array.isArray(g)||i.length!==g.length?!1:i.every((Q,N)=>Li(Q,g[N]));let m=i,b=g,A=Object.keys(m),k=Object.keys(b);return A.length===k.length&&A.every(Q=>Object.prototype.hasOwnProperty.call(b,Q)&&Li(m[Q],b[Q]))},Rc=i=>{let{content:g,rawContent:m,llmContent:b,...A}=i;return A},Pi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Ul(i),Bf=(i,g,m)=>{if(i.length!==g.length)return!1;let b=i[m.index],A=g[m.index];return!b||!A||b.id!==m.id||A.id!==m.id?!1:(!Object.is(b.content,A.content)||!Object.is(b.rawContent,A.rawContent)||!Object.is(b.llmContent,A.llmContent))&&Pi(b)&&Pi(A)&&Li(Rc(b),Rc(A))},Wc=null,Ko=null,Mo=null,Rn=null,Js=i=>{Wc=i;let g,m;Ko=null;for(let A=i.length-1;A>=0;A-=1){let k=i[A];if(!g&&k.role==="user"&&(g=k),!m&&k.role==="assistant"&&(m=k),!Ko&&Pi(k)&&(Ko={index:A,id:k.id}),g&&m&&Ko)break}Dr(Pe,i,Z),fl(Pe,mn.artifacts,{suppressTransition:yn}),Hf(),bi(i),Yn(!yn),kf(i),i.length===0&&(Br(),Rr=!0,Us=!1,Vs=null,qs=!1),!wi||js?(wi=!0,Ir=g?.id??null,xi=m?.id??null):g&&g.id!==Ir?(Ir=g.id,Tf(g.id)):m&&m.id!==xi&&Mf(),m&&(xi=m.id),Ef(i);let b=Ge.lastUserMessageId;g&&g.id!==b&&(Ge.lastUserMessageId=g.id,p.emit("user:message",g)),Ge.lastUserMessageWasVoice=!!g?.viaVoice,Si(i),qo()},Ii=()=>{Rn!==null&&(cancelAnimationFrame(Rn),Rn=null);let i=Mo;Mo=null,i&&Js(i)},Hc=()=>{Rn!==null&&cancelAnimationFrame(Rn),Rn=null,Mo=null},Df=i=>{let g=Mo??Wc;if(yn&&g&&Ko&&Bf(g,i,Ko)){Mo=i,Rn===null&&(Rn=requestAnimationFrame(()=>{Rn=null;let m=Mo;Mo=null,m&&Js(m)}));return}if(i.length===0){Hc(),Js(i);return}Ii(),Js(i)};O=new Ta(o,{onMessagesChanged(i){Df(i)},onStatusChanged(i){let g=o.statusIndicator??{};qt(D,(b=>b==="idle"?g.idleText??Lt.idle:b==="connecting"?g.connectingText??Lt.connecting:b==="connected"?g.connectedText??Lt.connected:b==="error"?g.errorText??Lt.error:b==="paused"?g.pausedText??Lt.paused:b==="resuming"?g.resumingText??Lt.resuming:Lt[b])(i),g,i)},onStreamingChanged(i){i||(O?.getMessages().length===0?Hc():Ii()),yn=i,Ei(i),O&&Dr(Pe,O.getMessages(),Z),i||Yn(!0),tn(),nc(i?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Wn(),Qo();break;case"processing":Wn(),Kf();break;case"speaking":Wn(),Gf();break;default:i==="idle"&&O.isBargeInActive()?(Wn(),Qo(),V?.setAttribute("aria-label","End voice session")):(Ge.active=!1,Wn(),In("system"),vn());break}},onArtifactsState(i){mn=i,i.artifacts.length===0&&($o=!1),fl(Pe,i.artifacts,{suppressTransition:yn}),Pn(),Si()},onReconnect(i){let{executionId:g,lastEventId:m}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:g,after:m}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:g,after:m,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:g,after:m})}}),lt.current=O,ze.push(()=>O.cancel());let Ri=null;if(O.onReadAloudChange((i,g)=>{lc=i,cc=g,dc();let m=i??Ri;i&&(Ri=i);let b=m?O.getMessages().find(A=>A.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:b,state:g,timestamp:Date.now()}),g==="idle"&&(Ri=null)}),wi=!0,o.voiceRecognition?.provider?.type==="runtype")try{O.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&O.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Me||o.onSSEEvent)&&O.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),De?.processEvent(i,g),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let Bc=()=>{o.resume&&typeof o.reconnectStream=="function"&&O.resumeFromHandle(o.resume)};w?w.then(i=>{if(i){if(i.metadata&&(u=Vl(i.metadata),E.syncFromMetadata()),i.messages?.length){js=!0;try{O.hydrateMessages(i.messages)}finally{js=!1}}i.artifacts?.length&&O.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Bc()):Bc();let Dc=()=>{!F()||X||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},Ff=(i,g)=>i?g?{refs:[...i.refs,...g.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([i.finalize(),g.finalize()]),A=[];return m.status==="fulfilled"?A.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?A.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),pb(A)}}:i:g,Nf=()=>{let g=ue.getInlineMessageFields?.();return g&&g.contentSegments.some(b=>b.kind==="mention")?g.contentSegments:void 0},$r=!1,Of=async i=>{let g=ue.value.trim(),m=Ct?.hasAttachments()??!1,b=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(b?.kind==="action"){ue.value="",ue.style.height="auto",zr(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,k=b?.kind==="server"?b.mentions:null,Q=Ff(A,k),N=b?.kind==="prompt"?b.sendText:g,K=!!A&&A.refs.length>0;if(!N&&!m&&!K&&!k)return;Dc();let ae;m&&(ae=[],ae.push(...Ct.getContentParts()),N&&ae.push(ar(N)));let ge=b?.kind==="prompt"?void 0:Nf();ue.value="",ue.style.height="auto",zr(),O.sendMessage(N,{contentParts:ae,mentions:Q??void 0,contentSegments:ge,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),A&&Zt?.clear()},Wi=async i=>{if(!$r){$r=!0;try{await Of(i)}finally{$r=!1}}},Fc=i=>{if(i.preventDefault(),O.isStreaming()){O.cancel(),De?.reset(),Qe?.update();return}$r||Wi()},_f=()=>o.features?.composerHistory!==!1,Hi={...hl},Bi=!1,zr=()=>{Hi={...hl}},$f=()=>O.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),zf=i=>{if(!ue)return;Bi=!0,ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),Bi=!1;let g=ue.value.length;ue.setSelectionRange(g,g)},jf=i=>{Bi||(i.isComposing||Zt?.handleInput(i.inputType??void 0),zr())},Uf=i=>{if(ue&&!(!i.isComposing&&Zt?.handleKeydown(i))){if(_f()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=ue.selectionStart===0&&ue.selectionEnd===0,m=zp({direction:i.key==="ArrowUp"?"up":"down",history:$f(),currentValue:ue.value,atStart:g,state:Hi});if(Hi=m.state,m.handled){i.preventDefault(),m.value!==void 0&&zf(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(O.isStreaming()){i.preventDefault();return}if($r){i.preventDefault();return}zr(),i.preventDefault(),Ce.click()}}},Nc=i=>{i.key!=="Escape"||i.isComposing||O.isStreaming()&&i.composedPath().includes(fe)&&(O.cancel(),De?.reset(),Qe?.update(),zr(),i.preventDefault(),i.stopImmediatePropagation())},Vf=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let g=ib(i.clipboardData);g.length!==0&&(i.preventDefault(),await Ct.handleFiles(g))},cn=null,Tn=!1,Go=null,bt=null,Oc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ys=(i="user")=>{if(Tn||O.isStreaming())return;let g=Oc();if(!g)return;cn=new g;let b=(o.voiceRecognition??{}).pauseDuration??2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let A=ue.value;cn.onresult=k=>{let Q="",N="";for(let ae=0;ae<k.results.length;ae++){let ge=k.results[ae],re=ge[0].transcript;ge.isFinal?Q+=re+" ":N=re}let K=A+Q+N;ue.value=K,Go&&clearTimeout(Go),(Q||N)&&(Go=window.setTimeout(()=>{ue.value.trim()&&cn&&Tn&&(Zn(),Wi({viaVoice:!0}))},b))},cn.onerror=k=>{k.error!=="no-speech"&&Zn()},cn.onend=()=>{if(Tn){let k=ue.value.trim();k&&k!==A.trim()&&Wi({viaVoice:!0}),Zn()}};try{if(cn.start(),Tn=!0,Ge.active=!0,i!=="system"&&(Ge.manuallyDeactivated=!1),In(i),vn(),V){let k=o.voiceRecognition??{};bt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??o.sendButton?.size??"40")||24};let Q=k.recordingBackgroundColor,N=k.recordingIconColor,K=k.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Q??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let ae=V.querySelector("svg");ae&&ae.setAttribute("stroke",N)}K&&(V.style.borderColor=K),V.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(i="user")=>{if(Tn){if(Tn=!1,Go&&(clearTimeout(Go),Go=null),cn){try{cn.stop()}catch{}cn=null}if(Ge.active=!1,In(i),vn(),V){if(V.classList.remove("persona-voice-recording"),bt){V.style.backgroundColor=bt.backgroundColor,V.style.color=bt.color,V.style.borderColor=bt.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",bt.color||"currentColor"),bt=null}V.setAttribute("aria-label","Start voice recognition")}}},qf=(i,g)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",A=i?.provider?.type==="custom";if(!(m||b||A))return null;let Q=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let K=i?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",K);let ae=i?.iconName??"mic",ge=g?.size??"40px",re=i?.iconSize??ge,we=parseFloat(re)||24,Ue=i?.backgroundColor??g?.backgroundColor,pt=i?.iconColor??g?.textColor;N.style.width=re,N.style.height=re,N.style.minWidth=re,N.style.minHeight=re,N.style.fontSize="18px",N.style.lineHeight="1",pt?N.style.color=pt:N.style.color="var(--persona-text, #111827)";let nn=ie(ae,we,pt||"currentColor",1.5);nn?N.appendChild(nn):N.textContent="\u{1F3A4}",Ue?N.style.backgroundColor=Ue:N.style.backgroundColor="",i?.borderWidth&&(N.style.borderWidth=i.borderWidth,N.style.borderStyle="solid"),i?.borderColor&&(N.style.borderColor=i.borderColor),i?.paddingX&&(N.style.paddingLeft=i.paddingX,N.style.paddingRight=i.paddingX),i?.paddingY&&(N.style.paddingTop=i.paddingY,N.style.paddingBottom=i.paddingY),Q.appendChild(N);let At=i?.showTooltip??!1;return Ot({anchor:N,trigger:Q,text:()=>N.getAttribute("aria-label")??K,enabled:At}),{micButton:N,micButtonWrapper:Q}},Di=()=>{if(!V||bt)return;let i=o.voiceRecognition??{};bt={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Fi=(i,g)=>{if(!V)return;let m=V.querySelector("svg");m&&m.remove();let b=bt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ie(i,b,g,1.5);A&&V.appendChild(A)},Zs=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qo=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(Zs(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let A=V.querySelector("svg");A&&A.setAttribute("stroke",m)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},Kf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??bt?.color??"",A=i.processingBackgroundColor??bt?.backgroundColor??"",k=i.processingBorderColor??bt?.borderColor??"";Zs(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=A,V.style.borderColor=k;let Q=b||"currentColor";V.style.color=Q,Fi(m,Q),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},Gf=()=>{if(!V)return;Di();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),m=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,A=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??bt?.color??"":bt?.color??""),k=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),Q=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":bt?.borderColor??"");Zs(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=k,V.style.borderColor=Q;let N=A||"currentColor";V.style.color=N,Fi(b,N);let K=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",K),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},Wn=()=>{V&&(Zs(),bt&&(V.style.backgroundColor=bt.backgroundColor??"",V.style.color=bt.color??"",V.style.borderColor=bt.borderColor??"",Fi(bt.iconName,bt.color||"currentColor"),bt=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},ea=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=O.getVoiceStatus(),g=O.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()});return}O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),Ge.manuallyDeactivated=!O.isVoiceActive(),vn(),In("user"),O.isVoiceActive()?Qo():Wn()});return}if(Tn){let i=ue.value.trim();Ge.manuallyDeactivated=!0,vn(),Zn("user"),i&&(ue.value="",ue.style.height="auto",O.sendMessage(i))}else Ge.manuallyDeactivated=!1,vn(),Ys("user")};rc=ea,V&&(V.addEventListener("click",ea),ze.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Wn()):Zn("system"),V&&V.removeEventListener("click",ea)}));let Qf=p.on("assistant:complete",()=>{yc&&(Ge.active||Ge.manuallyDeactivated||yc==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("auto"),O.isVoiceActive()&&Qo()}):Ys("auto"))},600))});ze.push(Qf);let Xf=p.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ze.push(Xf);let _c=()=>{dt(!X,"user")},Ft=null,Kt=null;if(M&&!F()){let{instance:i,element:g}=Cl({config:o,plugins:s,onToggle:_c});Ft=i,i||(Kt=g)}Ft?e.appendChild(Ft.element):Kt&&e.appendChild(Kt),_r(),bi(),Ic(),Ei(O.isStreaming()),Tc()||(sn()==="follow"?Yn(!0):Ac()),vf(),G&&(!M||F()?setTimeout(()=>ki(),0):X&&setTimeout(()=>ki(),200));let jr=()=>{if(F()){_o(),_r();return}let i=Dt(o),g=o.launcher?.sidebarMode??!1,m=i||g||(o.launcher?.fullHeight??!1),b=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,Q=b.innerWidth<=k,N=A&&Q&&M;try{if(N){Er(),kr=Ns();return}let K=!1;oe&&(oe=!1,Er(),K=!0);let ae=Ns();if(!K&&ae!==kr&&(Er(),K=!0),kr=ae,K&&hi(),!M&&!i){de.style.height="",de.style.width="";return}if(!g&&!i){let re=o?.launcher?.width??o?.launcherWidth??$n;de.style.width=re,de.style.maxWidth=re}if(Fs(),!m){let ge=b.innerHeight,re=64,we=o.launcher?.heightOffset??0,Ue=Math.max(200,ge-re),pt=Math.min(640,Ue),nt=Math.max(200,pt-we);de.style.height=`${nt}px`}}finally{if(_o(),_r(),X&&M){let ae=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,we=Dt(o)&&re&&ae,Ue=ge||re&&ae&&M||we;if(Ue&&!Sn){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!An&&(An=vl(nt,o.launcher?.zIndex??Vt)),Sn=wl(e.ownerDocument)}else Ue||(An?.(),An=null,Sn?.(),Sn=null)}}};jr();let $c=e.ownerDocument.defaultView??window;if($c.addEventListener("resize",jr),ze.push(()=>$c.removeEventListener("resize",jr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{_o()});i.observe(J),ze.push(()=>i.disconnect())}an=se.scrollTop;let zc=En(se),jc=()=>{let i=se.scrollTop,g=En(se),m=g<zc;if(zc=g,!Un()){an=i,tn();return}let{action:b,nextLastScrollTop:A}=$a({following:en.isFollowing(),currentScrollTop:i,lastScrollTop:an,nearBottom:uo(se,Ks),userScrollThreshold:yf,isAutoScrolling:ln||zs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(an=A,b==="resume"){Qs()||Jn();return}b==="pause"&&Hr()};if(se.addEventListener("scroll",jc,{passive:!0}),ze.push(()=>se.removeEventListener("scroll",jc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Sf(),zi(Pe)});i.observe(Pe),i.observe(se),ze.push(()=>i.disconnect())}let Uc=()=>{Un()&&en.isFollowing()&&Qs()&&Hr()},Vc=se.ownerDocument;Vc.addEventListener("selectionchange",Uc),ze.push(()=>{Vc.removeEventListener("selectionchange",Uc)});let Jf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),qc=i=>{Jf.has(i.key)&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())},Kc=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Ao(),Zl()&&Un()&&en.isFollowing()&&Hr())};se.addEventListener("keydown",qc),se.addEventListener("focusin",Kc),ze.push(()=>{se.removeEventListener("keydown",qc),se.removeEventListener("focusin",Kc)});let Gc=i=>{if(i.deltaY!==0&&Ao(),!Un())return;let g=za({following:en.isFollowing(),deltaY:i.deltaY,nearBottom:uo(se,Ks),resumeWhenNearBottom:!0});g==="pause"?Hr():g==="resume"&&!Qs()&&Jn()};se.addEventListener("wheel",Gc,{passive:!0}),se.addEventListener("touchmove",Ao,{passive:!0}),se.addEventListener("pointerdown",Ao,{passive:!0}),ze.push(()=>{se.removeEventListener("touchmove",Ao),se.removeEventListener("pointerdown",Ao)}),ze.push(()=>se.removeEventListener("wheel",Gc)),Tt.addEventListener("click",()=>{Br(),se.scrollTop=se.scrollHeight,an=se.scrollTop,Jn(),Yn(!0),tn()}),ze.push(()=>Tt.remove()),ze.push(()=>{wc(),Br()});let Qc=()=>{T&&(vo&&(T.removeEventListener("click",vo),vo=null),$()?(T.style.display="",vo=()=>{dt(!1,"user")},T.addEventListener("click",vo)):T.style.display="none")};Qc(),(()=>{let{clearChatButton:i}=Ie;i&&i.addEventListener("click",()=>{O.clearMessages(),wo.clear(),Jn(),rr(Ie.composerOverlay);try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()})})(),S&&S.addEventListener("submit",Fc);let Xc=[["keydown",Uf],["input",jf],["paste",Vf],["focus",uf]],Jc=i=>{if(i)for(let[g,m]of Xc)i.addEventListener(g,m)},Yc=i=>{if(i)for(let[g,m]of Xc)i.removeEventListener(g,m)};Jc(ue),Zt?.onComposerSwap((i,g)=>{Yc(g),ue=i,Jc(i)});let Zc=e.ownerDocument??document;Zc.addEventListener("keydown",Nc,!0);let ed="persona-attachment-drop-active",Ur=0,Ni=()=>{Ur=0,fe.classList.remove(ed)},Xo=()=>o.attachments?.enabled===!0&&Ct!==null,td=i=>{!li(i.dataTransfer)||!Xo()||(Ur++,Ur===1&&fe.classList.add(ed))},nd=i=>{!li(i.dataTransfer)||!Xo()||(Ur--,Ur<=0&&Ni())},od=i=>{!li(i.dataTransfer)||!Xo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},rd=i=>{if(!li(i.dataTransfer)||!Xo())return;i.preventDefault(),i.stopPropagation(),Ni();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Ct.handleFiles(g)},eo=!0;fe.addEventListener("dragenter",td,eo),fe.addEventListener("dragleave",nd,eo),e.addEventListener("dragover",od,eo),e.addEventListener("drop",rd,eo);let ta=e.ownerDocument,sd=i=>{Xo()&&i.preventDefault()},ad=i=>{Xo()&&i.preventDefault()};ta.addEventListener("dragover",sd),ta.addEventListener("drop",ad),ze.push(()=>{S&&S.removeEventListener("submit",Fc),Yc(ue),Zc.removeEventListener("keydown",Nc,!0),Zt?.destroy()}),ze.push(()=>{fe.removeEventListener("dragenter",td,eo),fe.removeEventListener("dragleave",nd,eo),e.removeEventListener("dragover",od,eo),e.removeEventListener("drop",rd,eo),ta.removeEventListener("dragover",sd),ta.removeEventListener("drop",ad),Ni()}),ze.push(()=>{O.cancel()}),Ft?ze.push(()=>{Ft?.destroy()}):Kt&&ze.push(()=>{Kt?.remove()});let Mt={update(i){let g=o.toolCall,m=o.messageActions,b=o.layout?.messages,A=o.colorScheme,k=o.loadingIndicator,Q=o.iterationDisplay,N=o.features?.showReasoning,K=o.features?.showToolCalls,ae=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=Nu({...o,features:r},i),r=o.features,o=Dl(o),Os(),cs(e,o),Ts(e,o),Ms(e,o),Pn(),o.colorScheme!==A&&hc();let we=_l.getForInstance(o.plugins);s.length=0,s.push(...we),M=o.launcher?.enabled??!0,_=o.launcher?.autoExpand??!1,ce=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,Y=o.features?.scrollToBottom??{};let Ue=sn();pe=o.features?.scrollBehavior??{},Ue!==sn()&&(Br(),Jn()),oc(),tn();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(Me||(ve=new As(ye),Me=new Cs(je,ve),De=De??new Ss,ve.open().then(()=>Me?.restore()).catch(()=>{}),O.setSSEEventCallback((ne,Ke)=>{o.onSSEEvent?.(ne,Ke),De?.processEvent(ne,Ke),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!tt&&z){let ne=o.features?.eventStream?.classNames,Ke="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne?.toggleButton?" "+ne.toggleButton:"");tt=h("button",Ke),tt.style.width="28px",tt.style.height="28px",tt.style.color=Qt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let mt=ie("activity","18px","currentColor",1.5);mt&&tt.appendChild(mt);let ot=Ie.clearChatButtonWrapper,st=Ie.closeButtonWrapper,jt=ot||st;jt&&jt.parentNode===z?z.insertBefore(tt,jt):z.appendChild(tt),tt.addEventListener("click",()=>{Ve?Tr():ui()})}}else!le&&pt&&(Tr(),tt&&(tt.remove(),tt=null),Me?.clear(),ve?.destroy(),Me=null,ve=null,De?.reset(),De=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Ft&&!Kt){let{instance:ne,element:Ke}=Cl({config:o,plugins:s,onToggle:_c});Ft=ne,ne||(Kt=Ke),e.appendChild(Ke)}Ft&&Ft.update(o),q&&o.launcher?.title!==void 0&&(q.textContent=o.launcher.title),H&&o.launcher?.subtitle!==void 0&&(H.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==U&&z){let ne=nt?Qa(o,nt,{showClose:$(),onClose:()=>dt(!1,"user")}):Ho({config:o,showClose:$(),onClose:()=>dt(!1,"user")});xt.replaceHeader(ne),z=xt.header.element,I=xt.header.iconHolder,q=xt.header.headerTitle,H=xt.header.headerSubtitle,T=xt.header.closeButton,U=nt?.layout}else if(nt){if(I&&(I.style.display=nt.showIcon===!1?"none":""),q&&(q.style.display=nt.showTitle===!1?"none":""),H&&(H.style.display=nt.showSubtitle===!1?"none":""),T){let ne=$()&&nt.showCloseButton!==!1;T.style.display=ne?"":"none"}if(Ie.clearChatButtonWrapper){let ne=nt.showClearChat;if(ne!==void 0){Ie.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ke}=Ie;Ke&&!Ke.classList.contains("persona-absolute")&&(ne?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;z&&(z.style.display=At?"":"none");let Et=o.layout?.showFooter!==!1;J&&(J.style.display=Et?"":"none"),_o(),tn(),M!==j?M?dt(_,"auto"):(X=!0,_r()):_!==x&&dt(_,"auto"),x=_,j=M,jr(),Qc();let Ne=JSON.stringify(o.toolCall)!==JSON.stringify(g),Se=JSON.stringify(o.messageActions)!==JSON.stringify(m),wt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ut=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,Bt=o.iterationDisplay!==Q,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);(Ne||Se||wt||ut||Bt||ft)&&O&&(vi++,Dr(Pe,O.getMessages(),Z));let kt=o.features?.streamAnimation?.type;if(kt!==re&&kt&&kt!=="none"){let ne=mr(kt,o.features?.streamAnimation?.plugins);ne&&qa(ne,e)}let ke=o.launcher??{},Oe=ke.headerIconHidden??!1,_t=o.layout?.header?.showIcon,$t=Oe||_t===!1,vt=ke.headerIconName,ct=ke.headerIconSize??"48px";if(I){let ne=fe.querySelector(".persona-border-b-persona-divider"),Ke=ne?.querySelector(".persona-flex-col");if($t)I.style.display="none",ne&&Ke&&!ne.contains(Ke)&&ne.insertBefore(Ke,ne.firstChild);else{if(I.style.display="",I.style.height=ct,I.style.width=ct,ne&&Ke&&(ne.contains(I)?I.nextSibling!==Ke&&(I.remove(),ne.insertBefore(I,Ke)):ne.insertBefore(I,Ke)),vt){let ot=parseFloat(ct)||24,st=ie(vt,ot*.6,"currentColor",1);st?I.replaceChildren(st):I.textContent=ke.agentIconText??"\u{1F4AC}"}else if(ke.iconUrl){let ot=I.querySelector("img");if(ot)ot.src=ke.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let st=document.createElement("img");st.src=ke.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,I.replaceChildren(st)}}else{let ot=I.querySelector("svg"),st=I.querySelector("img");(ot||st)&&I.replaceChildren(),I.textContent=ke.agentIconText??"\u{1F4AC}"}let mt=I.querySelector("img");mt&&(mt.style.height=ct,mt.style.width=ct)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(q&&(q.style.display=gt===!1?"none":""),H&&(H.style.display=Ze===!1?"none":""),T){let ne=$()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ne?"":"none";let Ke=ke.closeButtonSize??"32px",mt=ke.closeButtonPlacement??"inline";T.style.height=Ke,T.style.width=Ke;let{closeButtonWrapper:ot}=Ie,st=mt==="top-right",jt=ot?.classList.contains("persona-absolute");if(ot&&st!==jt)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(ot);else{let no=ke.clearChat?.placement??"inline",Kr=ke.clearChat?.enabled??!0;ot.className=Kr&&no==="inline"?"":"persona-ml-auto";let id=fe.querySelector(".persona-border-b-persona-divider");id&&id.appendChild(ot)}if(T.style.color=ke.closeButtonColor||Qt.actionIconColor,ke.closeButtonBackgroundColor?(T.style.backgroundColor=ke.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),ke.closeButtonBorderWidth||ke.closeButtonBorderColor){let no=ke.closeButtonBorderWidth||"0px",Kr=ke.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${Kr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");ke.closeButtonBorderRadius?(T.style.borderRadius=ke.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),ke.closeButtonPaddingX?(T.style.paddingLeft=ke.closeButtonPaddingX,T.style.paddingRight=ke.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),ke.closeButtonPaddingY?(T.style.paddingTop=ke.closeButtonPaddingY,T.style.paddingBottom=ke.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let on=ke.closeButtonIconName??"x",wn=ke.closeButtonIconText??"\xD7";T.innerHTML="";let Nt=ie(on,"28px","currentColor",1);Nt?(Nt.style.display="block",T.appendChild(Nt)):T.textContent=wn;let Ut=ke.closeButtonTooltipText??"Close chat",Bn=ke.closeButtonShowTooltip??!0;T.setAttribute("aria-label",Ut),ot&&Ot({anchor:T,trigger:ot,text:()=>T?.getAttribute("aria-label")??Ut,enabled:Bn})}let{clearChatButton:We,clearChatButtonWrapper:ht}=Ie;if(We){let ne=ke.clearChat??{},Ke=ne.enabled??!0,mt=o.layout?.header?.showClearChat,ot=mt!==void 0?mt:Ke,st=ne.placement??"inline";if(ht){ht.style.display=ot?"":"none";let{closeButtonWrapper:jt}=Ie;!F()&&jt&&!jt.classList.contains("persona-absolute")&&(ot?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let on=st==="top-right",wn=ht.classList.contains("persona-absolute");if(!F()&&on!==wn&&ot){if(ht.remove(),on)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",fe.style.position="relative",fe.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let Ut=fe.querySelector(".persona-border-b-persona-divider"),Bn=Ie.closeButtonWrapper;Ut&&Bn&&Bn.parentElement===Ut?Ut.insertBefore(ht,Bn):Ut&&Ut.appendChild(ht)}let Nt=Ie.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(on?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!F()){let no=ne.size??"32px";We.style.height=no,We.style.width=no}let jt=ne.iconName??"refresh-cw",on=ne.iconColor??"";We.style.color=on||Qt.actionIconColor,We.innerHTML="";let wn=F()?"14px":"20px",Nt=ie(jt,wn,"currentColor",1);if(Nt&&(Nt.style.display="block",We.appendChild(Nt)),ne.backgroundColor?(We.style.backgroundColor=ne.backgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let no=ne.borderWidth||"0px",Kr=ne.borderColor||"transparent";We.style.border=`${no} solid ${Kr}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");ne.borderRadius?(We.style.borderRadius=ne.borderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),ne.paddingX?(We.style.paddingLeft=ne.paddingX,We.style.paddingRight=ne.paddingX):(We.style.paddingLeft="",We.style.paddingRight=""),ne.paddingY?(We.style.paddingTop=ne.paddingY,We.style.paddingBottom=ne.paddingY):(We.style.paddingTop="",We.style.paddingBottom="");let Ut=ne.tooltipText??"Clear chat",Bn=ne.showTooltip??!0;We.setAttribute("aria-label",Ut),ht&&Ot({anchor:We,trigger:ht,text:()=>We?.getAttribute("aria-label")??Ut,enabled:Bn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[zl],pn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Es.message,Es.messageAndClick];E=jl({parsers:zt,handlers:pn,getSessionMetadata:C,updateSessionMetadata:R,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=Gu(o,E,Ae),O.updateConfig(o),Dr(Pe,O.getMessages(),Z),bi(),Ic(),Ei(O.isStreaming());let Vr=o.voiceRecognition?.enabled===!0,na=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),St=o.voiceRecognition?.provider?.type==="runtype";if(Vr&&(na||St))if(!V||!_e){let ne=qf(o.voiceRecognition,o.sendButton);ne&&(V=ne.micButton,_e=ne.micButtonWrapper,Re.insertBefore(_e,te),V.addEventListener("click",ea),V.disabled=O.isStreaming())}else{let ne=o.voiceRecognition??{},Ke=o.sendButton??{},mt=ne.iconName??"mic",ot=Ke.size??"40px",st=ne.iconSize??ot,jt=parseFloat(st)||24;V.style.width=st,V.style.height=st,V.style.minWidth=st,V.style.minHeight=st;let on=ne.iconColor??Ke.textColor;V.innerHTML="";let wn=ie(mt,jt,on||"currentColor",1.5);wn?V.appendChild(wn):V.textContent="\u{1F3A4}";let Nt=ne.backgroundColor??Ke.backgroundColor;Nt?V.style.backgroundColor=Nt:V.style.backgroundColor="",on?V.style.color=on:V.style.color="var(--persona-text, #111827)",ne.borderWidth?(V.style.borderWidth=ne.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ne.borderColor?V.style.borderColor=ne.borderColor:V.style.borderColor="",ne.paddingX?(V.style.paddingLeft=ne.paddingX,V.style.paddingRight=ne.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ne.paddingY?(V.style.paddingTop=ne.paddingY,V.style.paddingBottom=ne.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Ut=ne.tooltipText??"Start voice recognition",Bn=ne.showTooltip??!1;V.setAttribute("aria-label",Ut),_e&&Ot({anchor:V,trigger:_e,text:()=>V?.getAttribute("aria-label")??Ut,enabled:Bn}),_e.style.display="",V.disabled=O.isStreaming()}else V&&_e&&(_e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()&&O.toggleVoice():Tn&&Zn());if(o.attachments?.enabled===!0){if(!$e||!be){let ne=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Rt||(Rt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Rt.style.display="none",S.insertBefore(Rt,ue)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),S.insertBefore(Fe,ue)),$e=h("div","persona-send-button-wrapper"),be=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),be.type="button",be.setAttribute("aria-label",ne.buttonTooltipText??"Attach file");let ot=ne.buttonIconName??"paperclip",st=mt,jt=parseFloat(st)||40,on=Math.round(jt*.6);be.style.width=st,be.style.height=st,be.style.minWidth=st,be.style.minHeight=st,be.style.fontSize="18px",be.style.lineHeight="1";let wn=ie(ot,on,"currentColor",1.5);wn?be.appendChild(wn):be.textContent="\u{1F4CE}",be.addEventListener("click",Ut=>{Ut.preventDefault(),Fe?.click()}),$e.appendChild(be);let Nt=ne.buttonTooltipText??"Attach file";Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Nt}),Je?Je.append($e):S.appendChild($e),!Ct&&Fe&&Rt&&(Ct=as.fromConfig(ne),Ct.setPreviewsContainer(Rt),Fe.addEventListener("change",async()=>{Ct&&Fe?.files&&(await Ct.handleFileSelect(Fe.files),Fe.value="")}))}else{$e.style.display="";let ne=o.attachments??{};Fe&&(Fe.accept=(ne.allowedTypes??_n).join(","),Fe.multiple=(ne.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}if(fe.querySelector(".persona-attachment-drop-overlay")?.remove(),fe.appendChild(Qu(o.attachments?.dropOverlay)),be){let ne=o.attachments??{},Ke=ne.buttonTooltipText??"Attach file";be.setAttribute("aria-label",Ke),be.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,ot=ie(ne.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);ot?be.appendChild(ot):be.textContent="\u{1F4CE}",$e&&Ot({anchor:be,trigger:$e,text:()=>be?.getAttribute("aria-label")??Ke})}}else $e&&($e.style.display="none"),Ct&&Ct.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Wt=o.sendButton??{},qr=Wt.useIcon??!1,ra=Wt.iconText??"\u2191",Jo=Wt.iconName,sa=Wt.tooltipText??"Send message",Oi=Wt.showTooltip??!1,Eo=Wt.size??"40px",Hn=Wt.backgroundColor,ko=Wt.textColor;if(qr){if(Ce.style.width=Eo,Ce.style.height=Eo,Ce.style.minWidth=Eo,Ce.style.minHeight=Eo,Ce.style.fontSize="18px",Ce.style.lineHeight="1",ko?Ce.style.color=ko:Ce.style.color="var(--persona-button-primary-fg, #ffffff)",!O.isStreaming())if(Ce.innerHTML="",Jo){let ne=parseFloat(Eo)||24,Ke=ko?.trim()||"currentColor",mt=ie(Jo,ne,Ke,2);mt?Ce.appendChild(mt):Ce.textContent=ra}else Ce.textContent=ra;Ce.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-primary")):(Ce.style.backgroundColor="",Ce.classList.add("persona-bg-persona-primary"))}else Ce.textContent=o.copy?.sendButtonLabel??"Send",Ce.style.width="",Ce.style.height="",Ce.style.minWidth="",Ce.style.minHeight="",Ce.style.fontSize="",Ce.style.lineHeight="",Ce.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Hn?(Ce.style.backgroundColor=Hn,Ce.classList.remove("persona-bg-persona-accent")):Ce.classList.add("persona-bg-persona-accent"),ko?Ce.style.color=ko:Ce.classList.add("persona-text-white");Wt.borderWidth?(Ce.style.borderWidth=Wt.borderWidth,Ce.style.borderStyle="solid"):(Ce.style.borderWidth="",Ce.style.borderStyle=""),Wt.borderColor?Ce.style.borderColor=Wt.borderColor:Ce.style.borderColor="",Wt.paddingX?(Ce.style.paddingLeft=Wt.paddingX,Ce.style.paddingRight=Wt.paddingX):(Ce.style.paddingLeft="",Ce.style.paddingRight=""),Wt.paddingY?(Ce.style.paddingTop=Wt.paddingY,Ce.style.paddingBottom=Wt.paddingY):(Ce.style.paddingTop="",Ce.style.paddingBottom=""),O.isStreaming()||Ce.setAttribute("aria-label",sa),te&&Ot({anchor:Ce,trigger:te,text:()=>Ce.getAttribute("aria-label")??sa,enabled:Oi});let aa=o.layout?.contentMaxWidth??(F()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);aa?(Pe.style.maxWidth=aa,Pe.style.marginLeft="auto",Pe.style.marginRight="auto",Pe.style.width="100%",S&&(S.style.maxWidth=aa,S.style.marginLeft="auto",S.style.marginRight="auto"),it&&(it.style.maxWidth=aa,it.style.marginLeft="auto",it.style.marginRight="auto")):(Pe.style.maxWidth="",Pe.style.marginLeft="",Pe.style.marginRight="",Pe.style.width="",S&&(S.style.maxWidth="",S.style.marginLeft="",S.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let to=o.statusIndicator??{},Yf=to.visible??!0;if(D.style.display=Yf?"":"none",O){let ne=O.getStatus();qt(D,(mt=>mt==="idle"?to.idleText??Lt.idle:mt==="connecting"?to.connectingText??Lt.connecting:mt==="connected"?to.connectedText??Lt.connected:mt==="error"?to.errorText??Lt.error:Lt[mt])(ne),to,ne)}D.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Zf=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";D.classList.add(Zf)},open(){$()&&dt(!0,"api")},close(){$()&&dt(!1,"api")},toggle(){$()&&dt(!X,"api")},reconnect(){O.reconnectNow()},clearChat(){Ln=!1,O.clearMessages(),wo.clear(),Jn();try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c?.clear&&Ai(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),Me?.clear(),De?.reset(),Qe?.update()},setMessage(i){return!ue||O.isStreaming()?!1:(!X&&$()&&dt(!0,"system"),ue.value=i,ue.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(O.isStreaming())return!1;let g=i?.trim()||ue.value.trim();return g?(!X&&$()&&dt(!0,"system"),ue.value="",ue.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return O.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()||(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),O.toggleVoice().then(()=>{Ge.active=O.isVoiceActive(),In("user"),O.isVoiceActive()&&Qo()})),!0):Tn?!0:Oc()?(!X&&$()&&dt(!0,"system"),Ge.manuallyDeactivated=!1,vn(),Ys("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,vn(),In("user"),Wn()}),!0):!1:Tn?(Ge.manuallyDeactivated=!0,vn(),Zn("user"),!0):!1},injectMessage(i){return!X&&$()&&dt(!0,"system"),O.injectMessage(i)},injectAssistantMessage(i){!X&&$()&&dt(!0,"system");let g=O.injectAssistantMessage(i);return me&&(me=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(i){return!X&&$()&&dt(!0,"system"),O.injectUserMessage(i)},injectSystemMessage(i){return!X&&$()&&dt(!0,"system"),O.injectSystemMessage(i)},injectMessageBatch(i){return!X&&$()&&dt(!0,"system"),O.injectMessageBatch(i)},injectComponentDirective(i){return!X&&$()&&dt(!0,"system"),O.injectComponentDirective(i)},injectTestMessage(i){!X&&$()&&dt(!0,"system"),O.injectTestEvent(i)},async connectStream(i,g){return O.connectStream(i,g)},__pushEventStreamEvent(i){Me&&(De?.processEvent(i.type,i.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!le||!Me||ui()},hideEventStream(){Ve&&Tr()},isEventStreamVisible(){return Ve},showArtifacts(){Xt(o)&&(Ln=!1,$o=!0,Pn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Ln=!0,Pn())},upsertArtifact(i){return Xt(o)?(ro(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Ln=!1,$o=!0),O.upsertArtifact(i)):null},selectArtifact(i){Xt(o)&&O.selectArtifact(i)},clearArtifacts(){Xt(o)&&O.clearArtifacts()},getArtifacts(){return O?.getArtifacts()??[]},getSelectedArtifactId(){return O?.getSelectedArtifactId()??null},focusInput(){return M&&!X&&!F()||!ue?!1:(ue.focus(),!0)},async resolveApproval(i,g,m){let A=O.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===i);if(!A?.approval)throw new Error(`Approval not found: ${i}`);if(A.approval.toolType==="webmcp"){O.resolveWebMcpApproval(A.id,g);return}return O.resolveApproval(A.approval,g,m)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){R(i)},on(i,g){return p.on(i,g)},off(i,g){p.off(i,g)},isOpen(){return $()&&X},isVoiceActive(){return Ge.active},toggleReadAloud(i){O.toggleReadAloud(i)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(i){return O.getReadAloudState(i)},onReadAloudChange(i){return O.onReadAloudChange(i)},getState(){return{open:$()&&X,launcherEnabled:M,voiceActive:Ge.active,streaming:O.isStreaming()}},showCSATFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=Vu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitCSATFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!X&&$()&&dt(!0,"system");let g=Pe.querySelector(".persona-feedback-container");g&&g.remove();let m=qu({onSubmit:async(b,A)=>{O.isClientTokenMode()&&await O.submitNPSFeedback(b,A),i?.onSubmit?.(b,A)},onDismiss:i?.onDismiss,...i});Pe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return O.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return O.submitNPSFeedback(i,g)},destroy(){Ii(),To!=null&&(clearInterval(To),To=null),ze.forEach(i=>i()),He.remove(),et?.remove(),Ft?.destroy(),Kt?.remove(),vo&&T.removeEventListener("click",vo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Mt,getMessages:Mt.getMessages,getStatus:Mt.getStatus,getMetadata:Mt.getPersistentMetadata,updateMetadata:Mt.updatePersistentMetadata,clearHistory:()=>Mt.clearChat(),setVoiceActive:m=>m?Mt.startVoiceRecognition():Mt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ze.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.focusInput()};if(window.addEventListener("persona:focusInput",g),ze.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let N=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.showEventStream()},K=ae=>{let ge=ae.detail;(!ge?.instanceId||ge.instanceId===i)&&Mt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",K),ze.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",K)})}let m=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.showArtifacts()},b=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.hideArtifacts()},A=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||K?.artifact&&Mt.upsertArtifact(K.artifact)},k=N=>{let K=N.detail;K?.instanceId&&K.instanceId!==i||typeof K?.id=="string"&&Mt.selectArtifact(K.id)},Q=N=>{let K=N.detail;(!K?.instanceId||K.instanceId===i)&&Mt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",Q),ze.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",Q)})}let dn=lb(o.persistState);if(dn&&$()){let i=cb(dn.storage),g=`${dn.keyPrefix}widget-open`,m=`${dn.keyPrefix}widget-voice`,b=`${dn.keyPrefix}widget-voice-mode`;if(i){let A=dn.persist?.openState&&i.getItem(g)==="true",k=dn.persist?.voiceState&&i.getItem(m)==="true",Q=dn.persist?.voiceState&&i.getItem(b)==="true";if(A&&setTimeout(()=>{Mt.open(),setTimeout(()=>{if(k||Q)Mt.startVoiceRecognition();else if(dn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),dn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(g,"true")}),p.on("widget:closed",()=>{i.setItem(g,"false")})),dn.persist?.voiceState&&(p.on("voice:state",N=>{i.setItem(m,N.active?"true":"false")}),p.on("user:message",N=>{i.setItem(b,N.viaVoice?"true":"false")})),dn.clearOnChatClear){let N=()=>{i.removeItem(g),i.removeItem(m),i.removeItem(b)},K=()=>N();window.addEventListener("persona:clear-chat",K),ze.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(f&&$()&&setTimeout(()=>{Mt.open()},0),qo(),!hf){let i=la(()=>{O&&(vi++,wo.clear(),Dr(Pe,O.getMessages(),Z))});ze.push(i)}return Mt};var Ju=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},ub=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},fb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},gb=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Yu=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Ql=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Zu=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ql(e)},ql=e=>{e.style.transition=""},Kl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Gl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ci=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},mb=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},hb=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},yb=e=>{let t=dr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(t,r)??r;return{inset:o(n?.inset,La),canvasBackground:o(n?.canvasBackground,Pa)}},ef=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},bb=(e,t,n,o,r,s,a,l)=>{let p=gn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";mb(e,t,n,o,d),hb(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,R=f!=null?f.innerWidth<=C:!1;if(v&&R&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Kl(t),ql(o),Zu(o),Gl(n),ci(r,o),ef(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Zu(o),ub(o,p.maxHeight),ef(o,c&&a,u,w),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Kl(t),ql(o),Gl(n),ci(r,o);let L=p.animate?"transform 180ms ease":"none",E=p.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":E;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=L,o.style.transform=M,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ql(o),Ql(o),ci(r,o);let L=Ju(p.width,e.clientWidth),E=Math.max(0,e.clientWidth),M=p.animate?"margin-left 180ms ease":"none",_=p.side==="right"?a?-L:0:a?0:-L;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${E+L}px`,t.style.transition=M,t.style.marginLeft=`${_}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Kl(t),Ql(o),Gl(n),ci(r,o);let L=p.reveal==="emerge";L?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?p.width:"0px",M=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",_=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",fb(o,p.maxHeight),o.style.overflow=L||_?"hidden":"visible",o.style.transition=M,L){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=c?`calc(${Ju(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},vb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Yu(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Yu(n,o)},destroy(){n.remove()}}},wb=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let w=null,f=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?yb(t):null};C();let R=()=>{bb(a,l,p,d,c,t,u,v)},B=null,L=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=Ia(()=>{C(),R()}))},E=()=>{f(),gn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{R()}),w.observe(a)))},M=!1,_=()=>{R(),E(),u&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,gb(a,gn(t)))},G=a.ownerDocument.defaultView,x=()=>{_()};return G?.addEventListener("resize",x),gn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),_(),L(),{mode:"docked",host:c,shell:a,syncWidgetState(j){let U=j.launcherEnabled?j.open:!0;u!==U&&(u=U,_())},updateConfig(j){t=j,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),_(),L()},destroy(){G?.removeEventListener("resize",x),B?.(),B=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},tf=(e,t)=>Dt(t)?wb(e,t):vb(e,t);var ks={desktop:{w:1280,h:800},mobile:{w:390,h:844}},nf=.15,of=1.5,Xl="persona-preview-shell-theme",xb={load:()=>null,save:()=>{},clear:()=>{}},Cb=["How do I get started?","Pricing & plans","Talk to support"];function Jl(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ab(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function rf(e){let t=Ab(e);return`* { box-sizing: border-box; }
|
|
139
|
+
${wt?"background: transparent !important;":""}
|
|
140
|
+
`}if(!y&&!i){let Mt="max-height: -moz-available !important; max-height: stretch !important;",tn=p?"":"padding-top: 1.25em !important;",Pa=p?"":`z-index: ${o.launcher?.zIndex??Nt} !important;`;Le.style.cssText+=Mt+tn+Pa}hn()},Xi=()=>{e.style.setProperty("--persona-content-max-width",xo(o,Q()))},md=()=>{if(Q())return;let i=Rt(o),p=o.launcher?.sidebarMode??!1;if(i||p||(o.launcher?.fullHeight??!1)||!F)return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E)return;let U=y.innerHeight,O=64,V=o.launcher?.heightOffset??0,J=Math.max(200,U-O),fe=Math.min(640,J);ye.style.height=`${Math.max(200,fe-V)}px`};Yi(),Ds(e,o),ea(e,o),ta(e,o),Xi(),Lo=()=>{Yi(),md(),Ds(e,o),ea(e,o),ta(e,o),Xi(),aa?e.style.setProperty("--persona-artifact-welded-outer-radius",aa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Be=[];Be.push(()=>{document.removeEventListener("keydown",ud)}),Be.push(()=>{Qr!==null&&clearTimeout(Qr)});let Wn=null,Rn=null;Be.push(()=>{Wn?.(),Wn=null,Rn?.(),Rn=null}),es&&Be.push(()=>{es?.disconnect(),es=null}),Be.push(()=>{os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),me&&Be.push(()=>{ze!==null&&(cancelAnimationFrame(ze),ze=null),Ae?.destroy(),Ae=null,Oe?.destroy(),Oe=null,Ue=null});let Io=null,hd=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=oi(()=>{Ds(e,o)}))};hd(),Be.push(()=>{Io&&(Io(),Io=null)}),Be.push(d);let fa=o.features?.streamAnimation;if(fa?.type&&fa.type!=="none"){let i=Or(fa.type,fa.plugins);i&&(bi(i,e),Be.push(()=>yf(e)))}let _n=qs(M),yd=qs(An),bd=qs(ne),Wo=[_n,yd,bd];Be.push(()=>{Wo.forEach(i=>i.destroy())});let Ro=null,_,Ho=null,vd=!1,wd=0,xd=null,Cd=i=>i.reduce((p,m)=>m.role==="user"?p+1:p,0),Ad=i=>{for(let p=i.length-1;p>=0;p--)if(Ss(i[p]))return i[p].id??null;return null},Sd=!1,jg=()=>{Sd||o.debug!==!0||(Sd=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Td=!1,Md=!1,Ed=(i,p)=>{Td||o.debug!==!0||!p.enabled||p.expose||vd||Md&&(_.isStreaming()||i.some(Ss)||(Td=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},lr=i=>{if(!_)return;let p=i??_.getMessages(),m=J=>{J.render([],_,I,p)},y=J=>{Wo.forEach(fe=>{fe!==J&&m(fe)})};Ho&&(Cd(p)>wd||Ad(p)!==xd)&&(Ho=null);let x=vo(o);Ed(p,x);let E=x.enabled?au(p):null,U=Ho??E,O=Ho?"host":"agent";if(U){let J=o.suggestions?.followUps,fe=J?.placement??(J?"auto":"composer"),be=(fe==="auto"?Q()?"composer":"after-message":fe)==="after-message"?bd:_n;y(be),be.render(U,_,I,p,o.suggestionChipsConfig,{source:O,surface:"followUp",variant:J?.variant??"chip",behavior:J?.behavior??"send",overflow:J?.overflow??"wrap",maxItems:J?.maxItems??4,config:o,plugins:s});return}if(p.some(J=>J.role==="user")){Wo.forEach(m);return}let V=o.suggestions?.starters;if(V){let J=_r(Zo(o),p),fe=V.placement??"auto",le=fe==="auto"?J?"welcome":"composer":fe;if(le==="welcome"&&!J){jg(),Wo.forEach(m);return}let be=le==="welcome"?yd:_n;y(be),be.render(V.items??o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:o,plugins:s});return}y(_n),_n.render(o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},kd=()=>{Ho&&(Ho=null,lr())},Vg=i=>{let p=Array.isArray(i)?[...i]:[];if(!p.length){kd();return}let m=_?_.getMessages():[];Ho=p,vd=!0,wd=Cd(m),xd=Ad(m),lr(m)},En=!1,Bo=lf(),cr=new Map,Do=new Map,ro=new Map,Qi=0,qg=Gn()!==null,on=ui(),rn=0,so=null,Zt=!1,ga=!1,ao=0,Bt=null,Fo=null,Ji=!1,ma=!1,Oo=null,rs=!0,ha=!1,dr=null,ya=!1,No=()=>{ya=!0,Xg()},Zi=null,Kg=4,$n=24,Gg=80,Yg=1e3,Un=null,Ld=()=>{e.setAttribute("data-persona-scrollbar",Ni()),Ni()!=="on-scroll"&&(Un!==null&&clearTimeout(Un),Un=null,re.removeAttribute("data-persona-scrollbar-visible"))},Xg=()=>{Ni()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Un!==null&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,eo(re,$n)&&re.removeAttribute("data-persona-scrollbar-visible")},Yg))};Ld(),Be.push(()=>{Un!==null&&clearTimeout(Un)});let el=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Pd=o.voiceRecognition?.autoResume??!1,zn=i=>{c.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},kn=()=>{S(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Qg=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Nc(g.voiceState),p=!!i.active,m=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,p&&Date.now()-m<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("restore"),_.isVoiceActive()&&hr()}):Ma("restore"))},1e3)},Jg=()=>_?xg(_.getMessages()).filter(i=>!i.__skipPersist):[],ba=null,Id=(i,p)=>{typeof console<"u"&&console.error(i,p)},tl=(i,p)=>{let m=()=>{try{let U=i();return!U||typeof U.then!="function"?null:Promise.resolve(U).catch(O=>{Id(p,O)})}catch(U){return Id(p,U),null}},y=ba,x=y?y.then(()=>m()??void 0):m();if(!x)return;let E=x.finally(()=>{ba===E&&(ba=null)});ba=E};function nl(i){if(!w?.save)return;let m={messages:i?xg(i):_?Jg():[],metadata:g,artifacts:Tn.artifacts,selectedArtifactId:Tn.selectedId};tl(()=>w.save(m),"[AgentWidget] Failed to persist state:")}let pr=null,Wd=()=>Le.querySelector("#persona-scroll-container")||re,ur=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Zt=!1},Rd=()=>{so!==null&&(cancelAnimationFrame(so),so=null),ga=!1,ur()},Zg=()=>En&&rl()&&(nn()!=="anchor-top"||Kc()),ol=()=>{let i=Gr()||"Jump to latest",p=Zg();Et.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),ao>0?(Mo.textContent=String(ao),Mo.style.display="",Et.setAttribute("aria-label",`${i} (${ao} new)`)):(Mo.textContent="",Mo.style.display="none",Et.setAttribute("aria-label",p?`${i} (response streaming below)`:i))},Hd=()=>{ao!==0&&(ao=0,ol())},em=()=>{let i=Bt?.spacerHeight??0;return i<=0?eo(re,$n):xa(i)-re.scrollTop-re.clientHeight<=$n},rl=()=>no()?!on.isFollowing():!em(),sl=()=>!!_&&_.getMessages().length>0,$t=()=>{if(!Og()||Se){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==ve&&ve.appendChild(Et),ko();let p=Dn(re)>0&&rl()&&sl();p?ol():Hd(),Et.style.display=p?"":"none"},ss=()=>{on.pause()&&(Rd(),$t())},io=()=>{on.resume(),Hd(),$t()},lo=(i=!1)=>{no()&&sl()&&on.isFollowing()&&(!i&&!En||(so!==null&&(cancelAnimationFrame(so),so=null),ga=!0,so=requestAnimationFrame(()=>{so=null,ga=!1,on.isFollowing()&&tm(Wd(),i?220:140)})))},Bd=(i,p,m,y=()=>!0)=>{let x=i.scrollTop,E=p(),U=E-x;if(ur(),Math.abs(U)<1){Zt=!0,i.scrollTop=E,rn=i.scrollTop,Zt=!1;return}let O=performance.now();Zt=!0;let V=fe=>1-Math.pow(1-fe,3),J=fe=>{if(!y()){ur();return}let le=p();le!==E&&(E=le,U=E-x);let be=fe-O,Ge=Math.min(be/m,1),mt=V(Ge),ct=x+U*mt;i.scrollTop=ct,rn=i.scrollTop,Ge<1?pr=requestAnimationFrame(J):(i.scrollTop=E,rn=i.scrollTop,pr=null,Zt=!1)};pr=requestAnimationFrame(J)},tm=(i,p=500)=>{let m=Dn(i)-i.scrollTop;if(Math.abs(m)<1){rn=i.scrollTop;return}if(Math.abs(m)>=Gg){ur(),Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1;return}Bd(i,()=>Dn(i),p,()=>on.isFollowing())},Dd=()=>{if(!sl()){$t();return}let i=Wd();Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1,$t()},_o=i=>{let p=0,m=i;for(;m&&m!==re;)p+=m.offsetTop,m=m.offsetParent;return p},nm=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},va=()=>ff(nm(),re),Fd=()=>{if(Ng()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let p=[...i].reverse().find(E=>E.role==="user");if(!p)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=re.querySelector(`[data-message-id="${m}"]`);if(!y)return!1;let x=Math.min(Math.max(0,_o(y)-Yr()),Dn(re));return Zt=!0,re.scrollTop=x,rn=re.scrollTop,Zt=!1,nn()==="follow"&&!eo(re,$n)&&on.pause(),$t(),!0},wa=i=>{let p=Math.max(0,Math.round(i));fn.style.height=`${p}px`,fn.style.display=p>0?"":"none",Bt&&(Bt.spacerHeight=Math.max(0,i))},xa=i=>{let p=parseFloat(getComputedStyle(re).paddingBottom)||0,m=0;for(let x of Array.from(re.children)){if(x===fn||x.offsetHeight===0)continue;let E=_o(x)+x.offsetHeight;E>m&&(m=E)}let y=re.scrollHeight-i;return m>0?Math.min(m+p,y):y},om=()=>{if(!Bt||Bt.spacerHeight<=0)return;let i=xa(Bt.spacerHeight),p=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+$n);p<Bt.spacerHeight&&(wa(p),$t())},as=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),ur(),Bt=null,fn.style.height="0px",fn.style.display="none"},Od=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),al=i=>re.querySelector(`[data-message-id="${Od(i)}"]`),Nd=i=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{Fo=null;let p=Od(i),m=re.querySelector(`[data-message-id="${p}"]`);if(!m)return;let y=_o(m),x=Bt?.spacerHeight??0,E=xa(x),{targetScrollTop:U,spacerHeight:O}=sc({anchorOffsetTop:y,topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:E,slack:$n});Bt={initialSpacerHeight:O,contentHeightAtAnchor:E,spacerHeight:O},wa(O),Bd(re,()=>m.isConnected?Math.max(0,_o(m)-Yr()):U,220)})},_d=()=>{if(nn()!=="anchor-top"||!Bt||!dr)return;let i=al(dr);if(!i)return;ur();let p=Bt.spacerHeight,m=xa(p),{targetScrollTop:y,spacerHeight:x}=sc({anchorOffsetTop:_o(i),topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:m,slack:$n});Bt={initialSpacerHeight:x,contentHeightAtAnchor:m,spacerHeight:x},wa(x),Zt=!0,re.scrollTop=y,rn=re.scrollTop,Zt=!1,$t()},rm=()=>{if(no()){if(!on.isFollowing()||eo(re,1))return;lo(!En);return}if(Bt&&Bt.initialSpacerHeight>0){let i=re.scrollHeight-Bt.spacerHeight,p=gf({initialSpacerHeight:Bt.initialSpacerHeight,contentHeightAtAnchor:Bt.contentHeightAtAnchor,currentContentHeight:i});p!==Bt.spacerHeight&&wa(p)}$t()},sm=i=>{let p=nn();p==="follow"?(io(),lo(!0)):p==="anchor-top"&&(rs=!1,ha=!0,ya=!1,dr=i,Nd(i))},am=()=>{if(nn()==="anchor-top"){if(ha){rs=!1;return}rs=!0,as(),io(),lo(!0)}},im=96,lm=i=>{if(Oo===null)return!0;let p=al(Oo),m=al(i);if(!p||!m)return!0;let y=_o(m)-_o(p);return Yr()+y>re.clientHeight-im},cm=i=>{if(nn()!=="anchor-top"||!ha||ya||va())return;let p=Oo===null;for(let m of i){if(!p){m.id===Oo&&(p=!0);continue}if(uf(m)){if(m.id===dr||!lm(m.id))return;dr=m.id,Nd(m.id);return}}},dm=i=>{let p=new Map;i.forEach(m=>{let y=el.get(m.id);p.set(m.id,{streaming:m.streaming,role:m.role}),!y&&m.role==="assistant"&&(c.emit("assistant:message",m),!ma&&(nn()!=="anchor-top"||Kc())&&rl()&&(ao+=1,ol(),$t(),Yc(ao===1?"1 new message below.":`${ao} new messages below.`))),m.role==="assistant"&&y?.streaming&&m.streaming===!1&&c.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(y?m.approval.status!=="pending"&&c.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):c.emit("approval:requested",{approval:m.approval,message:m}))}),el.clear(),p.forEach((m,y)=>{el.set(y,m)})},Ca=(i,p)=>{let m=p==="user"?"user":"assistant",y=o.layout?.messages?.[m],x=y?.width??"content",E=y?.maxWidth??(x==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${p}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",p==="user"),i.setAttribute("data-message-role",p),i.setAttribute("data-message-width",x),i.style.setProperty("--persona-message-row-max-width",E)},$o=(i,p)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Ca(m,p),m},pm=(i,p,m)=>{let y=document.createElement("div"),E=(()=>{let D=s.find(Ie=>Ie.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),U=(D,Ie)=>Ie==null?!1:typeof Ie=="string"?(D.textContent=Ie,!0):(D.appendChild(Ie),!0),O=new Set,V=new Map,J=new Set,fe=s.some(D=>D.renderAskUserQuestion),le=[],be=[],Ge=o.enableComponentStreaming!==!1,mt=o.approval!==!1,ct=[];if(p.forEach(D=>{O.add(D.id),V.set(D.id,D.role);let Ie=fe&&qo(D),De=mt&&D.variant==="approval"&&!!D.approval,Me=!Ie&&D.role==="assistant"&&!D.variant&&Ge&&Oc(D);!De&&ro.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id)),!Me&&Do.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Do.delete(D.id));let Ct=qo(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=af(D,Qi)+Ct,Ft=Ie||De||Me?null:cf(Bo,D.id,dt);if(Ft){y.appendChild(Ft.cloneNode(!0)),qo(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let pt=null,en=s.find(Fe=>!!(D.variant==="reasoning"&&Fe.renderReasoning||D.variant==="tool"&&Fe.renderToolCall||!D.variant&&Fe.renderMessage)),Pt=o.layout?.messages;if(qo(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){cr.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ss(D)&&vo(o).enabled)return;if(qo(D)&&o.features?.askUserQuestion?.enabled!==!1){let Fe=s.find(Ut=>typeof Ut.renderAskUserQuestion=="function");if(Fe&&st.current){let Ut=cr.get(D.id),zt=Ut!==dt,wt=null;if(zt){let{payload:Xe,complete:He}=Tr(D),ht=D.id,jt=()=>st.current?.getMessages().find(hn=>hn.id===ht);wt=Fe.renderAskUserQuestion({message:D,payload:Xe,complete:He,resolve:hn=>{let ys=jt();ys&&st.current?.resolveAskUserQuestion(ys,hn)},dismiss:()=>{let hn=jt();hn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(hn),st.current?.resolveAskUserQuestion(hn,"(dismissed)"))},config:o})}let at=Ut!=null;if(zt&&wt===null&&!at){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let ut=$o(D.id,D.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),le.push({messageId:D.id,fingerprint:dt,bubble:wt});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}}else if(De){let Fe=s.find(at=>typeof at.renderApproval=="function")??u,zt=ro.get(D.id)!==dt,wt=null;if(zt&&Fe?.renderApproval){let at=D.id,ut=(Xe,He)=>{let ht=st.current?.getMessages().find(jt=>jt.id===at);ht?.approval&&(ht.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(ht.id,Xe):st.current?.resolveApproval(ht.approval,Xe,He))};wt=Fe.renderApproval({message:D,defaultRenderer:()=>Ri(D,o),config:o,approve:Xe=>ut("approved",Xe),deny:Xe=>ut("denied",Xe)})}if(zt&&wt===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id),pt=Ri(D,o);else{let at=$o(D.id,D.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),y.appendChild(at),ct.push({messageId:D.id,fingerprint:dt,bubble:wt});return}}else if(en)if(D.variant==="reasoning"&&D.reasoning&&en.renderReasoning){if(!pe)return;pt=en.renderReasoning({message:D,defaultRenderer:()=>xc(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&en.renderToolCall){if(!ee)return;pt=en.renderToolCall({message:D,defaultRenderer:()=>Ac(D,o),config:o})}else en.renderMessage&&(pt=en.renderMessage({message:D,defaultRenderer:()=>{let Fe=hc(D,m,Pt,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o});return D.role!=="user"&&Wc(Fe,D,o,_),Fe},config:o}));if(!pt&&Me){let Fe=bg(D);if(Fe){let Ut=Do.get(D.id),zt=Ut!==dt,wt=o.wrapComponentDirectiveInBubble!==!1&&Zn.getOptions(Fe.component)?.bubbleChrome!==!1,at=null;if(zt){let ut=hg(Fe,{config:o,message:D,transform:m});if(ut&&Fe.component==="PersonaArtifactInline"){let Xe=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Xe&&jt&&jt!==Xe&&tf(jt)&&(Xe===ut?ut=jt:Xe.replaceWith(jt))}if(ut)if(wt){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),Xe.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}}if(at||Ut!=null){let ut=$o(D.id,D.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),be.push({messageId:D.id,fingerprint:dt,bubble:at});return}}}if(!pt)if(D.variant==="reasoning"&&D.reasoning){if(!pe)return;pt=xc(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!ee)return;pt=Ac(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;pt=Ri(D,o)}else{let Fe=o.layout?.messages;Fe?.renderUserMessage&&D.role==="user"?pt=Fe.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):Fe?.renderAssistantMessage&&D.role==="assistant"?pt=Fe.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):pt=hc(D,m,Fe,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o}),D.role!=="user"&&pt&&Wc(pt,D,o,_)}let We=$o(D.id,D.role);We.appendChild(pt),df(Bo,D.id,dt,We),y.appendChild(We)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let De=Ie.getAttribute("data-persona-ask-sheet-for");De&&!J.has(De)&&Er(Te.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let D=[],Ie=[],De=o.features.toolCallDisplay.groupedMode==="summary";p.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&ee){Ie.push(Me);return}Me.variant==="reasoning"&&!pe||((Ie.length>1||De&&Ie.length>0)&&D.push(Ie),Ie=[])}),(Ie.length>1||De&&Ie.length>0)&&D.push(Ie),D.forEach(Me=>{let Ct=Me.map(Fe=>Array.from(y.children).find(Ut=>Ut instanceof HTMLElement&&Ut.getAttribute("data-wrapper-id")===Fe.id)).filter(Fe=>!!Fe);if(Ct.length<(De?1:2))return;let dt=$o(`tool-group-${Me[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Me[0].id}`;let en=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Pt=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map(Fe=>Fe.toolCall).filter(Fe=>!!Fe),defaultSummary:en,config:o});U(pt,Pt)||(pt.textContent=en);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Me[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(pt),De||Ft.appendChild(We),dt.appendChild(Ft),Ct[0].before(dt),Ct.forEach((Fe,Ut)=>{if(De){Fe.remove();return}Fe.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),Ut<Ct.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(Fe),We.appendChild(zt)})})}pf(Bo,O);let sn=p.some(D=>D.role==="assistant"&&D.streaming),At=p[p.length-1],Lt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(En&&p.some(D=>D.role==="user")&&!sn&&!Lt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Ie=s.find(Me=>Me.renderLoadingIndicator),De=null;if(Ie?.renderLoadingIndicator&&(De=Ie.renderLoadingIndicator(D)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(D)),De===null&&(De=Ys()),De){let Me=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Me.className=Ct?Xs("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Me.setAttribute("data-typing-indicator","true"),Ct&&(Me.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Me.appendChild(De);let Ft=$o("typing-indicator","assistant");Ft.appendChild(Me),y.appendChild(Ft)}}if(!En&&p.length>0){let D=p[p.length-1],Ie={config:o,lastMessage:D,messageCount:p.length},De=s.find(Ct=>Ct.renderIdleIndicator),Me=null;if(De?.renderIdleIndicator&&(Me=De.renderIdleIndicator(Ie)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(Ie)),Me){let Ct=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;Ct.className=dt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Me);let Ft=$o("idle-indicator","assistant");Ft.appendChild(Ct),y.appendChild(Ft)}}if(Np(y),pi(i,y),Il(i),le.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of le){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),cr.set(D,Ie)))}if(cr.size>0)for(let D of cr.keys())O.has(D)||cr.delete(D);if(be.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of be){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),Do.set(D,Ie)))}if(Do.size>0)for(let D of Do.keys())O.has(D)||Do.delete(D);if(ct.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of ct){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),ro.set(D,Ie)))}if(ro.size>0)for(let D of ro.keys())O.has(D)||ro.delete(D)},is=(i,p,m)=>{pm(i,p,m),cd()},ls=null,um=()=>{if(ls)return;let i=m=>{let y=m.composedPath();y.includes(Le)||tt&&y.includes(tt)||lt(!1,"user")};ls=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},$d=()=>{if(!ls)return;(e.ownerDocument??document).removeEventListener("pointerdown",ls,!0),ls=null};Be.push(()=>$d());let cs=null,fm=()=>{if(cs)return;let i=m=>{m.key==="Escape"&&(m.isComposing||lt(!1,"user"))};cs=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Ud=()=>{if(!cs)return;(e.ownerDocument??document).removeEventListener("keydown",cs,!0),cs=null};Be.push(()=>Ud());let ds=!1,zd=new Set,gm=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},fr=()=>{if(!Q())return;let i=Te.peekBanner,p=Te.peekTextNode;if(!i||!p)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],y;for(let At=m.length-1;At>=0;At--){let Lt=m[At];if(Lt.role==="assistant"&&Lt.content){y=Lt;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,E=!!y.streaming,U=gm(),O=mi(U),V=O.type!=="none"?Or(O.type,U?.plugins):null,J=V?.isAnimating?.(y)===!0,fe=V!==null&&(E||J);fe&&V&&!zd.has(V.name)&&(bi(V,e),zd.add(V.name));let le=fe&&V?.containerClass?V.containerClass:null,be=p.dataset.personaPeekStreamClass??null;be&&be!==le&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),le&&be!==le&&(p.classList.add(le),p.dataset.personaPeekStreamClass=le),fe?(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 Ge=fe?hi(x,O.buffer,V,y,E):x;if(fe&&O.placeholder==="skeleton"&&E&&(!Ge||!Ge.trim())){let At=document.createElement("div"),Lt=Us();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),pi(p,At)}else{let At=Math.max(0,Ge.length-100),Lt=Ge.length>100?Ge.slice(-100):Ge,D=mo(Lt);if(!fe||!V){let Ie=Ge.length>100?`\u2026${Lt}`:Lt;p.textContent!==Ie&&(p.textContent=Ie)}else{let Ie=D;(V.wrap==="char"||V.wrap==="word")&&(Ie=$s(D,V.wrap,`peek-${y.id}`,{skipTags:V.skipTags,startIndex:At}));let De=document.createElement("div");if(De.innerHTML=Ie,V.useCaret&&Lt.length>0){let Me=yi(),Ct=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Ct[Ct.length-1];dt?.parentNode?dt.parentNode.insertBefore(Me,dt.nextSibling):De.appendChild(Me)}pi(p,De),V.onAfterRender?.({container:p,bubble:i,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let sn=En||ds;i.classList.toggle("persona-pill-peek--visible",sn)};if(Q()){let i=Te.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",y),Be.push(()=>{i.removeEventListener("pointerdown",y)})}let p=()=>{ds||(ds=!0,fr())},m=()=>{ds&&(ds=!1,fr())};ye.addEventListener("pointerenter",p),ye.addEventListener("pointerleave",m),Be.push(()=>{ye.removeEventListener("pointerenter",p),ye.removeEventListener("pointerleave",m)}),tt&&(tt.addEventListener("pointerenter",p),tt.addEventListener("pointerleave",m),Be.push(()=>{tt.removeEventListener("pointerenter",p),tt.removeEventListener("pointerleave",m)}))}let mm=i=>{let p=o.launcher?.composerBar??{},m=p.expandedSize??"anchored",y=p.bottomOffset??"16px",x=p.collapsedMaxWidth,E=p.expandedMaxWidth??"880px",U=p.expandedTopOffset??"5vh",O=p.modalMaxWidth??"880px",V=p.modalMaxHeight??"min(90vh, 800px)",J="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let be=tt.style;be.bottom=y,be.width=x??""}if(i&&m!=="fullscreen"){if(m==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=O,le.maxWidth=J,le.maxHeight=V,le.height=V;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${y} + ${fe})`,le.top=U,le.width=E,le.maxWidth=J}},ps=()=>{if(!ie())return;if(Q()){let J=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Y?"expanded":"collapsed";Le.dataset.state=fe,Le.dataset.expandedSize=J,tt&&(tt.dataset.state=fe,tt.dataset.expandedSize=J),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),mm(Y),ve.style.display=Y?"flex":"none",Lo(),Y?(um(),fm()):($d(),Ud()),fr();return}let i=Rt(o),p=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=p.innerWidth<=m,E=y&&x&&F,U=vn(o).reveal;Y?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),Tt?(Tt.setPanelOpen(!0),Tt.element.style.display="none"):Xt&&(Xt.style.display="none")):(i?i&&(U==="overlay"||U==="push")&&!E?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),Tt?(Tt.setPanelOpen(!1),Tt.element.style.display=i?"none":""):Xt&&(Xt.style.display=i?"none":""))},lt=(i,p="user")=>{if(!ie()||Y===i)return;let m=Y;Y=i,ps();let y=(()=>{let E=o.launcher?.sidebarMode??!1,U=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640,J=U.innerWidth<=V,fe=Rt(o)&&O&&J,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||O&&J&&F||fe||le})();if(Y&&y){if(!Wn){let E=e.getRootNode(),U=E instanceof ShadowRoot?E.host:e.closest(".persona-host");U&&(Wn=lc(U,o.launcher?.zIndex??Nt))}Rn||(Rn=cc(e.ownerDocument))}else Y||(Wn?.(),Wn=null,Rn?.(),Rn=null);Y&&(ms(),Fd()||(nn()==="follow"?lo(!0):Dd()));let x={open:Y,source:p,timestamp:Date.now()};Y&&!m?c.emit("widget:opened",x):!Y&&m&&c.emit("widget:closed",x),c.emit("widget:state",{open:Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()})},Aa=i=>{ra(i?"stop":"send"),oe&&(oe.disabled=i),Wo.forEach(p=>{p.elements.forEach(m=>{m.toggleAttribute("data-disabled",i),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",i?"true":"false")}),p.buttons.forEach(m=>{m.disabled=i})}),pl.forEach(p=>{p.toggleAttribute("data-disabled",i),p instanceof HTMLButtonElement?p.disabled=i:p.setAttribute("aria-disabled",i?"true":"false"),p.querySelectorAll("button").forEach(m=>{m.disabled=i})}),Ce.dataset.personaComposerStreaming=i?"true":"false",Ce.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=i)})},il=()=>{Ke.active||I&&I.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>il(),200)});let ll=!q.hidden,co=null,jd=!v,Vd=null,qd,Kd=null,us=null,cl=i=>{let p=Zo(o),m=`${p.variant}|${p.dismiss}|${p.title}|${p.subtitle}`;(m!==Vd||p.icon!==qd)&&(Vd=m,qd=p.icon,Pi({host:q,iconHolder:$,title:ce,subtitle:je,starterSuggestions:An},p));let y=p.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${p.message}`;y!==Kd&&(Kd=y,Ii(K,p.message,o));let x=i??(_?_.getMessages():o.initialMessages),E=_r(p,x),U=E!==ll;if(ll=E,us){co?.cancel(),co=null,Nr(re,q,!0);return}if(U&&!E&&p.dismiss==="on-first-message"&&jd){co=Pf(q,O=>{co===O&&(co=null),!ll&&!us&&(Nr(re,q,!1),_d()),O?.cancel()});return}if(co){if(!E)return;co.cancel(),co=null}Nr(re,q,E),U&&!E&&_d()},dl=[],pl=[],ul=!1,Gd=null,Yd,Xd=()=>{pl.length=0;let i=dl.splice(0,dl.length);for(let p of i)try{p()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Be.push(Xd);let hm=(i,p)=>{let m=pc(i,p);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),b("span");let y=o.suggestions?.starters,x=uc({item:{...m,behavior:m.behavior??y?.behavior??"send"},index:p,surface:"starter",source:"config",variant:y?.variant??"card",streaming:a?_.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>I,eventTarget:q});return pl.push(x),x},fl=()=>{if(ul)return;ul=!0;let i=Zo(o);Gd=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Yd=i.icon;try{Xd(),kf(re,q,us),us=null;let p=_?_.getMessages():o.initialMessages,m=_r(i,p),y=0,x=null;for(let E of s)if(E.renderWelcome&&(x=E.renderWelcome({config:i,variant:i.variant,visible:m,defaultRenderer:()=>q,sendMessage:U=>{if(!_||_.isStreaming())return;let O=U.trim();O&&_.sendMessage(O)},requestRender:()=>fl(),renderStarter:U=>hm(U,y++),storage:l(E.id),onCleanup:U=>{dl.push(U)}}),x))break;x&&x!==q&&(us=x,Ef(re,q,x))}finally{ul=!1}cl()},ym=()=>{let i=Zo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Gd&&i.icon===Yd||fl()},gl=()=>{cl(),zi||(I.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),I.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',I.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=g.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(p=>({...p,sessionId:i}))}});let Uo=null,bm=()=>{Uo==null&&(Uo=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let p=Date.now();i.forEach(m=>{let y=Number(m.getAttribute("data-tool-elapsed"));y&&(m.textContent=za(p-y))})},100))},ml=(i,p)=>{if(Object.is(i,p))return!0;if(i===null||p===null||typeof i!="object"||typeof p!="object")return!1;if(Array.isArray(i)||Array.isArray(p))return!Array.isArray(i)||!Array.isArray(p)||i.length!==p.length?!1:i.every((U,O)=>ml(U,p[O]));let m=i,y=p,x=Object.keys(m),E=Object.keys(y);return x.length===E.length&&x.every(U=>Object.prototype.hasOwnProperty.call(y,U)&&ml(m[U],y[U]))},Qd=i=>{let{content:p,rawContent:m,llmContent:y,...x}=i;return x},hl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Oc(i),vm=(i,p,m)=>{if(i.length!==p.length)return!1;let y=i[m.index],x=p[m.index];return!y||!x||y.id!==m.id||x.id!==m.id?!1:(!Object.is(y.content,x.content)||!Object.is(y.rawContent,x.rawContent)||!Object.is(y.llmContent,x.llmContent))&&hl(y)&&hl(x)&&ml(Qd(y),Qd(x))},Jd=null,gr=null,zo=null,jn=null,Sa=i=>{Jd=i;let p,m;gr=null;for(let x=i.length-1;x>=0;x-=1){let E=i[x];if(!p&&E.role==="user"&&(p=E),!m&&E.role==="assistant"&&(m=E),!gr&&hl(E)&&(gr={index:x,id:E.id}),p&&m&&gr)break}is(xe,i,Z),tc(xe,Tn.artifacts,{suppressTransition:En}),bm(),cl(i),lr(i),lo(!En),dm(i),i.length===0&&(as(),rs=!0,ha=!1,dr=null,ya=!1),!Ji||ma?(Ji=!0,Oo=p?.id??null,Zi=m?.id??null):p&&p.id!==Oo?(Oo=p.id,sm(p.id)):m&&m.id!==Zi&&am(),m&&(Zi=m.id),cm(i);let y=Ke.lastUserMessageId;p&&p.id!==y&&(Ke.lastUserMessageId=p.id,c.emit("user:message",p)),Ke.lastUserMessageWasVoice=!!p?.viaVoice,nl(i),fr()},yl=()=>{jn!==null&&(cancelAnimationFrame(jn),jn=null);let i=zo;zo=null,i&&Sa(i)},Zd=()=>{jn!==null&&cancelAnimationFrame(jn),jn=null,zo=null},wm=i=>{let p=zo??Jd;if(En&&p&&gr&&vm(p,i,gr)){zo=i,jn===null&&(jn=requestAnimationFrame(()=>{jn=null;let m=zo;zo=null,m&&Sa(m)}));return}if(i.length===0){Zd(),Sa(i);return}yl(),Sa(i)};_=new Qa(o,{onMessagesChanged(i){wm(i)},onStatusChanged(i){let p=o.statusIndicator??{};Cn(R,(y=>y==="idle"?p.idleText??It.idle:y==="connecting"?p.connectingText??It.connecting:y==="connected"?p.connectedText??It.connected:y==="error"?p.errorText??It.error:y==="paused"?p.pausedText??It.paused:y==="resuming"?p.resumingText??It.resuming:It[y])(i),p,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?Zd():yl()),En=i,Aa(i),_&&is(xe,_.getMessages(),Z),i||(lo(!0),om(),Md=!0,_&&Ed(_.getMessages(),vo(o))),$t(),Yc(i?"Responding\u2026":"Response complete."),fr()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Vn(),hr();break;case"processing":Vn(),Im();break;case"speaking":Vn(),Wm();break;default:i==="idle"&&_.isBargeInActive()?(Vn(),hr(),oe?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Vn(),zn("system"),kn());break}},onArtifactsState(i){Tn=i,i.artifacts.length===0&&(sr=!1),tc(xe,i.artifacts,{suppressTransition:En}),Nn(),nl()},onReconnect(i){let{executionId:p,lastEventId:m}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:p,after:m}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:p,after:m,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:p,after:m})}}),st.current=_,Be.push(()=>_.cancel());let bl=null;if(_.onReadAloudChange((i,p)=>{id=i,ld=p,cd();let m=i??bl;i&&(bl=i);let y=m?_.getMessages().find(x=>x.id===m)??null:null;c.emit("message:read-aloud",{messageId:m,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(bl=null)}),a=!0,Ji=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&_.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Oe||o.onSSEEvent)&&_.setSSEEventCallback((i,p)=>{o.onSSEEvent?.(i,p),_e?.processEvent(i,p),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(p)})});let ep=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};v?v.then(i=>{if(i){if(i.metadata&&(g=Nc(i.metadata),H.syncFromMetadata()),i.messages?.length){ma=!0;try{_.hydrateMessages(i.messages)}finally{ma=!1}}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{jd=!0,ep()}):ep();let tp=()=>{!Q()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},xm=(i,p)=>i?p?{refs:[...i.refs,...p.refs],finalize:async()=>{let[m,y]=await Promise.allSettled([i.finalize(),p.finalize()]),x=[];return m.status==="fulfilled"?x.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),y.status==="fulfilled"?x.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),mw(x)}}:i:p,Cm=()=>{let p=I.getInlineMessageFields?.();return p&&p.contentSegments.some(y=>y.kind==="mention")?p.contentSegments:void 0},fs=!1,Am=async i=>{let p=I.value.trim(),m=yt?.hasAttachments()??!1,y=p?await(Yt?.takeInlineCommand(p)??Promise.resolve(null)):null;if(y?.kind==="action"){I.value="",I.style.height="auto",gs(),Yt?.clear();return}let x=Yt?.collectForSubmit()??null,E=y?.kind==="server"?y.mentions:null,U=xm(x,E),O=y?.kind==="prompt"?y.sendText:p,V=!!x&&x.refs.length>0;if(!O&&!m&&!V&&!E)return;tp();let J;m&&(J=[],J.push(...yt.getContentParts()),O&&J.push(Lr(O)));let fe=y?.kind==="prompt"?void 0:Cm();I.value="",I.style.height="auto",gs(),_.sendMessage(O,{contentParts:J,mentions:U??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),m&&yt.clearAttachments(),x&&Yt?.clear()},vl=async i=>{if(!fs){fs=!0;try{await Am(i)}finally{fs=!1}}},Ta=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),_e?.reset(),Ae?.update();return}fs||vl()},Sm=()=>o.features?.composerHistory!==!1,wl={...rc},xl=!1,gs=()=>{wl={...rc}},Tm=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Mm=i=>{if(!I)return;xl=!0,I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),xl=!1;let p=I.value.length;I.setSelectionRange(p,p)},Em=i=>{xl||(i.isComposing||Yt?.handleInput(i.inputType??void 0),gs())},km=i=>{if(I&&!(!i.isComposing&&Yt?.handleKeydown(i))){if(Sm()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let p=I.selectionStart===0&&I.selectionEnd===0,m=sf({direction:i.key==="ArrowUp"?"up":"down",history:Tm(),currentValue:I.value,atStart:p,state:wl});if(wl=m.state,m.handled){i.preventDefault(),m.value!==void 0&&Mm(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(fs){i.preventDefault();return}gs(),i.preventDefault(),h.click()}}},np=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(ve)&&(_.cancel(),_e?.reset(),Ae?.update(),gs(),i.preventDefault(),i.stopImmediatePropagation())},Lm=async i=>{if(o.attachments?.enabled!==!0||!yt)return;let p=pw(i.clipboardData);p.length!==0&&(i.preventDefault(),await yt.handleFiles(p))},gn=null,Hn=!1,mr=null,vt=null,op=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ma=(i="user")=>{if(Hn||_.isStreaming())return;let p=op();if(!p)return;gn=new p;let y=(o.voiceRecognition??{}).pauseDuration??2e3;gn.continuous=!0,gn.interimResults=!0,gn.lang="en-US";let x=I.value;gn.onresult=E=>{let U="",O="";for(let J=0;J<E.results.length;J++){let fe=E.results[J],le=fe[0].transcript;fe.isFinal?U+=le+" ":O=le}let V=x+U+O;I.value=V,mr&&clearTimeout(mr),(U||O)&&(mr=window.setTimeout(()=>{I.value.trim()&&gn&&Hn&&(po(),vl({viaVoice:!0}))},y))},gn.onerror=E=>{E.error!=="no-speech"&&po()},gn.onend=()=>{if(Hn){let E=I.value.trim();E&&E!==x.trim()&&vl({viaVoice:!0}),po()}};try{if(gn.start(),Hn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),zn(i),kn(),oe){let E=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let U=E.recordingBackgroundColor,O=E.recordingIconColor,V=E.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=U??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let J=oe.querySelector("svg");J&&J.setAttribute("stroke",O)}V&&(oe.style.borderColor=V),oe.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(i="user")=>{if(Hn){if(Hn=!1,mr&&(clearTimeout(mr),mr=null),gn){try{gn.stop()}catch{}gn=null}if(Ke.active=!1,zn(i),kn(),oe){if(oe.classList.remove("persona-voice-recording"),vt){oe.style.backgroundColor=vt.backgroundColor,oe.style.color=vt.color,oe.style.borderColor=vt.borderColor;let p=oe.querySelector("svg");p&&p.setAttribute("stroke",vt.color||"currentColor"),vt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Pm=(i,p)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),y=i?.provider?.type==="runtype",x=i?.provider?.type==="custom";if(!(m||y||x))return null;let U=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";let V=i?.tooltipText??"Start voice recognition";O.setAttribute("aria-label",V);let J=i?.iconName??"mic",fe=p?.size??"40px",le=i?.iconSize??fe,be=parseFloat(le)||24,Ge=i?.backgroundColor??p?.backgroundColor,mt=i?.iconColor??p?.textColor;O.style.width=le,O.style.height=le,O.style.minWidth=le,O.style.minHeight=le,O.style.fontSize="18px",O.style.lineHeight="1",mt?O.style.color=mt:O.style.color="var(--persona-text, #111827)";let sn=ae(J,be,mt||"currentColor",1.5);sn?O.appendChild(sn):O.textContent="\u{1F3A4}",Ge?O.style.backgroundColor=Ge: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),U.appendChild(O);let At=i?.showTooltip??!1;return _t({anchor:O,trigger:U,text:()=>O.getAttribute("aria-label")??V,enabled:At}),{micButton:O,micButtonWrapper:U}},Cl=()=>{if(!oe||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Al=(i,p)=>{if(!oe)return;let m=oe.querySelector("svg");m&&m.remove();let y=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),x=ae(i,y,p,1.5);x&&oe.appendChild(x)},Ea=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hr=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=i.recordingBackgroundColor,m=i.recordingIconColor,y=i.recordingBorderColor;if(Ea(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let x=oe.querySelector("svg");x&&x.setAttribute("stroke",m)}y&&(oe.style.borderColor=y),oe.setAttribute("aria-label","Stop voice recognition")},Im=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=i.processingIconName??"loader",y=i.processingIconColor??vt?.color??"",x=i.processingBackgroundColor??vt?.backgroundColor??"",E=i.processingBorderColor??vt?.borderColor??"";Ea(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=x,oe.style.borderColor=E;let U=y||"currentColor";oe.style.color=U,Al(m,U),oe.setAttribute("aria-label","Processing voice input"),p==="none"&&(oe.style.cursor="default")},Wm=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=i.speakingIconName??m,x=i.speakingIconColor??(p==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),E=i.speakingBackgroundColor??(p==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),U=i.speakingBorderColor??(p==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");Ea(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=E,oe.style.borderColor=U;let O=x||"currentColor";oe.style.color=O,Al(y,O);let V=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",V),p==="none"&&(oe.style.cursor="default"),p==="barge-in"&&oe.classList.add("persona-voice-recording")},Vn=()=>{oe&&(Ea(),vt&&(oe.style.backgroundColor=vt.backgroundColor??"",oe.style.color=vt.color??"",oe.style.borderColor=vt.borderColor??"",Al(vt.iconName,vt.color||"currentColor"),vt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},yr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),p=_.getVoiceInterruptionMode();if(p==="none"&&(i==="processing"||i==="speaking"))return;if(p==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()});return}_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),Ke.manuallyDeactivated=!_.isVoiceActive(),kn(),zn("user"),_.isVoiceActive()?hr():Vn()});return}if(Hn){let i=I.value.trim();Ke.manuallyDeactivated=!0,kn(),po("user"),i&&(I.value="",I.style.height="auto",_.sendMessage(i))}else Ke.manuallyDeactivated=!1,kn(),Ma("user")};Qc=yr,oe&&(oe.addEventListener("click",yr),Be.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Vn()):po("system"),oe&&oe.removeEventListener("click",yr)}));let Rm=c.on("assistant:complete",()=>{Pd&&(Ke.active||Ke.manuallyDeactivated||Pd==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("auto"),_.isVoiceActive()&&hr()}):Ma("auto"))},600))});Be.push(Rm);let Hm=c.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});Be.push(Hm);let rp=()=>{lt(!Y,"user")},Tt=null,Xt=null;if(F&&!Q()){let{instance:i,element:p}=wc({config:o,plugins:s,onToggle:rp});Tt=i,i||(Xt=p)}Tt?e.appendChild(Tt.element):Xt&&e.appendChild(Xt),ps(),lr(),gl(),fl(),Aa(_.isStreaming()),Fd()||(nn()==="follow"?lo(!0):Dd()),Qg(),z&&(!F||Q()?setTimeout(()=>il(),0):Y&&setTimeout(()=>il(),200));let ms=()=>{if(Q()){ko(),ps();return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,E=m.innerWidth<=x,U=y&&E&&F;try{if(U){Lo(),ts=ua();return}let O=!1;G&&(G=!1,Lo(),O=!0);let V=ua();if(!O&&V!==ts&&(Lo(),O=!0),ts=V,O&&Ki(),!F&&!i){ye.style.height="",ye.style.width="";return}if(!p&&!i){let fe=o?.launcher?.width??o?.launcherWidth??Jn;ye.style.width=fe,ye.style.maxWidth=fe}pa(),md()}finally{if(ko(),ps(),Y&&F){let V=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),J=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,le=Rt(o)&&fe&&V,be=J||fe&&V&&F||le;if(be&&!Rn){let Ge=e.getRootNode(),mt=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");mt&&!Wn&&(Wn=lc(mt,o.launcher?.zIndex??Nt)),Rn=cc(e.ownerDocument)}else be||(Wn?.(),Wn=null,Rn?.(),Rn=null)}}};ms();let sp=e.ownerDocument.defaultView??window;if(sp.addEventListener("resize",ms),Be.push(()=>sp.removeEventListener("resize",ms)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ko()});i.observe(Ce),Be.push(()=>i.disconnect())}rn=re.scrollTop;let ap=Dn(re),ip=()=>{let i=re.scrollTop,p=Dn(re),m=p<ap;if(ap=p,!no()){rn=i,$t();return}let{action:y,nextLastScrollTop:x}=fi({following:on.isFollowing(),currentScrollTop:i,lastScrollTop:rn,nearBottom:eo(re,$n),userScrollThreshold:Kg,isAutoScrolling:Zt||ga||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=x,y==="resume"){va()||io();return}y==="pause"&&ss()};if(re.addEventListener("scroll",ip,{passive:!0}),Be.push(()=>re.removeEventListener("scroll",ip)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{rm(),Il(xe)});i.observe(xe),i.observe(re),Be.push(()=>i.disconnect())}let lp=()=>{no()&&on.isFollowing()&&va()&&ss()},cp=re.ownerDocument;cp.addEventListener("selectionchange",lp),Be.push(()=>{cp.removeEventListener("selectionchange",lp)});let Bm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dp=i=>{Bm.has(i.key)&&(No(),qc()&&no()&&on.isFollowing()&&ss())},pp=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(No(),qc()&&no()&&on.isFollowing()&&ss())};re.addEventListener("keydown",dp),re.addEventListener("focusin",pp),Be.push(()=>{re.removeEventListener("keydown",dp),re.removeEventListener("focusin",pp)});let up=i=>{if(i.deltaY!==0&&No(),!no())return;let p=gi({following:on.isFollowing(),deltaY:i.deltaY,nearBottom:eo(re,$n),resumeWhenNearBottom:!0});p==="pause"?ss():p==="resume"&&!va()&&io()};re.addEventListener("wheel",up,{passive:!0}),re.addEventListener("touchmove",No,{passive:!0}),re.addEventListener("pointerdown",No,{passive:!0}),Be.push(()=>{re.removeEventListener("touchmove",No),re.removeEventListener("pointerdown",No)}),Be.push(()=>re.removeEventListener("wheel",up)),Et.addEventListener("click",()=>{as(),re.scrollTop=re.scrollHeight,rn=re.scrollTop,io(),lo(!0),$t()}),Be.push(()=>Et.remove()),Be.push(()=>{Rd(),as()});let fp=()=>{de&&(Ro&&(de.removeEventListener("click",Ro),Ro=null),ie()?(de.style.display="",Ro=()=>{lt(!1,"user")},de.addEventListener("click",Ro)):de.style.display="none")};fp(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),io(),Er(Te.composerOverlay);try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(p),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()})})(),L&&L.addEventListener("submit",Ta);let gp=[["keydown",km],["input",Em],["paste",Lm],["focus",_g]],Sl=i=>{if(i)for(let[p,m]of gp)i.addEventListener(p,m)},Tl=i=>{if(i)for(let[p,m]of gp)i.removeEventListener(p,m)};Sl(I);let mp=()=>{Yt?.onComposerSwap((i,p)=>{Tl(p),I=i,Sl(i)})};mp();let Ml=!1;function Dm(){if(!Ml){Ml=!0;try{let i=I?.value??"",p=Ce.ownerDocument??document,m=I?p.activeElement===I:!1;Tl(I),L?.removeEventListener("submit",Ta),oe?.removeEventListener("click",yr),Yt?.destroy(),Yt=null;let y=null,x=()=>(y=Q()?ki({config:o}):Gs({config:o}),y.footer),E=ed(x)??x();et.replaceComposer(E),Ce=et.composer.footer;let U=y!==null&&E===y.footer;zi=!U,ra=U?y.setSendButtonMode:()=>{},Zc(Ce),nd(Ce),od(),rd(),sd(),mp(),L&&L.addEventListener("submit",Ta),Sl(I),oe?.addEventListener("click",yr);let O=Wo.indexOf(_n);_n.destroy(),_n=qs(M),O>=0&&(Wo[O]=_n),I&&(I.value=i),gl(),lr(),Aa(_.isStreaming()),Lo(),ko(),m&&I?.focus()}finally{Ml=!1}}}let hp=e.ownerDocument??document;hp.addEventListener("keydown",np,!0);let yp="persona-attachment-drop-active",hs=0,El=()=>{hs=0,ve.classList.remove(yp)},br=()=>o.attachments?.enabled===!0&&yt!==null,bp=i=>{!Fi(i.dataTransfer)||!br()||(hs++,hs===1&&ve.classList.add(yp))},vp=i=>{!Fi(i.dataTransfer)||!br()||(hs--,hs<=0&&El())},wp=i=>{!Fi(i.dataTransfer)||!br()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},xp=i=>{if(!Fi(i.dataTransfer)||!br())return;i.preventDefault(),i.stopPropagation(),El();let p=Array.from(i.dataTransfer.files??[]);p.length!==0&&yt.handleFiles(p)},uo=!0;ve.addEventListener("dragenter",bp,uo),ve.addEventListener("dragleave",vp,uo),e.addEventListener("dragover",wp,uo),e.addEventListener("drop",xp,uo);let ka=e.ownerDocument,Cp=i=>{br()&&i.preventDefault()},Ap=i=>{br()&&i.preventDefault()};ka.addEventListener("dragover",Cp),ka.addEventListener("drop",Ap),Be.push(()=>{L&&L.removeEventListener("submit",Ta),Tl(I),hp.removeEventListener("keydown",np,!0),Yt?.destroy()}),Be.push(()=>{ve.removeEventListener("dragenter",bp,uo),ve.removeEventListener("dragleave",vp,uo),e.removeEventListener("dragover",wp,uo),e.removeEventListener("drop",xp,uo),ka.removeEventListener("dragover",Cp),ka.removeEventListener("drop",Ap),El()}),Be.push(()=>{_.cancel()}),Tt?Be.push(()=>{Tt?.destroy()}):Xt&&Be.push(()=>{Xt?.remove()});let kt={update(i){let p=o.toolCall,m=o.messageActions,y=o.layout?.messages,x=o.colorScheme,E=o.loadingIndicator,U=o.iterationDisplay,O=o.features?.showReasoning,V=o.features?.showToolCalls,J=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ug({...o,features:r},i),r=o.features,o=Pc(o),Yi(),Ds(e,o),ea(e,o),ta(e,o),Nn(),o.colorScheme!==x&&hd();let be=Hc.getForInstance(o.plugins);s.length=0,s.push(...be),F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,we=o.features?.scrollToBottom??{};let Ge=nn();he=o.features?.scrollBehavior??{},Ge!==nn()&&(as(),io()),Ld(),Xc(),$t();let mt=me;if(me=o.features?.showEventStreamToggle??!1,me&&!mt){if(Oe||(Ue=new Js(Ne),Oe=new Qs(Qe,Ue),_e=_e??new Zs,Ue.open().then(()=>Oe?.restore()).catch(()=>{}),_.setSSEEventCallback((se,qe)=>{o.onSSEEvent?.(se,qe),_e?.processEvent(se,qe),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!Je&&Re){let se=o.features?.eventStream?.classNames,qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(se?.toggleButton?" "+se.toggleButton:"");Je=b("button",qe),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let ft=ae("activity","18px","currentColor",1.5);ft&&Je.appendChild(ft);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Vt=Ze||ot;Vt&&Vt.parentNode===Re?Re.insertBefore(Je,Vt):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}}else!me&&mt&&(Jr(),Je&&(Je.remove(),Je=null),Oe?.clear(),Ue?.destroy(),Oe=null,Ue=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Tt&&(Tt.destroy(),Tt=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Tt&&!Xt){let{instance:se,element:qe}=wc({config:o,plugins:s,onToggle:rp});Tt=se,se||(Xt=qe),e.appendChild(qe)}Tt&&Tt.update(o),Ve&&o.launcher?.title!==void 0&&(Ve.textContent=o.launcher.title),$e&&o.launcher?.subtitle!==void 0&&($e.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==A&&Re){let se=ct?xi(o,ct,{showClose:ie(),onClose:()=>lt(!1,"user")}):Jo({config:o,showClose:ie(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),Re=et.header.element,Pe=et.header.iconHolder,Ve=et.header.headerTitle,$e=et.header.headerSubtitle,de=et.header.closeButton,A=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),Ve&&(Ve.style.display=ct.showTitle===!1?"none":""),$e&&($e.style.display=ct.showSubtitle===!1?"none":""),de){let se=ie()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:qe}=Te;qe&&!qe.classList.contains("persona-absolute")&&(se?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;Re&&(Re.style.display=At?"":"none");let Lt=o.layout?.showFooter!==!1;Ce&&(Ce.style.display=Lt?"":"none"),ko(),$t(),F!==te?F?lt(N,"auto"):(Y=!0,ps()):N!==j&<(N,"auto"),j=N,te=F,ms(),fp();let De=JSON.stringify(o.toolCall)!==JSON.stringify(p),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),dt=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,Ft=o.iterationDisplay!==U,pt=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(J)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(De||Me||Ct||dt||Ft||pt)&&_&&(Qi++,is(xe,_.getMessages(),Z));let Pt=o.features?.streamAnimation?.type;if(Pt!==le&&Pt&&Pt!=="none"){let se=Or(Pt,o.features?.streamAnimation?.plugins);se&&bi(se,e)}let We=o.launcher??{},Fe=We.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,zt=Fe||Ut===!1,wt=We.headerIconName,at=We.headerIconSize??"48px";if(Pe){let se=ve.querySelector(".persona-border-b-persona-divider"),qe=se?.querySelector(".persona-flex-col");if(zt)Pe.style.display="none",se&&qe&&!se.contains(qe)&&se.insertBefore(qe,se.firstChild);else{if(Pe.style.display="",Pe.style.height=at,Pe.style.width=at,se&&qe&&(se.contains(Pe)?Pe.nextSibling!==qe&&(Pe.remove(),se.insertBefore(Pe,qe)):se.insertBefore(Pe,qe)),wt){let Ze=parseFloat(at)||24,ot=ae(wt,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=We.iconUrl,Ze.style.height=at,Ze.style.width=at;else{let ot=document.createElement("img");ot.src=We.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=at,ot.style.width=at,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=We.agentIconText??"\u{1F4AC}"}let ft=Pe.querySelector("img");ft&&(ft.style.height=at,ft.style.width=at)}}let ut=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(Ve&&(Ve.style.display=ut===!1?"none":""),$e&&($e.style.display=Xe===!1?"none":""),de){let se=ie()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let qe=We.closeButtonSize??"32px",ft=We.closeButtonPlacement??"inline";de.style.height=qe,de.style.width=qe;let{closeButtonWrapper:Ze}=Te,ot=ft==="top-right",Vt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Vt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ve.style.position="relative",ve.appendChild(Ze);else{let go=We.clearChat?.placement??"inline",vs=We.clearChat?.enabled??!0;Ze.className=vs&&go==="inline"?"":"persona-ml-auto";let Sp=ve.querySelector(".persona-border-b-persona-divider");Sp&&Sp.appendChild(Ze)}if(de.style.color=We.closeButtonColor||Kt.actionIconColor,We.closeButtonBackgroundColor?(de.style.backgroundColor=We.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let go=We.closeButtonBorderWidth||"0px",vs=We.closeButtonBorderColor||"transparent";de.style.border=`${go} solid ${vs}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");We.closeButtonBorderRadius?(de.style.borderRadius=We.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(de.style.paddingLeft=We.closeButtonPaddingX,de.style.paddingRight=We.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),We.closeButtonPaddingY?(de.style.paddingTop=We.closeButtonPaddingY,de.style.paddingBottom=We.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let an=We.closeButtonIconName??"x",Ln=We.closeButtonIconText??"\xD7";de.innerHTML="";let Ot=ae(an,"28px","currentColor",1);Ot?(Ot.style.display="block",de.appendChild(Ot)):de.textContent=Ln;let qt=We.closeButtonTooltipText??"Close chat",Kn=We.closeButtonShowTooltip??!0;de.setAttribute("aria-label",qt),Ze&&_t({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??qt,enabled:Kn})}let{clearChatButton:He,clearChatButtonWrapper:ht}=Te;if(He){let se=We.clearChat??{},qe=se.enabled??!0,ft=o.layout?.header?.showClearChat,Ze=ft!==void 0?ft:qe,ot=se.placement??"inline";if(ht){ht.style.display=Ze?"":"none";let{closeButtonWrapper:Vt}=Te;!Q()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Ze?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let an=ot==="top-right",Ln=ht.classList.contains("persona-absolute");if(!Q()&&an!==Ln&&Ze){if(ht.remove(),an)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",ve.style.position="relative",ve.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let qt=ve.querySelector(".persona-border-b-persona-divider"),Kn=Te.closeButtonWrapper;qt&&Kn&&Kn.parentElement===qt?qt.insertBefore(ht,Kn):qt&&qt.appendChild(ht)}let Ot=Te.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(an?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let go=se.size??"32px";He.style.height=go,He.style.width=go}let Vt=se.iconName??"refresh-cw",an=se.iconColor??"";He.style.color=an||Kt.actionIconColor,He.innerHTML="";let Ln=Q()?"14px":"20px",Ot=ae(Vt,Ln,"currentColor",1);if(Ot&&(Ot.style.display="block",He.appendChild(Ot)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let go=se.borderWidth||"0px",vs=se.borderColor||"transparent";He.style.border=`${go} solid ${vs}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let qt=se.tooltipText??"Clear chat",Kn=se.showTooltip??!0;He.setAttribute("aria-label",qt),ht&&_t({anchor:He,trigger:ht,text:()=>He?.getAttribute("aria-label")??qt,enabled:Kn})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],hn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick];H=Fc({parsers:jt,handlers:hn,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null}),Z=Cg(o,H,ge),_.updateConfig(o),is(xe,_.getMessages(),Z),lr(),gl(),ym(),Aa(_.isStreaming());let ys=o.voiceRecognition?.enabled===!0,La=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(ys&&(La||Mt))if(!oe||!pn){let se=Pm(o.voiceRecognition,o.sendButton);se&&(oe=se.micButton,pn=se.micButtonWrapper,xt.insertBefore(pn,W),oe.addEventListener("click",yr),oe.disabled=_.isStreaming())}else{let se=o.voiceRecognition??{},qe=o.sendButton??{},ft=se.iconName??"mic",Ze=qe.size??"40px",ot=se.iconSize??Ze,Vt=parseFloat(ot)||24;oe.style.width=ot,oe.style.height=ot,oe.style.minWidth=ot,oe.style.minHeight=ot;let an=se.iconColor??qe.textColor;oe.innerHTML="";let Ln=ae(ft,Vt,an||"currentColor",1.5);Ln?oe.appendChild(Ln):oe.textContent="\u{1F3A4}";let Ot=se.backgroundColor??qe.backgroundColor;Ot?oe.style.backgroundColor=Ot:oe.style.backgroundColor="",an?oe.style.color=an:oe.style.color="var(--persona-text, #111827)",se.borderWidth?(oe.style.borderWidth=se.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),se.borderColor?oe.style.borderColor=se.borderColor:oe.style.borderColor="",se.paddingX?(oe.style.paddingLeft=se.paddingX,oe.style.paddingRight=se.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),se.paddingY?(oe.style.paddingTop=se.paddingY,oe.style.paddingBottom=se.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let qt=se.tooltipText??"Start voice recognition",Kn=se.showTooltip??!1;oe.setAttribute("aria-label",qt),pn&&_t({anchor:oe,trigger:pn,text:()=>oe?.getAttribute("aria-label")??qt,enabled:Kn}),pn.style.display="",oe.disabled=_.isStreaming()}else oe&&pn&&(pn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Hn&&po());if(o.attachments?.enabled===!0){if(!un||!it){let se=o.attachments??{},ft=(o.sendButton??{}).size??"40px";Sn||(Sn=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",L.insertBefore(Sn,I)),St||(St=document.createElement("input"),St.type="file",St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),L.insertBefore(St,I)),un=b("div","persona-send-button-wrapper"),it=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=ft,Vt=parseFloat(ot)||40,an=Math.round(Vt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Ln=ae(Ze,an,"currentColor",1.5);Ln?it.appendChild(Ln):it.textContent="\u{1F4CE}",it.addEventListener("click",qt=>{qt.preventDefault(),St?.click()}),un.appendChild(it);let Ot=se.buttonTooltipText??"Attach file";_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??Ot}),dn?dn.append(un):L.appendChild(un),!yt&&St&&Sn&&(yt=Rs.fromConfig(se),yt.setPreviewsContainer(Sn),St.addEventListener("change",async()=>{yt&&St?.files&&(await yt.handleFileSelect(St.files),St.value="")}))}else{un.style.display="";let se=o.attachments??{};St&&(St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1),yt&&yt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(Ag(o.attachments?.dropOverlay)),it){let se=o.attachments??{},qe=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",qe),it.textContent="";let ft=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(ft*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",un&&_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??qe})}}else un&&(un.style.display="none"),yt&&yt.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},bs=Dt.useIcon??!1,Ia=Dt.iconText??"\u2191",vr=Dt.iconName,Wa=Dt.tooltipText??"Send message",kl=Dt.showTooltip??!1,jo=Dt.size??"40px",qn=Dt.backgroundColor,Vo=Dt.textColor;if(bs){if(h.style.width=jo,h.style.height=jo,h.style.minWidth=jo,h.style.minHeight=jo,h.style.fontSize="18px",h.style.lineHeight="1",Vo?h.style.color=Vo:h.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(h.innerHTML="",vr){let se=parseFloat(jo)||24,qe=Vo?.trim()||"currentColor",ft=ae(vr,se,qe,2);ft?h.appendChild(ft):h.textContent=Ia}else h.textContent=Ia;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.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",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),Vo?h.style.color=Vo:h.classList.add("persona-text-white");Dt.borderWidth?(h.style.borderWidth=Dt.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),Dt.borderColor?h.style.borderColor=Dt.borderColor:h.style.borderColor="",Dt.paddingX?(h.style.paddingLeft=Dt.paddingX,h.style.paddingRight=Dt.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),Dt.paddingY?(h.style.paddingTop=Dt.paddingY,h.style.paddingBottom=Dt.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),_.isStreaming()||h.setAttribute("aria-label",Wa),W&&_t({anchor:h,trigger:W,text:()=>h.getAttribute("aria-label")??Wa,enabled:kl});let wr=xo(o,Q());Xi(),wr?(xe.style.maxWidth=wr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=wr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",L&&(L.style.maxWidth=wr,L.style.marginLeft="auto",L.style.marginRight="auto"),M&&(M.style.maxWidth=wr,M.style.marginLeft="auto",M.style.marginRight="auto"),R.style.maxWidth=wr,R.style.marginLeft="auto",R.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",K.style.maxWidth="",K.style.marginLeft="",K.style.marginRight="",K.style.width="",L&&(L.style.maxWidth="",L.style.marginLeft="",L.style.marginRight=""),M&&(M.style.maxWidth="",M.style.marginLeft="",M.style.marginRight=""),R.style.maxWidth="",R.style.marginLeft="",R.style.marginRight="");let fo=o.statusIndicator??{},Fm=fo.visible??!0;if(R.style.display=Fm?"":"none",_){let se=_.getStatus();Cn(R,(ft=>ft==="idle"?fo.idleText??It.idle:ft==="connecting"?fo.connectingText??It.connecting:ft==="connected"?fo.connectedText??It.connected:ft==="error"?fo.errorText??It.error:It[ft])(se),fo,se)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Om=fo.align==="left"?"persona-text-left":fo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Om)},open(){ie()&<(!0,"api")},close(){ie()&<(!1,"api")},toggle(){ie()&<(!Y,"api")},reconnect(){_.reconnectNow()},clearChat(){On=!1,_.clearMessages(),Bo.clear(),io();try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!I||_.isStreaming()?!1:(!Y&&ie()&<(!0,"system"),I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let p=i?.trim()||I.value.trim();return p?(!Y&&ie()&<(!0,"system"),I.value="",I.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("user"),_.isVoiceActive()&&hr()})),!0):Hn?!0:op()?(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),Ma("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()}),!0):!1:Hn?(Ke.manuallyDeactivated=!0,kn(),po("user"),!0):!1},injectMessage(i){return!Y&&ie()&<(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Y&&ie()&<(!0,"system");let p=_.injectAssistantMessage(i);return ue&&(ue=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(i){return!Y&&ie()&<(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Y&&ie()&<(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&ie()&<(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&ie()&<(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Y&&ie()&<(!0,"system"),_.injectTestEvent(i)},async connectStream(i,p){return _.connectStream(i,p)},__pushEventStreamEvent(i){Oe&&(_e?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Oe||$i()},hideEventStream(){Se&&Jr()},isEventStreamVisible(){return Se},showArtifacts(){Jt(o)&&(On=!1,sr=!0,Nn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(On=!0,Nn())},upsertArtifact(i){return Jt(o)?(ho(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(On=!1,sr=!0),_.upsertArtifact(i)):null},selectArtifact(i){Jt(o)&&_.selectArtifact(i)},clearArtifacts(){Jt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return F&&!Y&&!Q()||!I?!1:(I.focus(),!0)},async resolveApproval(i,p,m){let x=_.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,p);return}return _.resolveApproval(x.approval,p,m)},setFollowUpSuggestions(i){Vg(i)},clearFollowUpSuggestions(){kd()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...g}},updatePersistentMetadata(i){S(i)},on(i,p){return c.on(i,p)},off(i,p){c.off(i,p)},isOpen(){return ie()&&Y},isVoiceActive(){return Ke.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:ie()&&Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=vg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=wg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,p){return _.submitCSATFeedback(i,p)},async submitNPSFeedback(i,p){return _.submitNPSFeedback(i,p)},destroy(){yl(),Uo!=null&&(clearInterval(Uo),Uo=null),Be.forEach(i=>i()),Le.remove(),tt?.remove(),Tt?.destroy(),Xt?.remove(),Ro&&de.removeEventListener("click",Ro)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,p={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:m=>m?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Be.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",p),Be.push(()=>{window.removeEventListener("persona:focusInput",p)}),me){let O=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.showEventStream()},V=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",V),Be.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",V)})}let m=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.showArtifacts()},y=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.hideArtifacts()},x=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||V?.artifact&&kt.upsertArtifact(V.artifact)},E=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||typeof V?.id=="string"&&kt.selectArtifact(V.id)},U=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",x),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",U),Be.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",x),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",U)})}let mn=uw(o.persistState);if(mn&&ie()){let i=fw(mn.storage),p=`${mn.keyPrefix}widget-open`,m=`${mn.keyPrefix}widget-voice`,y=`${mn.keyPrefix}widget-voice-mode`;if(i){let x=mn.persist?.openState&&i.getItem(p)==="true",E=mn.persist?.voiceState&&i.getItem(m)==="true",U=mn.persist?.voiceState&&i.getItem(y)==="true";if(x&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(E||U)kt.startVoiceRecognition();else if(mn.persist?.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0)),mn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(p,"true")}),c.on("widget:closed",()=>{i.setItem(p,"false")})),mn.persist?.voiceState&&(c.on("voice:state",O=>{i.setItem(m,O.active?"true":"false")}),c.on("user:message",O=>{i.setItem(y,O.viaVoice?"true":"false")})),mn.clearOnChatClear){let O=()=>{i.removeItem(p),i.removeItem(m),i.removeItem(y)},V=()=>O();window.addEventListener("persona:clear-chat",V),Be.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(C&&ie()&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fr(),!qg){let i=Ha(()=>{_&&(Qi++,Bo.clear(),is(xe,_.getMessages(),Z))});Be.push(i)}return kt};var Tg=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Mg=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},zc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",zc(e)},_c=e=>{e.style.transition=""},$c=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Uc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Oi=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vw=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ww=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},xw=e=>{let t=Rr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(t,r)??r;return{inset:o(n?.inset,ti),canvasBackground:o(n?.canvasBackground,ni)}},kg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Cw=(e,t,n,o,r,s,a,l)=>{let u=vn(s),d=u.reveal==="push",c=l!=null,f=l?.inset??"",w=l?.canvasBackground??"";vw(e,t,n,o,d),ww(e,t,n,o,u.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=u.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,T=g!=null?g.innerWidth<=C:!1;if(v&&T&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$c(t),_c(o),Eg(o),Uc(n),Oi(r,o),kg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Nt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Eg(o),hw(o,u.maxHeight),kg(o,c&&a,f,w),u.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$c(t),_c(o),Uc(n),Oi(r,o);let S=u.animate?"transform 180ms ease":"none",k=u.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":k;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=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=P,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_c(o),zc(o),Oi(r,o);let S=Tg(u.width,e.clientWidth),k=Math.max(0,e.clientWidth),P=u.animate?"margin-left 180ms ease":"none",H=u.side==="right"?a?-S:0:a?0:-S;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${k+S}px`,t.style.transition=P,t.style.marginLeft=`${H}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",$c(t),zc(o),Uc(n),Oi(r,o);let S=u.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?u.width:"0px",P=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",H=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${k}`,o.style.width=k,o.style.maxWidth=k,o.style.minWidth=k,o.style.minHeight="0",yw(o,u.maxHeight),o.style.overflow=S||H?"hidden":"visible",o.style.transition=P,S){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let F=c?`calc(${Tg(u.width,e.clientWidth)}px - (2 * ${f}))`:u.width;r.style.width=F,r.style.minWidth=F,r.style.maxWidth=F,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Mg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Mg(n,o)},destroy(){n.remove()}}},Sw=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),u=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),u.appendChild(e);let w=null,g=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?xw(t):null};C();let T=()=>{Cw(a,l,u,d,c,t,f,v)},B=null,S=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=oi(()=>{C(),T()}))},k=()=>{g(),vn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{T()}),w.observe(a)))},P=!1,H=()=>{T(),k(),f&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,bw(a,vn(t)))},F=a.ownerDocument.defaultView,N=()=>{H()};return F?.addEventListener("resize",N),vn(t).reveal==="push"?(l.appendChild(u),l.appendChild(d),a.appendChild(l)):(a.appendChild(u),a.appendChild(d)),H(),S(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let j=z.launcherEnabled?z.open:!0;f!==j&&(f=j,H())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(f=!0),C(),H(),S()},destroy(){F?.removeEventListener("resize",N),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Lg=(e,t)=>Rt(t)?Sw(e,t):Aw(e,t);var oa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Pg=.15,Ig=1.5,jc="persona-preview-shell-theme",Tw={load:()=>null,save:()=>{},clear:()=>{}},Mw=["How do I get started?","Pricing & plans","Talk to support"];function Vc(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ew(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Wg(e){let t=Ew(e);return`* { box-sizing: border-box; }
|
|
141
141
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
142
142
|
html { color-scheme: ${e}; }
|
|
143
143
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -161,7 +161,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
161
161
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
162
162
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
163
163
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
164
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
164
|
+
.preview-workspace-card.short { height: 96px; }`}function Rg(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(jc);o||(o=n.createElement("style"),o.id=jc,n.head.appendChild(o)),o.textContent=Wg(t)}var kw=`
|
|
165
165
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
166
166
|
<div class="preview-iframe-chrome">
|
|
167
167
|
<span class="preview-iframe-dot"></span>
|
|
@@ -180,7 +180,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
180
180
|
<div class="preview-iframe-line body"></div>
|
|
181
181
|
<div class="preview-iframe-line body"></div>
|
|
182
182
|
</div>
|
|
183
|
-
</div>`,
|
|
183
|
+
</div>`,Lw=`
|
|
184
184
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
185
185
|
<div class="preview-iframe-line hero"></div>
|
|
186
186
|
<div class="preview-iframe-line body"></div>
|
|
@@ -193,8 +193,8 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
193
193
|
<div class="preview-workspace-card short"></div>
|
|
194
194
|
<div class="preview-workspace-card short"></div>
|
|
195
195
|
</div>
|
|
196
|
-
</div>`;function
|
|
197
|
-
${
|
|
196
|
+
</div>`;function Hg(e,t,n,o){let r=`
|
|
197
|
+
${kw}
|
|
198
198
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
|
|
199
199
|
<div class="preview-workspace-shell">
|
|
200
200
|
<div class="preview-workspace-topbar">
|
|
@@ -206,7 +206,7 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
206
206
|
</div>
|
|
207
207
|
<div class="preview-workspace-body">
|
|
208
208
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
209
|
-
${
|
|
209
|
+
${Lw}
|
|
210
210
|
</div>
|
|
211
211
|
</div>
|
|
212
212
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var ss=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
214
214
|
<head>
|
|
215
215
|
<meta charset="UTF-8">
|
|
216
216
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
217
|
-
<link rel="stylesheet" href="${
|
|
218
|
-
<style id="${
|
|
217
|
+
<link rel="stylesheet" href="${Vc(o)}">
|
|
218
|
+
<style id="${jc}">${Wg(t)}</style>
|
|
219
219
|
</head>
|
|
220
220
|
<body>
|
|
221
221
|
${n?s:r}
|
|
222
222
|
</body>
|
|
223
|
-
</html>`}var
|
|
224
|
-
${
|
|
225
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
226
|
-
</div>`,
|
|
223
|
+
</html>`}var Pw=()=>[{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()}],Iw=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function Ww(e,t,n=[]){if(e==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return e==="home"?[]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&Iw(t)?[...Pw(),...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 Rw(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:Mw:e.suggestionChips,initialMessages:Ww(t,e,n),storageAdapter:Tw};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Hw(e,t){let n=e.theme?Wr(e.theme,{validate:!1}):Wr();return{...rt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Kr(e,t){let n=e.scene??"conversation";return Rw(Hw(e,t),n,e.appendedMessages??[])}function Bg(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Kr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Kr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Kr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Kr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Kr(e,n),shellMode:n}]}function Bw(e,t){let n={...t},o=[],r=[],s=null,a=!1,l=1,u=1,d=0;function c(){return n.device??"desktop"}function f(){return n.zoom??l}function w(){let S=getComputedStyle(e),k=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),P=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),H=40,F=(n.compareMode??"off")!=="off",N=(e.clientWidth-k-H)/(F?2:1),z=e.clientHeight-P-H;if(N<=0||z<=0)return 1;let j=oa[c()]??oa.desktop;return Math.min(N/j.w,z/j.h,1)}function g(){l=w();let S=Math.max(Pg,Math.min(Ig,f()));u=S;let k=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let P of k){let H=P.dataset.device??"desktop",F=oa[H]??oa.desktop;P.style.width=`${F.w*S}px`,P.style.height=`${F.h*S}px`,H==="mobile"&&(P.style.borderRadius=`${32*S}px`);let N=P.querySelector("iframe");N&&(N.style.width=`${F.w}px`,N.style.height=`${F.h}px`,N.style.transformOrigin="top left",N.style.transition="none",N.style.transform=`scale(${S})`)}n.onScaleChange?.(S)}function v(){n.onBeforeDestroy?.();for(let S of o)S.destroy();for(let S of r)S();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function T(){if(a)return;v();let S=++d,k=Bg(n),P=c(),H=(n.compareMode??"off")!=="off",F=(n.scene??"conversation")==="minimized",N=n.widgetCssPath??"/widget-dist/widget.css",z=n.buildSrcdoc??Hg,j=P==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",te=ue=>`<div class="${j}" data-mount-id="${ue.mountId}" data-device="${P}" data-shell-mode="${ue.shellMode}">
|
|
224
|
+
${H?`<div class="preview-frame-meta"><span class="preview-frame-label">${Vc(ue.label)}</span></div>`:""}
|
|
225
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ue.mountId}"></iframe>
|
|
226
|
+
</div>`,A=H?`<div class="preview-compare-grid">${k.map(ue=>`<div class="preview-compare-cell">${te(ue)}</div>`).join("")}</div>`:`<div class="preview-single">${te(k[0])}</div>`;n.morphContainer?n.morphContainer(e,A):e.innerHTML=A,g();let G=C(),Q=0,ie=G.length,Y=()=>{if(a||S!==d)return;for(let X of G){let ge=X.dataset.mountId;if(!ge||!X.contentDocument)continue;let Z=k.find(he=>he.mountId===ge);if(!Z)continue;let pe=()=>{},ee=Rt(Z.config),me=ee?(()=>{let he=X.contentDocument?.getElementById(`preview-content-${ge}`);if(!he)return null;let ke=Lg(he,Z.config),Ne=X.contentDocument.createElement("div");Ne.id=ge,Ne.style.height="100%",Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1",Ne.style.minHeight="0",ke.host.appendChild(Ne);let Ue=()=>ke.syncWidgetState(we.getState()),Qe=pe;return pe=()=>{ke.destroy(),Qe()},Ne.__syncDock=Ue,Ne.__hostLayout=ke,Ne})():X.contentDocument.getElementById(ge);if(!me)continue;let we=Sg(me,Z.config);if(o.push(we),ee&&me.__syncDock){let he=me.__syncDock,ke=we.on("widget:opened",he),Ne=we.on("widget:closed",he),Ue=pe;pe=()=>{ke(),Ne(),Ue()},he()}r.push(pe),F&&we.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let X of o)X.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
227
227
|
|
|
228
228
|
This is a preview of the artifact sidebar.
|
|
229
229
|
|
|
@@ -231,4 +231,4 @@ This is a preview of the artifact sidebar.
|
|
|
231
231
|
|
|
232
232
|
- Markdown rendering
|
|
233
233
|
- Document toolbar
|
|
234
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes
|
|
234
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:G,controllers:[...o]})};for(let ue of G){let X=ue.dataset.mountId;if(!X)continue;let ge=k.find(Z=>Z.mountId===X);ge&&(ue.addEventListener("load",()=>{Q++,Q>=ie&&Y()},{once:!0}),ue.srcdoc=z(X,ge.shellMode,Rt(ge.config),N))}ie===0&&Y()}function B(){if(a)return;let S=Bg(n);if(o.length!==S.length){T();return}if(S.some(P=>{let H=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!H||H.dataset.shellMode!==P.shellMode})){T();return}o.forEach((P,H)=>{P.update(S[H].config),(n.scene??"conversation")==="minimized"&&P.close()});for(let P of S){let H=e.querySelector(`iframe[data-mount-id="${P.mountId}"]`);H&&Rg(H,P.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(e)),T(),{update(S){if(a)return;let k=S.device!==void 0&&S.device!==n.device||S.scene!==void 0&&S.scene!==n.scene||S.compareMode!==void 0&&S.compareMode!==n.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==n.widgetCssPath;n={...n,...S},k?T():B()},destroy(){a||(a=!0,v(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return u},setZoom(S){a||(n={...n,zoom:S},g())}}}export{Bw as createThemePreview};
|