@runtypelabs/persona 4.7.0 → 4.9.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 +1 -0
- package/dist/animations/glyph-cycle.cjs +2 -2
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/glyph-cycle.js +2 -2
- package/dist/animations/{types-CSmiKRVa.d.cts → types-4ROVJ1gA.d.cts} +85 -3
- package/dist/animations/{types-CSmiKRVa.d.ts → types-4ROVJ1gA.d.ts} +85 -3
- package/dist/animations/wipe.cjs +2 -2
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-5EIIHQLQ.js +1 -0
- package/dist/chunk-IO5VVUKP.js +3 -0
- package/dist/chunk-IPVK3KOM.js +1 -0
- package/dist/chunk-UPO4GUFC.js +1 -0
- package/dist/codegen.cjs +13 -13
- package/dist/codegen.js +14 -14
- package/dist/context-mentions-7S5KVUTG.js +169 -0
- package/dist/context-mentions-inline-TTCN7ZM2.js +4 -0
- package/dist/context-mentions-inline.cjs +4 -0
- package/dist/context-mentions-inline.d.cts +203 -0
- package/dist/context-mentions-inline.d.ts +203 -0
- package/dist/context-mentions-inline.js +4 -0
- package/dist/context-mentions.cjs +295 -0
- package/dist/context-mentions.d.cts +7025 -0
- package/dist/context-mentions.d.ts +7025 -0
- package/dist/context-mentions.js +295 -0
- package/dist/index.cjs +99 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1507 -182
- package/dist/index.d.ts +1507 -182
- package/dist/index.global.js +88 -56
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +99 -68
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +3 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +24 -24
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +17 -0
- package/dist/plugin-kit.d.ts +17 -0
- package/dist/plugin-kit.js +1 -1
- package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
- package/dist/runtype-tts.js +1 -1
- package/dist/session-reconnect-JKIJBHS5.js +1 -0
- package/dist/smart-dom-reader.cjs +18 -17
- package/dist/smart-dom-reader.d.cts +1260 -16
- package/dist/smart-dom-reader.d.ts +1260 -16
- package/dist/smart-dom-reader.js +18 -17
- package/dist/testing.cjs +3 -3
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +260 -58
- package/dist/theme-editor-preview.d.cts +1234 -15
- package/dist/theme-editor-preview.d.ts +1234 -15
- package/dist/theme-editor-preview.js +87 -58
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +1226 -15
- package/dist/theme-editor.d.ts +1226 -15
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +76 -0
- package/dist/theme-reference.d.ts +76 -0
- package/dist/theme-reference.js +1 -1
- package/dist/voice-worklet-player.cjs +2 -2
- package/dist/voice-worklet-player.js +2 -2
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +16 -5
- package/src/artifacts-session.test.ts +178 -0
- package/src/client.test.ts +255 -1
- package/src/client.ts +157 -60
- package/src/components/artifact-card.test.ts +333 -0
- package/src/components/artifact-card.ts +75 -28
- package/src/components/artifact-inline.test.ts +1328 -0
- package/src/components/artifact-inline.ts +920 -0
- package/src/components/artifact-pane.test.ts +1042 -0
- package/src/components/artifact-pane.ts +440 -131
- package/src/components/artifact-preview.test.ts +1155 -0
- package/src/components/artifact-preview.ts +994 -0
- package/src/components/composer-parts.ts +3 -12
- package/src/components/context-mention-button.test.ts +70 -0
- package/src/components/context-mention-button.ts +82 -0
- package/src/components/context-mention-chip.ts +134 -0
- package/src/components/context-mention-menu.test.ts +508 -0
- package/src/components/context-mention-menu.ts +0 -0
- package/src/components/message-bubble.test.ts +175 -0
- package/src/components/message-bubble.ts +177 -19
- package/src/components/panel.ts +7 -10
- package/src/components/pill-composer-builder.test.ts +6 -2
- package/src/components/pill-composer-builder.ts +6 -6
- package/src/components/reasoning-bubble.ts +1 -13
- package/src/components/registry.ts +38 -3
- package/src/components/tool-bubble.ts +1 -13
- package/src/context-mentions-bundle.test.ts +163 -0
- package/src/context-mentions-entry.ts +185 -0
- package/src/context-mentions-inline-entry.test.ts +136 -0
- package/src/context-mentions-inline-entry.ts +226 -0
- package/src/context-mentions-inline-loader.test.ts +30 -0
- package/src/context-mentions-inline-loader.ts +36 -0
- package/src/context-mentions-inline.ts +15 -0
- package/src/context-mentions-loader.ts +32 -0
- package/src/context-mentions.ts +16 -0
- package/src/defaults.ts +1 -0
- package/src/generated/runtype-openapi-contract.ts +55 -3
- package/src/index-core.ts +46 -1
- package/src/index-global.ts +51 -0
- package/src/index.ts +8 -0
- package/src/markdown-parsers-loader.test.ts +158 -0
- package/src/markdown-parsers-loader.ts +83 -27
- package/src/plugin-kit.test.ts +40 -0
- package/src/plugin-kit.ts +39 -5
- package/src/runtime/host-layout.test.ts +163 -0
- package/src/runtime/host-layout.ts +110 -7
- package/src/runtime/init.ts +18 -61
- package/src/session.mentions.test.ts +175 -0
- package/src/session.test.ts +52 -4
- package/src/session.ts +197 -27
- package/src/smart-dom-reader.test.ts +129 -2
- package/src/smart-dom-reader.ts +127 -1
- package/src/styles/context-mention-menu-css.ts +176 -0
- package/src/styles/widget.css +1002 -152
- package/src/theme-editor/preview.ts +2 -0
- package/src/theme-editor/sections.test.ts +26 -1
- package/src/theme-editor/sections.ts +13 -5
- package/src/theme-reference.ts +2 -2
- package/src/tool-call-display-defaults.test.ts +1 -0
- package/src/types/theme.ts +79 -0
- package/src/types.ts +1041 -17
- package/src/ui.artifact-pane-gating.test.ts +636 -0
- package/src/ui.component-directive.test.ts +104 -0
- package/src/ui.composer-bar.test.ts +60 -2
- package/src/ui.detached-panel.test.ts +1049 -0
- package/src/ui.mention-submit.test.ts +235 -0
- package/src/ui.tool-display.test.ts +51 -0
- package/src/ui.ts +998 -159
- package/src/utils/artifact-custom-actions.ts +128 -0
- package/src/utils/artifact-display.test.ts +42 -0
- package/src/utils/artifact-display.ts +84 -0
- package/src/utils/artifact-file.test.ts +116 -0
- package/src/utils/artifact-file.ts +117 -0
- package/src/utils/artifact-gate.test.ts +112 -5
- package/src/utils/artifact-gate.ts +39 -14
- package/src/utils/artifact-loading-status.ts +55 -0
- package/src/utils/artifact-status-label.ts +190 -0
- package/src/utils/buttons.ts +7 -1
- package/src/utils/chunk-loader.test.ts +97 -0
- package/src/utils/chunk-loader.ts +88 -0
- package/src/utils/code-highlight.test.ts +186 -0
- package/src/utils/code-highlight.ts +400 -0
- package/src/utils/composer-contenteditable.test.ts +507 -0
- package/src/utils/composer-contenteditable.ts +626 -0
- package/src/utils/composer-document.test.ts +280 -0
- package/src/utils/composer-document.ts +293 -0
- package/src/utils/composer-history.test.ts +35 -7
- package/src/utils/composer-history.ts +30 -20
- package/src/utils/composer-input.ts +159 -0
- package/src/utils/context-mention-controller.test.ts +1215 -0
- package/src/utils/context-mention-controller.ts +1186 -0
- package/src/utils/context-mention-manager.test.ts +422 -0
- package/src/utils/context-mention-manager.ts +410 -0
- package/src/utils/context-mention-orchestrator.test.ts +538 -0
- package/src/utils/context-mention-orchestrator.ts +348 -0
- package/src/utils/icons.ts +2 -0
- package/src/utils/live-region.test.ts +108 -0
- package/src/utils/live-region.ts +94 -0
- package/src/utils/mention-channels.ts +63 -0
- package/src/utils/mention-llm-format.test.ts +91 -0
- package/src/utils/mention-llm-format.ts +79 -0
- package/src/utils/mention-matcher.test.ts +86 -0
- package/src/utils/mention-matcher.ts +221 -0
- package/src/utils/mention-token.ts +72 -0
- package/src/utils/mention-trigger.test.ts +155 -0
- package/src/utils/mention-trigger.ts +156 -0
- package/src/utils/roving-tablist.test.ts +152 -0
- package/src/utils/roving-tablist.ts +111 -0
- package/src/utils/spinner.ts +45 -0
- package/src/utils/theme.test.ts +76 -4
- package/src/utils/theme.ts +7 -0
- package/src/utils/tokens.ts +118 -11
- package/src/utils/tool-loading-animation.test.ts +32 -0
- package/src/utils/tool-loading-animation.ts +24 -0
- package/dist/chunk-DFBSCFYN.js +0 -1
- package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
- package/dist/session-reconnect-U77QFUR7.js +0 -1
|
@@ -1,22 +1,34 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),
|
|
3
|
-
`):
|
|
1
|
+
import{a as Uc}from"./chunk-5EIIHQLQ.js";import{a as m,b as Tn,c as zc,d as Ne,e as Bn,f as oe,g as qc,i as Kc,j as Gc}from"./chunk-IPVK3KOM.js";import{a as jc,b as Vc}from"./chunk-IO5VVUKP.js";var Jo=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:$y,load:xf,provide:zy,getSync:ki}=Jo({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),Qs=new Set,Cf=()=>{let t=[...Qs];Qs.clear();for(let e of t)try{e()}catch{}};var Af=()=>{let t=ki();return t?Promise.resolve(t):xf().then(e=>(Cf(),e))},Xs=t=>ki()?()=>{}:(Qs.add(t),Af().catch(()=>{}),()=>{Qs.delete(t)});var Hn=ki;var Sf=t=>{if(t)return t},Li=t=>{let e=null;return n=>{let o=Hn();if(!o)return Zn(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Sf(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Js=t=>t?Li({markedOptions:t.options,renderer:t.renderer}):Li(),Vy=Li();var Zn=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Tf={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"]},Mf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ef=()=>{let t=null;return e=>{let n=Hn();if(!n)return Zn(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Mf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Tf)}},Ys=t=>t===!1?null:typeof t=="function"?t:Ef();var Qc=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Xc=t=>t.includes("|"),Jc=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},kf=t=>`| ${t.join(" | ")} |`,Lf=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Pf=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Yc=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Xc(r)||Qc.test(r)||!Qc.test(s))continue;let a=Jc(r).length;if(a<1)continue;let l=Lf(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let d=e[p];if(d.trim()===""||!Xc(d))break;let c=kf(Pf(Jc(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
|
|
3
|
+
`):t};var Dn="webmcp:",Pi=new Map,Zc=t=>{Pi.clear();for(let e of t){let n=e.title?.trim();n&&Pi.set(e.name,n)}},jr=t=>Pi.get(od(t)),Zs={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},ed=null;function nd(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${If(e.join(""))}`}function td(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function If(t){let e=td(t,0).toString(36),n=td(t,2654435761).toString(36);return`${e}.${n}`}var ea=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return Zs.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Zc(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=Wf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return wn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=od(e),a;try{a=await r.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return wn(`Failed to read WebMCP registry: ${C}`)}Zc(a);let l=a.find(b=>b.name===s);if(!l)return wn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return wn("Aborted by cancel()");let p=jr(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return wn("User declined the tool call.");if(o?.aborted)return wn("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let b=await r.executeTool(l,Nf(n),{signal:c.signal});return Bf(b)}catch(b){if(u)return wn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return wn("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return wn(C)}finally{clearTimeout(w),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(ed?await ed():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Zs.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Zs.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??Hf;try{return await n(e)}catch(o){return Zs.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Rf(e,o))}},od=t=>t.startsWith(Dn)?t.slice(Dn.length):t,Yo=t=>t.startsWith(Dn),Rf=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Wf=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Bf=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Ff(e)}]}},wn=t=>({isError:!0,content:[{type:"text",text:t}]}),Hf=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Df(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
|
-
${e}`:"")+(
|
|
6
|
+
${e}`:"")+(t.description?`
|
|
7
7
|
|
|
8
|
-
${n.description}`:"");return window.confirm(t)},uf=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},mf=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},gf=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var ff="agent_",hf="flow_";function Su(n){return n.startsWith(ff)?{kind:"agentId",agentId:n}:n.startsWith(hf)?{kind:"flowId",flowId:n}:null}function Tu(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),l=t.slice(r+1);if(a==="runtype"){let c=Su(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let o=Su(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as yf,ARR as bf,OBJ as vf,STR as wf}from"partial-json";var v=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Pr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Us=(...n)=>n.filter(Boolean).join(" ");var Li="ask_user_question",zs=8,ds="data-persona-ask-sheet-for",xf="Other",Cf="Other\u2026",Eu="Type your own answer here",ku="Send",Af="Next",Sf="Back",Tf="Submit all",Mf="Skip",Ef=3,Pi="data-ask-current-index",Ii="data-ask-question-count",Lu="data-ask-answers",Wi="data-ask-grouped",Pu="data-ask-layout",kf=n=>n.layout==="pills"?"pills":"rows",Lf=n=>n.getAttribute(Pu)==="pills"?"pills":"rows",Mu=!1,Iu=n=>n.replace(/["\\]/g,"\\$&"),_o=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Li,Ri=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ps=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=yf(o,wf|vf|bf);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},qs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>zs&&!Mu&&(Mu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zs}.`)),e.slice(0,zs)},Pf=n=>{var e;return(e=qs(n)[0])!=null?e:null},If=(n,e)=>{var t;return(t=qs(n)[e])!=null?t:null},Wf=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Wu=(n,e,t)=>{if(n!=="rows")return null;let r=v("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");r.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},Rf=(n,e,t,r)=>{let s=v("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=n.label,a.appendChild(l),n.description){let c=v("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=Wu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Hf=n=>{let t=v("span",n==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Bf=(n,e,t,r)=>{var u,g,h;let s=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<Ef;m++)s.appendChild(Hf(r));return s}if(d.forEach((m,b)=>{s.appendChild(Rf(m,b,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?xf:Cf;if(r==="rows"){let b=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let w=v("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(u=e.freeTextPlaceholder)!=null?u:Eu,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(S),b.appendChild(w);let B=Wu(r,a,d.length);B&&b.appendChild(B),s.appendChild(b)}else{let b=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(h=e.freeTextLabel)!=null?h:m,s.appendChild(b)}}return s},Ru=(n,e)=>{var s,a;let r=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:Eu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let l=v("button","persona-ask-free-text-submit persona-pointer-events-auto");l.type="button",l.textContent=(a=n.submitLabel)!=null?a:ku,l.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(l)}return r},Df=n=>{var r;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=v("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:ku,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Nf=(n,e,t)=>{var c,u,g,h;let r=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Sf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Mf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=n===e-1;return l.textContent=d?(g=t.submitAllLabel)!=null?g:Tf:(h=t.nextLabel)!=null?h:Af,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),r.appendChild(s),r},$o=n=>{let e=n.getAttribute(Lu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Hu=(n,e)=>{n.setAttribute(Lu,JSON.stringify(e))},er=n=>{var t;let e=Number((t=n.getAttribute(Pi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Ff=(n,e)=>{n.setAttribute(Pi,String(Math.max(0,Math.floor(e))))},us=n=>{var t;let e=Number((t=n.getAttribute(Ii))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ho=n=>n.getAttribute(Wi)==="true",Of=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let l=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(t,l)){let d=t[l];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},_f=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Ta=(n,e)=>{let{payload:t}=ps(e),r=qs(t),o=$o(n),s={},a=new Set;return r.forEach((l,d)=>{let c=typeof(l==null?void 0:l.question)=="string"?l.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Bu=n=>{let e=$o(n),t=er(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),l=n.querySelector('[data-ask-free-text-input="true"]');if(l)if(typeof r=="string"&&r.length>0&&!a.has(r)){l.value=r;let d=l.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else l.value=""},Du=n=>{if(!ho(n))return;let e=$o(n),t=er(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Hi=(n,e,t)=>{let r=Ri(t),o=Lf(n),{payload:s,complete:a}=ps(e),l=ho(n),d=er(n),c=us(n),u=l?If(s,d):Pf(s),g=!!(u!=null&&u.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=n.querySelector('[data-ask-question="true"]');if(b){let T=typeof(u==null?void 0:u.question)=="string"?u.question:"";b.textContent=T,b.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let T=Bf(u,r,a,o);w.replaceWith(T)}if(o!=="rows"){let T=n.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Ru(r,o))}let S=n.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!S?n.appendChild(Df(r)):(!g||l)&&S&&S.remove(),n.setAttribute("data-multi-select",g?"true":"false");let B=n.querySelector('[data-ask-nav-row="true"]');if(l){let T=Nf(d,c,r);B?B.replaceWith(T):n.appendChild(T)}else B&&B.remove();Bu(n),Du(n)},$f=(n,e,t)=>{let r=Ri(e),o=kf(r),s=n.toolCall.id,a=qs(t),l=Math.max(1,a.length),d=l>1,c=Of(n,a),u=d?_f(n,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(Ii,String(l)),g.setAttribute(Pi,String(u)),g.setAttribute(Wi,d?"true":"false"),g.setAttribute(Pu,o),Hu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Wf(g,r);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",h.appendChild(b),g.appendChild(h);let S=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),g.appendChild(S),o!=="rows"&&g.appendChild(Ru(r,o)),Hi(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Uf=(n,e,t)=>{let{payload:r}=ps(e),o=Math.max(1,qs(r).length);o>us(n)&&(n.setAttribute(Ii,String(o)),o>1&&!ho(n)&&n.setAttribute(Wi,"true")),Hi(n,e,t)};var Ma=(n,e,t)=>{if(!t||!_o(n)||Ri(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ds}]`).forEach(c=>{c.getAttribute(ds)!==o&&c.remove()});let a=t.querySelector(`[${ds}="${Iu(o)}"]`);if(a){Uf(a,n,e);return}let{payload:l}=ps(n),d=$f(n,e,l);t.appendChild(d)},ms=(n,e)=>{if(!n)return;let t=e?`[${ds}="${Iu(e)}"]`:`[${ds}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Bi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),yo=(n,e)=>{let t=$o(n),r=er(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,Hu(n,t),Bu(n),Du(n)},Ea=(n,e,t,r)=>{let o=us(n),s=Math.max(0,Math.min(o-1,r));Ff(n,s),Hi(n,e,t)};var Vr="suggest_replies";var zf={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},Nu={name:Vr,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:zf,origin:"sdk",annotations:{readOnlyHint:!0}},Di=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ni=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===Vr},qf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Fu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Ni(r))continue;let o=qf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},Ou=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var jf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,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},Vf={name:Li,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:jf,origin:"sdk",annotations:{readOnlyHint:!0}},ka=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(Vf),Ou(n)&&e.push(Nu),e};import{parse as Kf,STR as Gf,OBJ as Qf}from"partial-json";var _u=n=>n.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Ks=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},zu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},qu=()=>{var e;let n=Yf();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},ju=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=Kf(t,Gf|Qf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?_u(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=_u(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Vu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Ku="4.7.0";var Gs=Ku;var eh="https://api.runtype.com/v1/dispatch",Wa="https://api.runtype.com";function th(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let l=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(l&&l!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(l))return`attachment.${l}`}return"attachment"}var Oi=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function nh(n){switch(n){case"json":return ju;case"regex-json":return qu;case"xml":return Vu;default:return zu}}var Gu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function rh(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Gu(t);if(!Gu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Ks(n);return Ks(e)!==null&&a===null?e:n}var Qs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:eh,this.headers={"Content-Type":"application/json","X-Persona-Version":Gs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:nh(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Sa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=Tu(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var l,d,c;let e=((d=(l=this.config).getStoredSessionId)==null?void 0:d.call(l))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gs},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wa}/v1/client/feedback`}async sendFeedback(e){var a,l;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(l=(a=this.config).onSessionExpired)==null||l.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){var r;return(r=e.signal)==null||r.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var r,o,s,a;t({type:"status",status:"connecting"});try{let l=await this.initSession();if(new Date>=new Date(l.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(r=this.config).onSessionExpired)==null||o.call(r);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let d=await this.buildPayload(e.messages),c=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:l.sessionId,messages:e.messages.filter(Oi).map(m=>{var b,w,S;return{id:m.id,role:m.role,content:(S=(w=(b=m.contentParts)!=null?b:m.llmContent)!=null?w:m.rawContent)!=null?S:m.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},{response:g,commit:h}=await this.sendWithClientToolsDiff(l.sessionId,d.clientTools,m=>{let b={...u,...m};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",b),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Gs},body:JSON.stringify(b),signal:e.signal})});if(!g.ok){let m=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clearClientSession(),(a=(s=this.config).onSessionExpired)==null||a.call(s);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(g.status===429){let w=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let b=new Error(m.error||"Failed to send message");throw t({type:"error",error:b}),b}if(!g.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}h(),t({type:"status",status:"connected"});try{await this.streamResponse(g.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(l){let d=l instanceof Error?l:new Error(String(l));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&t({type:"error",error:d}),d}}async dispatchProxy(e,t){t({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw t({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:a}),a}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){t({type:"status",status:"connecting"});let r=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw t({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:a}),a}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Wa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async sendWithClientToolsDiff(e,t,r,o){let s=!!(t&&t.length>0),a=s?Cu(t):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,c=!s&&(o==null?void 0:o.emptyMeansReplace)===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,g;for(let h=0;;h++){if(g=await r({...s&&(u||!d)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&h===0&&s){let b=await g.clone().json().catch(()=>null);if((b==null?void 0:b.error)==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a!=null?a:null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,t,r){var c,u,g,h;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Wa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};if(a&&(d.sessionId=a),o&&a){let m=[...ka(this.config),...(h=await((g=this.webMcpBridge)==null?void 0:g.snapshotForDispatch()))!=null?h:[]],{response:b,commit:w}=await this.sendWithClientToolsDiff(a,m,S=>{let B={...d,...S};return this.debug&&console.debug("[AgentWidgetClient] client token resume",B),fetch(s,{method:"POST",headers:l,body:JSON.stringify(B),signal:r==null?void 0:r.signal})},{emptyMeansReplace:!0});return b.ok&&w(),b}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,l,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Oi).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let g=new Date(c.createdAt).getTime(),h=new Date(u.createdAt).getTime();return g-h}).map(c=>{var u,g,h;return{role:c.role,content:(h=(g=(u=c.contentParts)!=null?u:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ka(this.config),...(d=await((l=this.webMcpBridge)==null?void 0:l.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async u=>{try{let g=await u({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,l;let t=e.slice().filter(Oi).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return u-g}).map(d=>{var c,u,g;return{role:d.role,content:(g=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...ka(this.config),...(l=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?l:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=g,o(g),g},c=u=>r.current?r.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=c(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,o(u)}return l.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),l.error&&(a.current=null,t({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,t,r,o){var hn,gr,fr,Ue;let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),c=0,u=()=>d+c++,g=M=>{let me=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Me=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...M,reasoning:me,toolCall:Me,tools:ke}},h=M=>{if(M.role!=="assistant"||M.variant)return!0;let me=Array.isArray(M.contentParts)&&M.contentParts.length>0,Me=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||me||Me||!!M.stopReason},m=M=>{h(M)&&t({type:"message",message:g(M)})},b=null,w=null,S={current:null},B={current:null},T=null,I="",R=new Map,P=new Map,A=new Map,W=new Map,z=new Map,$={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},U=M=>{if(M==null)return null;try{return String(M)}catch{return null}},F=M=>{var me,Me,ke,Re,tt;return U((tt=(Re=(ke=(Me=(me=M.stepId)!=null?me:M.step_id)!=null?Me:M.step)!=null?ke:M.parentId)!=null?Re:M.flowStepId)!=null?tt:M.flow_step_id)},te=M=>{var me,Me,ke,Re,tt,Qe,ht;return U((ht=(Qe=(tt=(Re=(ke=(Me=(me=M.callId)!=null?me:M.call_id)!=null?Me:M.requestId)!=null?ke:M.request_id)!=null?Re:M.toolCallId)!=null?tt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,Y=()=>{if(b)return b;let M,me="",Me=T;return!de&&Ee?(M=Ee,de=!0,me=o!=null?o:""):Ee&&Me?M=`${Ee}_${Me}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(b),b},Le=(M,me)=>{$.lastId=me,M&&$.byStep.set(M,me)},Pe=(M,me)=>{var tt;let Me=(tt=M.reasoningId)!=null?tt:M.id,ke=F(M);if(Me){let Qe=String(Me);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!me)return $.lastId;if(!me)return null;let Re=`reason-${u()}`;return Le(ke,Re),Re},ae=M=>{let me=W.get(M);if(me)return me;let Me={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:M,status:"streaming",chunks:[]}};return W.set(M,Me),m(Me),Me},fe=(M,me)=>{k.lastId=me,M&&k.byCall.set(M,me)},ne=new Set,re=new Map,ce=new Set,Ce=new Map,_e=M=>{if(!M)return!1;let me=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},V=(M,me)=>{var tt;let Me=(tt=M.toolId)!=null?tt:M.id,ke=te(M);if(Me){let Qe=String(Me);return fe(ke,Qe),Qe}if(ke){let Qe=k.byCall.get(ke);if(Qe)return k.lastId=Qe,Qe}if(k.lastId&&!me)return k.lastId;if(!me)return null;let Re=`tool-${u()}`;return fe(ke,Re),Re},X=M=>{let me=z.get(M);if(me)return me;let Me={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:M,status:"pending"}};return z.set(M,Me),m(Me),Me},Ae=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let me=Number(M);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Me=Date.parse(M);if(!Number.isNaN(Me))return Me}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},ie=new Map,Se=new Map,Je=new Map,et=(M,me,Me)=>{var ht;let ke=Je.get(M);ke||(ke=[],Je.set(M,ke));let Re=0,tt=ke.length;for(;Re<tt;){let ge=Re+tt>>>1;ke[ge].seq<me?Re=ge+1:tt=ge}((ht=ke[Re])==null?void 0:ht.seq)===me?ke[Re]={seq:me,text:Me}:ke.splice(Re,0,{seq:me,text:Me});let Qe="";for(let ge=0;ge<ke.length;ge++)Qe+=ke[ge].text;return Qe},Wt=(M,me)=>{let Me=J(me),ke=Se.get(M.id),Re=rh(ke,Me);M.rawContent=Re;let tt=ie.get(M.id),Qe=le=>{var Ke;let gt=(Ke=M.content)!=null?Ke:"";le.trim()!==""&&(gt.trim().length===0||le.startsWith(gt)||le.trimStart().startsWith(gt.trim()))&&(M.content=le)},ht=()=>{var le;if(tt){let gt=(le=tt.close)==null?void 0:le.call(tt);gt instanceof Promise&>.catch(()=>{})}ie.delete(M.id),Se.delete(M.id),M.streaming=!1,m(M)};if(!tt){Qe(Me),ht();return}let ge=Ks(Re);if(ge!==null&&ge.trim()!==""){Qe(ge),ht();return}let H=le=>{var Lt;let gt=typeof le=="string"?le:(Lt=le==null?void 0:le.text)!=null?Lt:null;if(gt!==null&>.trim()!=="")return gt;let Ke=tt.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Me},be;try{be=tt.processChunk(Re)}catch{Qe(Me),ht();return}if(be instanceof Promise){be.then(le=>{Qe(H(le)),ht()}).catch(()=>{Qe(Me),ht()});return}Qe(H(be)),ht()},ft=null,rt=(M,me,Me,ke)=>{var ge;M.rawContent=me,ie.has(M.id)||ie.set(M.id,this.createStreamParser());let Re=ie.get(M.id),tt=me.trim().startsWith("{")||me.trim().startsWith("[");if(tt&&Se.set(M.id,me),Re.__isPlainTextParser===!0){M.content=ke!==void 0?me:M.content+Me,Se.delete(M.id),ie.delete(M.id),M.rawContent=void 0,m(M);return}let ht=Re.processChunk(me);if(ht instanceof Promise)ht.then(H=>{var le;let be=typeof H=="string"?H:(le=H==null?void 0:H.text)!=null?le:null;be!==null&&be.trim()!==""?(M.content=be,m(M)):!tt&&!me.trim().startsWith("<")&&(M.content=ke!==void 0?me:M.content+Me,Se.delete(M.id),ie.delete(M.id),M.rawContent=void 0,m(M))}).catch(()=>{M.content=ke!==void 0?me:M.content+Me,Se.delete(M.id),ie.delete(M.id),M.rawContent=void 0,m(M)});else{let H=typeof ht=="string"?ht:(ge=ht==null?void 0:ht.text)!=null?ge:null;H!==null&&H.trim()!==""?(M.content=H,m(M)):!tt&&!me.trim().startsWith("<")&&(M.content=ke!==void 0?me:M.content+Me,Se.delete(M.id),ie.delete(M.id),M.rawContent=void 0,m(M))}},ue=(M,me)=>{var ge,H;let Me=me!=null?me:M.content;if(Me==null||Me===""){M.streaming=!1,m(M);return}let ke=Se.get(M.id),Re=ke!=null?ke:J(Me);M.rawContent=Re;let tt=ie.get(M.id),Qe=null,ht=!1;if(tt&&(Qe=tt.getExtractedText(),Qe===null&&(Qe=Ks(Re)),Qe===null)){let be=tt.processChunk(Re);be instanceof Promise?(ht=!0,be.then(le=>{var Ke;let gt=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;gt!==null&&(M.content=gt,M.streaming=!1,ie.delete(M.id),Se.delete(M.id),m(M))}).catch(()=>{})):Qe=typeof be=="string"?be:(ge=be==null?void 0:be.text)!=null?ge:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Se.has(M.id)||(M.content=J(Me));let be=ie.get(M.id);if(be){let le=(H=be.close)==null?void 0:H.call(be);le instanceof Promise&&le.catch(()=>{}),ie.delete(M.id)}Se.delete(M.id),M.streaming=!1,m(M)}},Q=(M,me,Me)=>{let ke=P.get(M);if(ke)return ke;let Re={id:`nested-${me}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return P.set(M,Re),m(Re),Re},it=[],je,Te=new Map,we=0,Ye="agent",qt=!1,ye=null,pe=null,Cn=new Map,Ct=(hn=this.config.iterationDisplay)!=null?hn:"separate";for(je=()=>{var M,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Yt,hr,Wr,nr,rr,Qr,jt,or,Rr,Hn,Pn,Bn,sr,yr,Xr,jn,Jr,At,br,vr,Hr,ar,yt,Co,wr,Ao,In,Qo,Yr,Br,Zr,eo,So,To,to,wt,Dn,Nn,An,St,Vn,Kn,Fn,no,xe,Dr,Gn,Ot,Qn,Nr,Ms,Xo,Es,Mo,xr,ro,lt,tn,nn,Cr,ks,Fr,Eo,Ar,O,Jo,Xn,Sr,Or,Tr,ir,Yo,ga,yn,Sn,lr,Tn,ko,cr,bn,Mr,Zo,Lo,es,oo;for(let so=0;so<it.length;so++){let ot=it[so].payloadType,x=it[so].payload;if(!qt&&Ye!=="flow"&&typeof x.stepType=="string"&&(Ye="flow"),ot==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){R.set(j,q),Q(j,q,"reasoning");continue}let G=(M=Pe(x,!0))!=null?M:`reason-${u()}`,K=ae(G);K.reasoning=(me=K.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Ae((Me=x.startedAt)!=null?Me:x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(ot==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&R.has(j)&&P.has(j)){let De=P.get(j),nt=(Qe=(tt=(Re=x.reasoningText)!=null?Re:x.text)!=null?tt:x.delta)!=null?Qe:"";nt&&x.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(nt)),m(De));continue}let q=(ge=(ht=Pe(x,!1))!=null?ht:Pe(x,!0))!=null?ge:`reason-${u()}`,G=ae(q);G.reasoning=(H=G.reasoning)!=null?H:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(le=G.reasoning.startedAt)!=null?le:Ae((be=x.startedAt)!=null?be:x.timestamp);let K=(Lt=(Ke=(gt=x.reasoningText)!=null?gt:x.text)!=null?Ke:x.delta)!=null?Lt:"";if(K&&x.hidden!==!0){let De=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(De!==void 0){let nt=et(q,De,String(K));G.reasoning.chunks=[nt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=x.done?"complete":"streaming",x.done){G.reasoning.completedAt=Ae((Et=x.completedAt)!=null?Et:x.timestamp);let De=(vt=G.reasoning.startedAt)!=null?vt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-De)}G.streaming=G.reasoning.status!=="complete",m(G)}else if(ot==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&R.has(j)&&P.has(j)){let nt=P.get(j);if(nt.reasoning){let ct=typeof x.text=="string"?x.text:"";ct&&nt.reasoning.chunks.length===0&&nt.reasoning.chunks.push(ct),nt.reasoning.status="complete",nt.streaming=!1,m(nt)}R.delete(j),P.delete(j);continue}let q=(Ft=(Qt=Pe(x,!1))!=null?Qt:Pe(x,!0))!=null?Ft:`reason-${u()}`,G=typeof x.text=="string"?x.text:"";!W.get(q)&&(G||x.scope==="loop")&&ae(q);let K=W.get(q);if(K!=null&&K.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Ae((Yt=x.completedAt)!=null?Yt:x.timestamp);let nt=(hr=K.reasoning.startedAt)!=null?hr:Date.now();K.reasoning.durationMs=Math.max(0,((Wr=K.reasoning.completedAt)!=null?Wr:Date.now())-nt),K.streaming=!1,m(K)}let De=F(x);De&&$.byStep.delete(De)}else if(ot==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(rr=(nr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?nr:V(x,!0))!=null?rr:`tool-${u()}`,q=(Qr=x.toolName)!=null?Qr:x.name;if(_e(q)){ne.add(j);continue}fe(te(x),j);let G=X(j),K=(jt=G.toolCall)!=null?jt:{id:j,status:"pending"};K.name=q!=null?q:K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=(Rr=K.startedAt)!=null?Rr:Ae((or=x.startedAt)!=null?or:x.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,x.executionId&&(G.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(G)}else if(ot==="tool_output_delta"){let j=(Pn=(Hn=V(x,!1))!=null?Hn:V(x,!0))!=null?Pn:`tool-${u()}`;if(ne.has(j))continue;let q=X(j),G=(Bn=q.toolCall)!=null?Bn:{id:j,status:"running"};G.startedAt=(yr=G.startedAt)!=null?yr:Ae((sr=x.startedAt)!=null?sr:x.timestamp);let K=(Jr=(jn=(Xr=x.text)!=null?Xr:x.delta)!=null?jn:x.message)!=null?Jr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Hr=q.agentMetadata)!=null?Hr:{executionId:(br=De==null?void 0:De.executionId)!=null?br:x.executionId,iteration:(vr=De==null?void 0:De.iteration)!=null?vr:x.iteration}),m(q)}else if(ot==="tool_complete"){let j=(yt=(ar=V(x,!1))!=null?ar:V(x,!0))!=null?yt:`tool-${u()}`;if(ne.has(j)){ne.delete(j);continue}let q=X(j),G=(Co=q.toolCall)!=null?Co:{id:j,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=Ae((wr=x.completedAt)!=null?wr:x.timestamp);let K=(Ao=x.duration)!=null?Ao:x.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(In=G.startedAt)!=null?In:Date.now();G.durationMs=Math.max(0,((Qo=G.completedAt)!=null?Qo:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Zr=q.agentMetadata)!=null?Zr:{executionId:(Yr=De==null?void 0:De.executionId)!=null?Yr:x.executionId,iteration:(Br=De==null?void 0:De.iteration)!=null?Br:x.iteration}),m(q);let nt=te(x);nt&&k.byCall.delete(nt)}else if(ot==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,q=(eo=j!=null?j:x.toolId)!=null?eo:`local-${u()}`,G=X(q),K=x.toolName,De=x.origin==="webmcp"&&!cs(K)?`webmcp:${K}`:K,nt=cs(De),ct=(So=G.toolCall)!=null?So:{id:q,status:"pending"};ct.name=De,ct.args=x.parameters,ct.status=nt?"running":"complete",ct.chunks=(To=ct.chunks)!=null?To:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Ae((wt=(to=x.startedAt)!=null?to:x.timestamp)!=null?wt:x.awaitedAt),nt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=x.executionId)!=null?St:(An=G.agentMetadata)==null?void 0:An.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},m(G)}else if(ot==="text_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){R.set(j,q);continue}let G=b;G&&(Ye==="flow"?(ue(G),ft=G):(G.streaming=!1,m(G)),b=null),T=typeof x.id=="string"?x.id:T,I=""}else if(ot==="text_delta"){let j=typeof x.id=="string"?x.id:null,q=j?R.get(j):void 0;if(j&&q){let K=typeof x.delta=="string"?x.delta:"",De=((Vn=A.get(j))!=null?Vn:"")+K;if(A.set(j,De),De.trim()==="")continue;let nt=Q(j,q);nt.agentMetadata={...nt.agentMetadata,executionId:x.executionId,parentToolId:q},rt(nt,De,K,void 0);continue}if(T=typeof x.id=="string"?x.id:T,Ye==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(I+=K,I.trim()==="")continue;let De=Y();De.agentMetadata={executionId:x.executionId,iteration:x.iteration},rt(De,I,K,void 0),w=De;continue}let G=Y();G.content+=(Kn=x.delta)!=null?Kn:"",G.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:ye!=null?ye:void 0,agentName:pe==null?void 0:pe.agentName},w=G,m(G)}else if(ot==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&R.has(j)){let G=P.get(j);G&&ue(G),R.delete(j),A.delete(j),P.delete(j);continue}let q=b;q&&(Ye==="flow"?(ue(q),ft=q):(((Fn=q.content)!=null?Fn:"")===""&&typeof x.text=="string"&&(q.content=x.text),q.streaming=!1,m(q)),b=null),T=null,I=""}else if(ot==="step_complete"){let j=x.stepType,q=x.executionType;if(j==="tool"||q==="context")continue;if(x.success===!1){let G=x.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((no=G.message)!=null?no:"Step failed"):"Step failed";t({type:"error",error:new Error(K)});let De=b;De&&De.streaming&&(De.streaming=!1,m(De)),t({type:"status",status:"idle"});continue}{let G=ft;ft=null;let K=x.stopReason,De=(xe=x.result)==null?void 0:xe.response;if(G)K&&(G.stopReason=K),De!=null?Wt(G,De):G.streaming!==!1&&(ie.delete(G.id),Se.delete(G.id),G.streaming=!1,m(G));else{let nt=De!=null&&De!=="";if(nt||K){let ct=Y();K&&(ct.stopReason=K),nt?ue(ct,De):(ct.streaming=!1,m(ct))}}continue}}else if(ot==="execution_start")Ye=x.kind==="flow"?"flow":"agent",qt=!0,Ye==="agent"&&(pe={executionId:x.executionId,agentId:(Dr=x.agentId)!=null?Dr:"virtual",agentName:(Gn=x.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ot=x.maxTurns)!=null?Ot:1,startedAt:Ae(x.startedAt)});else if(ot==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(pe&&(pe.currentIteration=j),Ct==="separate"&&j>1){let q=b;q&&(q.streaming=!1,m(q),Cn.set(j-1,q),b=null)}we=j}ye=typeof x.id=="string"?x.id:null,w=null}else if(ot==="tool_input_delta"){let j=(Qn=x.toolCallId)!=null?Qn:k.lastId;if(j){let q=z.get(j);q!=null&&q.toolCall&&(q.toolCall.chunks=(Nr=q.toolCall.chunks)!=null?Nr:[],q.toolCall.chunks.push((Ms=x.delta)!=null?Ms:""),m(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=x.stopReason,q=b!=null?b:w;if(j&&q!==null){let G=x.id;(!G||((Xo=q.agentMetadata)==null?void 0:Xo.turnId)===G)&&(q.stopReason=j,m(q))}ye===x.id&&(ye=null)}else if(ot==="media_start"){let j=String(x.id);Te.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Te.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(ot==="media_complete"){let j=String(x.id),q=Te.get(j);Te.delete(j);let G=(Mo=(Es=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Es:q==null?void 0:q.mediaType)!=null?Mo:"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,De=typeof x.url=="string"?x.url:q&&q.parts.length>0?q.parts.join(""):void 0,nt=null;if(K)nt={type:"media",data:K,mediaType:G};else if(De){let Mn=G.toLowerCase();nt={type:Mn==="image"||Mn.startsWith("image/")?"image-url":"file-url",url:De,mediaType:G}}let ct=(xr=x.toolCallId)!=null?xr:q==null?void 0:q.toolCallId,ui=nt?[nt]:[],ao=[];for(let Mn of ui){if(!Mn||typeof Mn!="object")continue;let cn=Mn,_r=typeof cn.type=="string"?cn.type:void 0,Er=typeof cn.mediaType=="string"?cn.mediaType.toLowerCase():"",rn=null,En="";if(_r==="media"){let un=typeof cn.data=="string"?cn.data:void 0;if(!un)continue;En=Er.length>0?Er:"application/octet-stream",rn=`data:${En};base64,${un}`}else if(_r==="image-url"){let un=typeof cn.url=="string"?cn.url:void 0;if(!un)continue;En=Er,rn=un}else if(_r==="file-url"){let un=typeof cn.url=="string"?cn.url:void 0;if(!un)continue;En=Er,rn=un}else continue;if(rn)if(_r==="image-url"||En.startsWith("image/"))ao.push({type:"image",image:rn,...En.includes("/")?{mimeType:En}:{}});else if(En.startsWith("audio/"))ao.push({type:"audio",audio:rn,mimeType:En});else if(En.startsWith("video/"))ao.push({type:"video",video:rn,mimeType:En});else{let un=En||"application/octet-stream";ao.push({type:"file",data:rn,mimeType:un,filename:th(un)})}}if(ao.length>0){let Mn=u(),cn=ct,Er={id:`agent-media-${typeof cn=="string"&&cn.length>0?`${cn}-${Mn}`:String(Mn)}`,role:"assistant",content:"",contentParts:ao,createdAt:new Date().toISOString(),streaming:!1,sequence:Mn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};m(Er);let rn=b;rn&&(rn.streaming=!1,m(rn)),b=null,S.current=null}}else if(ot==="execution_complete"){let j=(ro=x.kind)!=null?ro:Ye;j==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=Ae(x.completedAt),pe.stopReason=x.stopReason);let q=b;q&&(j==="flow"&&q.streaming!==!1?ue(q):(q.streaming=!1,m(q)),b=null),T=null,I="",ft=null,t({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let j=typeof x.error=="string"?x.error:(tn=(lt=x.error)==null?void 0:lt.message)!=null?tn:"Execution error";t({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(nn=x.approvalId)!=null?nn:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(Cr=pe==null?void 0:pe.agentId)!=null?Cr:"virtual",executionId:(Fr=(ks=x.executionId)!=null?ks:pe==null?void 0:pe.executionId)!=null?Fr:"",toolName:(Eo=x.toolName)!=null?Eo:"",toolType:x.toolType,description:(O=x.description)!=null?O:`Execute ${(Ar=x.toolName)!=null?Ar:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="step_await"&&x.awaitReason==="approval_required"){let j=(Jo=x.approvalId)!=null?Jo:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(Xn=pe==null?void 0:pe.agentId)!=null?Xn:"virtual",executionId:(Or=(Sr=x.executionId)!=null?Sr:pe==null?void 0:pe.executionId)!=null?Or:"",toolName:(Tr=x.toolName)!=null?Tr:"",toolType:x.toolType,description:(Yo=x.description)!=null?Yo:`Execute ${(ir=x.toolName)!=null?ir:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="approval_complete"){let j=x.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:(ga=x.decision)!=null?ga:"approved",agentId:(yn=pe==null?void 0:pe.agentId)!=null?yn:"virtual",executionId:(lr=(Sn=x.executionId)!=null?Sn:pe==null?void 0:pe.executionId)!=null?lr:"",toolName:(Tn=x.toolName)!=null?Tn:"",description:(ko=x.description)!=null?ko:"",resolvedAt:Date.now()}};m(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=x.artifactType,q=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:q,artifactType:j,title:G,component:typeof x.component=="string"?x.component:void 0}),Ce.set(q,{markdown:"",title:G}),!ce.has(q)){ce.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:j,status:"streaming"}})};re.set(q,K),m(K)}}else if(ot==="artifact_delta"){let j=String(x.id),q=typeof x.delta=="string"?x.delta:String((cr=x.delta)!=null?cr:"");t({type:"artifact_delta",id:j,artDelta:q});let G=Ce.get(j);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(ot==="artifact_complete"){let j=String(x.id);t({type:"artifact_complete",id:j});let q=re.get(j);if(q){q.streaming=!1;try{let G=JSON.parse((bn=q.rawContent)!=null?bn:"{}");if(G.props){G.props.status="complete";let K=Ce.get(j);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}Ce.delete(j),m(q),re.delete(j)}}}else if(ot==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let q=String((Mr=j.id)!=null?Mr:`msg-${u()}`),G=j.role,De={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:u()};if(m(De),De.rawContent)try{let nt=JSON.parse(De.rawContent),ct=(Zo=nt==null?void 0:nt.props)==null?void 0:Zo.artifactId;typeof ct=="string"&&ce.add(ct)}catch{}b=null,S.current=null,ie.delete(q),Se.delete(q)}else if(ot==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Lo=x.error)==null?void 0:Lo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(j)});let q=b;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(ot==="dispatch_error"){let q=(es=x.message)!=null?es:x.error;q!=null&&q!==""&&(j=new Error(String(q)))}else{let q=x.error;typeof q=="string"&&q!==""?j=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(j=new Error(String((oo=q.message)!=null?oo:q)))}if(j){t({type:"error",error:j});let q=b;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:me}=await s.read();if(M)break;l+=a.decode(me,{stream:!0});let Me=l.split(`
|
|
8
|
+
${t.description}`:"");return window.confirm(n)},Df=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Nf=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Ff=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function ko(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function ta(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Of="agent_",_f="flow_";function rd(t){return t.startsWith(Of)?{kind:"agentId",agentId:t}:t.startsWith(_f)?{kind:"flowId",flowId:t}:null}function sd(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=rd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=rd(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as $f,ARR as zf,OBJ as Uf,STR as jf}from"partial-json";var Ii="ask_user_question",Vr=8,Zo="data-persona-ask-sheet-for",Vf="Other",qf="Other\u2026",id="Type your own answer here",ld="Send",Kf="Next",Gf="Back",Qf="Submit all",Xf="Skip",Jf=3,Ri="data-ask-current-index",Wi="data-ask-question-count",cd="data-ask-answers",Bi="data-ask-grouped",dd="data-ask-layout",Yf=t=>t.layout==="pills"?"pills":"rows",Zf=t=>t.getAttribute(dd)==="pills"?"pills":"rows",ad=!1,pd=t=>t.replace(/["\\]/g,"\\$&"),Lo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Ii,Hi=t=>t?.features?.askUserQuestion??{},er=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=$f(r,jf|Uf|zf);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},qr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Vr&&!ad&&(ad=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Vr}.`)),e.slice(0,Vr)},eg=t=>qr(t)[0]??null,tg=(t,e)=>qr(t)[e]??null,ng=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ud=(t,e,n)=>{if(t!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},og=(t,e,n,o)=>{let s=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=m("span","persona-ask-row-content"),l=m("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let d=m("span","persona-ask-row-description");d.textContent=t.description,a.appendChild(d)}s.appendChild(a);let p=ud(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},rg=t=>{let n=m("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},sg=(t,e,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Jf;c++)s.appendChild(rg(o));return s}if(p.forEach((c,u)=>{s.appendChild(og(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?Vf:qf;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??id,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let b=ud(o,a,p.length);b&&u.appendChild(b),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??c,s.appendChild(u)}}return s},fd=(t,e)=>{let o=m("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??id,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ld,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},ag=t=>{let e=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ld,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},ig=(t,e,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Gf,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Xf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=m("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??Qf:n.nextLabel??Kf,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Po=t=>{let e=t.getAttribute(cd);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},gd=(t,e)=>{t.setAttribute(cd,JSON.stringify(e))},un=t=>{let e=Number(t.getAttribute(Ri)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},lg=(t,e)=>{t.setAttribute(Ri,String(Math.max(0,Math.floor(e))))},tr=t=>{let e=Number(t.getAttribute(Wi)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},eo=t=>t.getAttribute(Bi)==="true",cg=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},dg=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},na=(t,e)=>{let{payload:n}=er(e),o=qr(n),r=Po(t),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},md=t=>{let e=Po(t),n=un(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},hd=t=>{if(!eo(t))return;let e=Po(t),n=un(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Di=(t,e,n)=>{let o=Hi(n),r=Zf(t),{payload:s,complete:a}=er(e),l=eo(t),p=un(t),d=tr(t),c=l?tg(s,p):eg(s),u=!!c?.multiSelect,w=t.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let M=typeof c?.question=="string"?c.question:"";b.textContent=M,b.classList.toggle("persona-ask-question-skeleton",!M&&!a)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let M=sg(c,o,a,r);C.replaceWith(M)}if(r!=="rows"){let M=t.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(fd(o,r))}let P=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?t.appendChild(ag(o)):(!u||l)&&P&&P.remove(),t.setAttribute("data-multi-select",u?"true":"false");let H=t.querySelector('[data-ask-nav-row="true"]');if(l){let M=ig(p,d,o);H?H.replaceWith(M):t.appendChild(M)}else H&&H.remove();md(t),hd(t)},pg=(t,e,n)=>{let o=Hi(e),r=Yf(o),s=t.toolCall.id,a=qr(n),l=Math.max(1,a.length),p=l>1,d=cg(t,a),c=p?dg(t,l):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Zo,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Wi,String(l)),u.setAttribute(Ri,String(c)),u.setAttribute(Bi,p?"true":"false"),u.setAttribute(dd,r),gd(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`),ng(u,o);let w=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let b=m("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",w.appendChild(b),u.appendChild(w);let P=m("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),u.appendChild(P),r!=="rows"&&u.appendChild(fd(o,r)),Di(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ug=(t,e,n)=>{let{payload:o}=er(e),r=Math.max(1,qr(o).length);r>tr(t)&&(t.setAttribute(Wi,String(r)),r>1&&!eo(t)&&t.setAttribute(Bi,"true")),Di(t,e,n)};var oa=(t,e,n)=>{if(!n||!Lo(t)||Hi(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Zo}]`).forEach(d=>{d.getAttribute(Zo)!==r&&d.remove()});let a=n.querySelector(`[${Zo}="${pd(r)}"]`);if(a){ug(a,t,e);return}let{payload:l}=er(t),p=pg(t,e,l);n.appendChild(p)},nr=(t,e)=>{if(!t)return;let n=e?`[${Zo}="${pd(e)}"]`:`[${Zo}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ni=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),to=(t,e)=>{let n=Po(t),o=un(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,gd(t,n),md(t),hd(t)},ra=(t,e,n,o)=>{let r=tr(t),s=Math.max(0,Math.min(r-1,o));lg(t,s),Di(t,e,n)};var Nn="suggest_replies";var fg={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},yd={name:Nn,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:fg,origin:"sdk",annotations:{readOnlyHint:!0}},Fi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Oi=t=>t.variant==="tool"&&t.toolCall?.name===Nn,gg=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},bd=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Oi(n))continue;let o=gg(n.toolCall?.args);return o.length>0?o:null}return null},vd=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var mg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Vr,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},hg={name:Ii,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:mg,origin:"sdk",annotations:{readOnlyHint:!0}},sa=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(hg),vd(t)&&e.push(yd),e};import{parse as yg,STR as bg,OBJ as vg}from"partial-json";var wd=t=>t.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),no=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},wg=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},xd=t=>t.status==="complete"?wg(t):t.status==="pending"?"Waiting":"",xg=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Cd=t=>t.status==="complete"?xg(t):"Using tool...",aa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Gr=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return aa(e)},ia=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return aa(e)},_i=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Gr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},la=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Kr(o,n.slice(s,a.index),[]),a[1]!==void 0?Kr(o,a[1],["bold"]):a[2]!==void 0?Kr(o,a[2],["italic"]):a[3]!==void 0&&Kr(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Kr(o,n.slice(s),[]),o},Kr=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Cg=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Qr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Ad=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Sd=()=>{let t=Cg();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Td=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=yg(n,bg|vg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?wd(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=wd(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Md=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Ed="4.9.0";var Xr=Ed;var Sg="https://api.runtype.com/v1/dispatch",ca="https://api.runtype.com";function Tg(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var $i=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Mg(t){switch(t){case"json":return Td;case"regex-json":return Sd;case"xml":return Md;default:return Ad}}var kd=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Eg(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=kd(n);if(!kd(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Qr(t);return Qr(e)!==null&&a===null?e:t}var Jr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??Sg,this.headers={"Content-Type":"application/json","X-Persona-Version":Xr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Mg(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new ea(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=sd(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ca}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},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$/,"")||ca}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:e.messages.filter($i).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xr},body:JSON.stringify(c),signal:e.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ca}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?nd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ca}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...sa(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(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,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(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter($i).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=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);return a&&(r.context=a),r}async buildPayload(e){let n=e.slice().filter($i).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=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);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(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=E=>{let Q=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,v=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,S=E.tools?E.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...E,reasoning:Q,toolCall:v,tools:S}},w=E=>{if(E.role!=="assistant"||E.variant)return!0;let Q=Array.isArray(E.contentParts)&&E.contentParts.length>0,v=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||Q||v||!!E.stopReason},f=E=>{w(E)&&n({type:"message",message:u(E)})},b=null,C=null,P={current:null},H={current:null},M=null,T="",I=new Map,z=new Map,N=new Map,x=new Map,U=new Map,V={lastId:null,byStep:new Map},J={lastId:null,byCall:new Map},D=E=>{if(E==null)return null;try{return String(E)}catch{return null}},$=E=>D(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),fe=E=>D(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),he=o,Ee=!1,xe=()=>{if(b)return b;let E,Q="",v=M;return!Ee&&he?(E=he,Ee=!0,Q=r??""):he&&v?E=`${he}_${v}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:E,role:"assistant",content:Q,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(b),b},te=(E,Q)=>{V.lastId=Q,E&&V.byStep.set(E,Q)},ge=(E,Q)=>{let v=E.reasoningId??E.id,S=$(E);if(v){let W=String(v);return te(S,W),W}if(S){let W=V.byStep.get(S);if(W)return V.lastId=W,W}if(V.lastId&&!Q)return V.lastId;if(!Q)return null;let k=`reason-${c()}`;return te(S,k),k},Y=E=>{let Q=x.get(E);if(Q)return Q;let v={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return x.set(E,v),f(v),v},le=(E,Q)=>{J.lastId=Q,E&&J.byCall.set(E,Q)},Z=new Set,be=new Map,ve=new Set,ue=new Map,Te=E=>{if(!E)return!1;let Q=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return Q==="emit_artifact_markdown"||Q==="emit_artifact_component"},Ce=(E,Q)=>{let v=E.toolId??E.id,S=fe(E);if(v){let W=String(v);return le(S,W),W}if(S){let W=J.byCall.get(S);if(W)return J.lastId=W,W}if(J.lastId&&!Q)return J.lastId;if(!Q)return null;let k=`tool-${c()}`;return le(S,k),k},je=E=>{let Q=U.get(E);if(Q)return Q;let v={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,v),f(v),v},Fe=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let Q=Number(E);if(!Number.isNaN(Q)&&Number.isFinite(Q))return Q;let v=Date.parse(E);if(!Number.isNaN(v))return v}return Date.now()},Pe=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Be=new Map,at=new Map,_e=new Map,Xe=(E,Q,v)=>{let S=_e.get(E);S||(S=[],_e.set(E,S));let k=0,W=S.length;for(;k<W;){let B=k+W>>>1;S[B].seq<Q?k=B+1:W=B}S[k]?.seq===Q?S[k]={seq:Q,text:v}:S.splice(k,0,{seq:Q,text:v});let G="";for(let B=0;B<S.length;B++)G+=S[B].text;return G},an=(E,Q)=>{let v=Pe(Q),S=at.get(E.id),k=Eg(S,v);E.rawContent=k;let W=Be.get(E.id),G=Me=>{let lt=E.content??"";Me.trim()!==""&&(lt.trim().length===0||Me.startsWith(lt)||Me.trimStart().startsWith(lt.trim()))&&(E.content=Me)},B=()=>{if(W){let Me=W.close?.();Me instanceof Promise&&Me.catch(()=>{})}Be.delete(E.id),at.delete(E.id),E.streaming=!1,f(E)};if(!W){G(v),B();return}let j=Qr(k);if(j!==null&&j.trim()!==""){G(j),B();return}let ae=Me=>{let lt=typeof Me=="string"?Me:Me?.text??null;if(lt!==null&<.trim()!=="")return lt;let q=W.getExtractedText();return q!==null&&q.trim()!==""?q:v},tt;try{tt=W.processChunk(k)}catch{G(v),B();return}if(tt instanceof Promise){tt.then(Me=>{G(ae(Me)),B()}).catch(()=>{G(v),B()});return}G(ae(tt)),B()},Et=null,ft=(E,Q,v,S)=>{E.rawContent=Q,Be.has(E.id)||Be.set(E.id,this.createStreamParser());let k=Be.get(E.id),W=Q.trim().startsWith("{")||Q.trim().startsWith("[");if(W&&at.set(E.id,Q),k.__isPlainTextParser===!0){E.content=S!==void 0?Q:E.content+v,at.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E);return}let B=k.processChunk(Q);if(B instanceof Promise)B.then(j=>{let ae=typeof j=="string"?j:j?.text??null;ae!==null&&ae.trim()!==""?(E.content=ae,f(E)):!W&&!Q.trim().startsWith("<")&&(E.content=S!==void 0?Q:E.content+v,at.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=S!==void 0?Q:E.content+v,at.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E)});else{let j=typeof B=="string"?B:B?.text??null;j!==null&&j.trim()!==""?(E.content=j,f(E)):!W&&!Q.trim().startsWith("<")&&(E.content=S!==void 0?Q:E.content+v,at.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E))}},ke=(E,Q)=>{let v=Q??E.content;if(v==null||v===""){E.streaming=!1,f(E);return}let k=at.get(E.id)??Pe(v);E.rawContent=k;let W=Be.get(E.id),G=null,B=!1;if(W&&(G=W.getExtractedText(),G===null&&(G=Qr(k)),G===null)){let j=W.processChunk(k);j instanceof Promise?(B=!0,j.then(ae=>{let tt=typeof ae=="string"?ae:ae?.text??null;tt!==null&&(E.content=tt,E.streaming=!1,Be.delete(E.id),at.delete(E.id),f(E))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!B){G!==null&&G.trim()!==""?E.content=G:at.has(E.id)||(E.content=Pe(v));let j=Be.get(E.id);if(j){let ae=j.close?.();ae instanceof Promise&&ae.catch(()=>{}),Be.delete(E.id)}at.delete(E.id),E.streaming=!1,f(E)}},me=(E,Q,v)=>{let S=z.get(E);if(S)return S;let k={id:`nested-${Q}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Q}};return z.set(E,k),f(k),k},it=[],Ie,pe=new Map,ie=0,ye="agent",bt=!1,F=null,ne=null,De=new Map,Se=this.config.iterationDisplay??"separate";for(Ie=()=>{for(let E=0;E<it.length;E++){let Q=it[E].payloadType,v=it[E].payload;if(!bt&&ye!=="flow"&&typeof v.stepType=="string"&&(ye="flow"),Q==="reasoning_start"){let S=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&k){I.set(S,k),me(S,k,"reasoning");continue}let W=ge(v,!0)??`reason-${c()}`,G=Y(W);G.reasoning=G.reasoning??{id:W,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Fe(v.startedAt??v.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(G.reasoning.scope=v.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(Q==="reasoning_delta"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)&&z.has(S)){let B=z.get(S),j=v.reasoningText??v.text??v.delta??"";j&&v.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(j)),f(B));continue}let k=ge(v,!1)??ge(v,!0)??`reason-${c()}`,W=Y(k);W.reasoning=W.reasoning??{id:k,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??Fe(v.startedAt??v.timestamp);let G=v.reasoningText??v.text??v.delta??"";if(G&&v.hidden!==!0){let B=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(B!==void 0){let j=Xe(k,B,String(G));W.reasoning.chunks=[j]}else W.reasoning.chunks.push(String(G))}if(W.reasoning.status=v.done?"complete":"streaming",v.done){W.reasoning.completedAt=Fe(v.completedAt??v.timestamp);let B=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-B)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(Q==="reasoning_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)&&z.has(S)){let j=z.get(S);if(j.reasoning){let ae=typeof v.text=="string"?v.text:"";ae&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(ae),j.reasoning.status="complete",j.streaming=!1,f(j)}I.delete(S),z.delete(S);continue}let k=ge(v,!1)??ge(v,!0)??`reason-${c()}`,W=typeof v.text=="string"?v.text:"";!x.get(k)&&(W||v.scope==="loop")&&Y(k);let G=x.get(k);if(G?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(G.reasoning.scope=v.scope),W&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(W),G.reasoning.status="complete",G.reasoning.completedAt=Fe(v.completedAt??v.timestamp);let j=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-j),G.streaming=!1,f(G)}let B=$(v);B&&V.byStep.delete(B)}else if(Q==="tool_start"){b&&(b.streaming=!1,f(b),b=null),typeof v.iteration=="number"&&(ie=v.iteration);let S=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Ce(v,!0)??`tool-${c()}`,k=v.toolName??v.name;if(Te(k)){Z.add(S);continue}le(fe(v),S);let W=je(S),G=W.toolCall??{id:S,status:"pending"};G.name=k??G.name,G.status="running",v.parameters!==void 0?G.args=v.parameters:v.args!==void 0&&(G.args=v.args),G.startedAt=G.startedAt??Fe(v.startedAt??v.timestamp),G.completedAt=void 0,G.durationMs=void 0,W.toolCall=G,W.streaming=!0,v.executionId&&(W.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(W)}else if(Q==="tool_output_delta"){let S=Ce(v,!1)??Ce(v,!0)??`tool-${c()}`;if(Z.has(S))continue;let k=je(S),W=k.toolCall??{id:S,status:"running"};W.startedAt=W.startedAt??Fe(v.startedAt??v.timestamp);let G=v.text??v.delta??v.message??"";G&&(W.chunks=W.chunks??[],W.chunks.push(String(G))),W.status="running",k.toolCall=W,k.streaming=!0;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(k)}else if(Q==="tool_complete"){let S=Ce(v,!1)??Ce(v,!0)??`tool-${c()}`;if(Z.has(S)){Z.delete(S);continue}let k=je(S),W=k.toolCall??{id:S,status:"running"};W.status="complete",v.result!==void 0&&(W.result=v.result),typeof v.duration=="number"&&(W.duration=v.duration),W.completedAt=Fe(v.completedAt??v.timestamp);let G=v.duration??v.executionTime;if(typeof G=="number")W.durationMs=G;else{let ae=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-ae)}k.toolCall=W,k.streaming=!1;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),f(k);let j=fe(v);j&&J.byCall.delete(j)}else if(Q==="await"&&v.toolName){let S=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,k=S??v.toolId??`local-${c()}`,W=je(k),G=v.toolName,B=v.origin==="webmcp"&&!Yo(G)?`webmcp:${G}`:G,j=Yo(B),ae=W.toolCall??{id:k,status:"pending"};ae.name=B,ae.args=v.parameters,ae.status=j?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??Fe(v.startedAt??v.timestamp??v.awaitedAt),j?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,W.toolCall=ae,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:v.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(W)}else if(Q==="text_start"){let S=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&k){I.set(S,k);continue}let W=b;W&&(ye==="flow"?(ke(W),Et=W):(W.streaming=!1,f(W)),b=null),M=typeof v.id=="string"?v.id:M,T=""}else if(Q==="text_delta"){let S=typeof v.id=="string"?v.id:null,k=S?I.get(S):void 0;if(S&&k){let G=typeof v.delta=="string"?v.delta:"",B=(N.get(S)??"")+G;if(N.set(S,B),B.trim()==="")continue;let j=me(S,k);j.agentMetadata={...j.agentMetadata,executionId:v.executionId,parentToolId:k},ft(j,B,G,void 0);continue}if(M=typeof v.id=="string"?v.id:M,ye==="flow"){let G=typeof v.delta=="string"?v.delta:"";if(T+=G,T.trim()==="")continue;let B=xe();B.agentMetadata={executionId:v.executionId,iteration:v.iteration},ft(B,T,G,void 0),C=B;continue}let W=xe();W.content+=v.delta??"",W.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:F??void 0,agentName:ne?.agentName},C=W,f(W)}else if(Q==="text_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&I.has(S)){let W=z.get(S);W&&ke(W),I.delete(S),N.delete(S),z.delete(S);continue}let k=b;k&&(ye==="flow"?(ke(k),Et=k):((k.content??"")===""&&typeof v.text=="string"&&(k.content=v.text),k.streaming=!1,f(k)),b=null),M=null,T=""}else if(Q==="step_complete"){let S=v.stepType,k=v.executionType;if(S==="tool"||k==="context")continue;if(v.success===!1){let W=v.error,G=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let B=b;B&&B.streaming&&(B.streaming=!1,f(B)),n({type:"status",status:"idle"});continue}{let W=Et;Et=null;let G=v.stopReason,B=v.result?.response;if(W)G&&(W.stopReason=G),B!=null?an(W,B):W.streaming!==!1&&(Be.delete(W.id),at.delete(W.id),W.streaming=!1,f(W));else{let j=B!=null&&B!=="";if(j||G){let ae=xe();G&&(ae.stopReason=G),j?ke(ae,B):(ae.streaming=!1,f(ae))}}continue}}else if(Q==="execution_start")ye=v.kind==="flow"?"flow":"agent",bt=!0,ye==="agent"&&(ne={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Fe(v.startedAt)});else if(Q==="turn_start"){let S=typeof v.iteration=="number"?v.iteration:ie;if(S!==ie){if(ne&&(ne.currentIteration=S),Se==="separate"&&S>1){let k=b;k&&(k.streaming=!1,f(k),De.set(S-1,k),b=null)}ie=S}F=typeof v.id=="string"?v.id:null,C=null}else if(Q==="tool_input_delta"){let S=v.toolCallId??J.lastId;if(S){let k=U.get(S);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(v.delta??""),f(k))}}else{if(Q==="tool_input_complete")continue;if(Q==="turn_complete"){let S=v.stopReason,k=b??C;if(S&&k!==null){let W=v.id;(!W||k.agentMetadata?.turnId===W)&&(k.stopReason=S,f(k))}F===v.id&&(F=null)}else if(Q==="media_start"){let S=String(v.id);pe.set(S,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(Q==="media_delta"){let S=pe.get(String(v.id));S&&typeof v.delta=="string"&&S.parts.push(v.delta)}else if(Q==="media_complete"){let S=String(v.id),k=pe.get(S);pe.delete(S);let W=(typeof v.mediaType=="string"?v.mediaType:void 0)??k?.mediaType??"application/octet-stream",G=typeof v.data=="string"?v.data:void 0,B=typeof v.url=="string"?v.url:k&&k.parts.length>0?k.parts.join(""):void 0,j=null;if(G)j={type:"media",data:G,mediaType:W};else if(B){let lt=W.toLowerCase();j={type:lt==="image"||lt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:W}}let ae=v.toolCallId??k?.toolCallId,tt=j?[j]:[],Me=[];for(let lt of tt){if(!lt||typeof lt!="object")continue;let q=lt,ze=typeof q.type=="string"?q.type:void 0,Re=typeof q.mediaType=="string"?q.mediaType.toLowerCase():"",We=null,Le="";if(ze==="media"){let Je=typeof q.data=="string"?q.data:void 0;if(!Je)continue;Le=Re.length>0?Re:"application/octet-stream",We=`data:${Le};base64,${Je}`}else if(ze==="image-url"){let Je=typeof q.url=="string"?q.url:void 0;if(!Je)continue;Le=Re,We=Je}else if(ze==="file-url"){let Je=typeof q.url=="string"?q.url:void 0;if(!Je)continue;Le=Re,We=Je}else continue;if(We)if(ze==="image-url"||Le.startsWith("image/"))Me.push({type:"image",image:We,...Le.includes("/")?{mimeType:Le}:{}});else if(Le.startsWith("audio/"))Me.push({type:"audio",audio:We,mimeType:Le});else if(Le.startsWith("video/"))Me.push({type:"video",video:We,mimeType:Le});else{let Je=Le||"application/octet-stream";Me.push({type:"file",data:We,mimeType:Je,filename:Tg(Je)})}}if(Me.length>0){let lt=c(),q=ae,Re={id:`agent-media-${typeof q=="string"&&q.length>0?`${q}-${lt}`:String(lt)}`,role:"assistant",content:"",contentParts:Me,createdAt:new Date().toISOString(),streaming:!1,sequence:lt,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ie}};f(Re);let We=b;We&&(We.streaming=!1,f(We)),b=null,P.current=null}}else if(Q==="execution_complete"){let S=v.kind??ye;S==="agent"&&ne&&(ne.status=v.success?"complete":"error",ne.completedAt=Fe(v.completedAt),ne.stopReason=v.stopReason);let k=b;k&&(S==="flow"&&k.streaming!==!1?ke(k):(k.streaming=!1,f(k)),b=null),M=null,T="",Et=null,n({type:"status",status:"idle",terminal:!0})}else if(Q==="execution_error"){let S=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(Q!=="ping"){if(Q==="approval_start"){let S=v.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:ne?.agentId??"virtual",executionId:v.executionId??ne?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(k)}else if(Q==="step_await"&&v.awaitReason==="approval_required"){let S=v.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:ne?.agentId??"virtual",executionId:v.executionId??ne?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(k)}else if(Q==="approval_complete"){let S=v.approvalId;if(S){let W={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:v.decision??"approved",agentId:ne?.agentId??"virtual",executionId:v.executionId??ne?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(W)}}else if(Q==="artifact_start"||Q==="artifact_delta"||Q==="artifact_update"||Q==="artifact_complete"){if(Q==="artifact_start"){let S=v.artifactType,k=String(v.id),W=typeof v.title=="string"?v.title:void 0,G=v.file,B;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(B={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:k,artifactType:S,title:W,component:typeof v.component=="string"?v.component:void 0,...B?{file:B}:{}});let j=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(ue.set(k,{markdown:"",title:W,file:B,...j?{props:j}:{}}),!ve.has(k)){ve.add(k);let ae=ko(this.config.features?.artifacts,S),tt=typeof v.component=="string"?v.component:void 0,Me={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ta(ae,{artifactId:k,title:W,artifactType:S,status:"streaming",...B?{file:B}:{},...tt?{component:tt}:{}})};be.set(k,Me),f(Me)}}else if(Q==="artifact_delta"){let S=String(v.id),k=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:S,artDelta:k});let W=ue.get(S);W&&(W.markdown+=k)}else if(Q==="artifact_update"){let S=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:S,component:typeof v.component=="string"?v.component:void 0});let k=ue.get(String(v.id));k&&(k.props={...k.props??{},...S})}else if(Q==="artifact_complete"){let S=String(v.id);n({type:"artifact_complete",id:S});let k=be.get(S);if(k){k.streaming=!1;try{let W=JSON.parse(k.rawContent??"{}");if(W.props){W.props.status="complete";let G=ue.get(S);G?.markdown&&(W.props.markdown=G.markdown),G?.file&&(W.props.file=G.file),W.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(W.props.componentProps=G.props)}k.rawContent=JSON.stringify(W)}catch{}ue.delete(S),f(k),be.delete(S)}}}else if(Q==="transcript_insert"){let S=v.message;if(!S||typeof S!="object")continue;let k=String(S.id??`msg-${c()}`),W=S.role,B={id:k,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:c()};if(f(B),B.rawContent)try{let ae=JSON.parse(B.rawContent)?.props?.artifactId;typeof ae=="string"&&ve.add(ae)}catch{}b=null,P.current=null,Be.delete(k),at.delete(k)}else if(Q==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let S=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(S)});let k=b;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}else if(Q==="step_error"||Q==="dispatch_error"||Q==="flow_error"){let S=null;if(v.error instanceof Error)S=v.error;else if(Q==="dispatch_error"){let k=v.message??v.error;k!=null&&k!==""&&(S=new Error(String(k)))}else{let k=v.error;typeof k=="string"&&k!==""?S=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(S=new Error(String(k.message??k)))}if(S){n({type:"error",error:S});let k=b;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:E,value:Q}=await s.read();if(E)break;l+=a.decode(Q,{stream:!0});let v=l.split(`
|
|
12
12
|
|
|
13
|
-
`);l=
|
|
14
|
-
`),tt="message",Qe="",ht=null;for(let le of Re)le.startsWith("event:")?tt=le.replace("event:","").trim():le.startsWith("data:")?Qe+=le.replace("data:","").trim():le.startsWith("id:")&&(ht=le.slice(3).trim());let ge=()=>{ht!==null&&ht!==""&&t({type:"cursor",id:ht})};if(!Qe){ge();continue}let H;try{H=JSON.parse(Qe)}catch(le){t({type:"error",error:le instanceof Error?le:new Error("Failed to parse chat stream payload")});continue}let be=tt!=="message"?tt:(fr=H.type)!=null?fr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,be,H),this.parseSSEEvent){S.current=b;let le=await this.handleCustomSSEEvent(H,t,S,m,u,B);if(S.current&&S.current!==b&&(b=S.current),le){ge();continue}}it.push({payloadType:be,payload:H}),je(),ge()}}je()}};function Ra(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function gs(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ha="[Image]";function _i(n){return{type:"text",text:n}}var Qu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],oh=["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"],Kr=[...Qu,...oh];function sh(n){return Qu.includes(n)||n.startsWith("image/")}function Ba(n){return sh(n.type)}async function Xu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ba(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function Ju(n,e=Kr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function ah(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Yu(n,e){let t=ah(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||t||"FILE"}var Zu=16e3,ih=24e3,lh=4096,ch=1380533830;function dh(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===ch?new Uint8Array(n,44):new Uint8Array(n)}function ph(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Xs=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,l,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(l=this.config)==null?void 0:l.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Zu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:Zu});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new uu(ih);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${ph(r)}/ws/agents/${encodeURIComponent(e)}/voice`,b=new WebSocket(m,["runtype.bearer",t]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,b,o))},b.onmessage=w=>this.handleMessage(w,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let S=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(lh,1,1);this.processor=a,a.onaudioprocess=l=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let g=Math.max(-1,Math.min(1,d[u]));c[u]=g<0?g*32768:g*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=dh(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Uo=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var l;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((l=this.config)!=null&&l.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function fs(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Xs(n.runtype);case"browser":if(!Uo.isSupported())throw new Error("Browser speech recognition not supported");return new Uo(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function em(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return fs({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return fs({type:"runtype",runtype:n.runtype});if(Uo.isSupported())return fs({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function $i(n){try{return em(n),!0}catch{return!1}}function Da(n){var t;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var hs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let l=s.find(d=>d.name===e.voice);l&&(o.voice=l)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Da(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var l;return(l=t.onEnd)==null?void 0:l.call(t)},o.onerror=l=>{var c,u;let d=l.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(u=t.onError)==null||u.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var l;r.speak(o),(l=t.onStart)==null||l.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Js=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function Ui(n){if(!n)return"";let e=uh(n);return tm(e!==null?e:n)}function uh(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function tm(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);l=v.pop()??"";for(let S of v){let k=S.split(`
|
|
14
|
+
`),W="message",G="",B=null;for(let Me of k)Me.startsWith("event:")?W=Me.replace("event:","").trim():Me.startsWith("data:")?G+=Me.replace("data:","").trim():Me.startsWith("id:")&&(B=Me.slice(3).trim());let j=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!G){j();continue}let ae;try{ae=JSON.parse(G)}catch(Me){n({type:"error",error:Me instanceof Error?Me:new Error("Failed to parse chat stream payload")});continue}let tt=W!=="message"?W:ae.type??"message";if(this.onSSEEvent?.(tt,ae),this.parseSSEEvent){P.current=b;let Me=await this.handleCustomSSEEvent(ae,n,P,f,c,H);if(P.current&&P.current!==b&&(b=P.current),Me){j();continue}}it.push({payloadType:tt,payload:ae}),Ie(),j()}}Ie()}};function da(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function or(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var pa="[Image]";function Ld(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function rr(t){return{type:"text",text:t}}var Pd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],kg=["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"],Fn=[...Pd,...kg];function Lg(t){return Pd.includes(t)||t.startsWith("image/")}function ua(t){return Lg(t.type)}async function Id(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ua(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Rd(t,e=Fn,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Pg(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Wd(t,e){let n=Pg(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var Bd=16e3,Ig=24e3,Rg=4096,Wg=1380533830;function Bg(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Wg?new Uint8Array(t,44):new Uint8Array(t)}function Hg(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Yr=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Bd,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:Bd});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Uc(Ig);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=`${Hg(o)}/ws/agents/${encodeURIComponent(e)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Rg,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=Bg(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function sr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Yr(t.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function Hd(t){if(t?.type==="custom"&&t.custom)return sr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return sr({type:"runtype",runtype:t.runtype});if(Io.isSupported())return sr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zi(t){try{return Hd(t),!0}catch{return!1}}function fa(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var ar=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):fa(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Zr=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Ui(t){if(!t)return"";let e=Dg(t);return Dd(e!==null?e:t)}function Dg(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Dd(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),e=e.replace(/\n{2,}/g,`
|
|
16
|
-
`),e.trim()}var
|
|
16
|
+
`),e.trim()}var Nd=null;var ji=()=>Nd?Nd():import("./runtype-tts-entry-UJAEF7NZ.js");var Ng=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Fg(t,e){return Ng.some(n=>t[n]!==e[n])}function Vi(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
17
17
|
|
|
18
|
-
_Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]}),rm=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,om=n=>cs(n)||n===Vr,Na=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Js(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,l,d,c,u,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(cs(h.name)||h.name===Vr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(l=e.message.agentMetadata.iteration)!=null?l:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,l,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.agentId)!=null?d:(l=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:l.agentId)!=null?c:this.config.agentId;!t||!r||!this.config.clientToken||zi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return $i((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,l,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=hs.isSupported()?new hs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(l=e.agentId)!=null?l:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&u&&g)return zi().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:b})=>{let w=new m({host:c,agentId:u,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new b(w,t,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=fs(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(l=>{l.provider!=="runtype"&&l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((l,d,c)=>{if(l==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(l=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,l)}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(l=>{var d,c;this.voiceStatus=l,this.voiceActive=l==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,l)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,l,d,c,u,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(l=(a=e.runtype)==null?void 0:a.clientToken)!=null?l:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!gh(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Qs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:l,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:g}=e,m={id:a!=null?a:t==="user"?Ra():t==="assistant"?gs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:l!=null?l:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:l,id:d,createdAt:c,sequence:u,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?Ra():o==="assistant"?gs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:l,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,u,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Ra(),s=gs();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Ha,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let w=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!w){let S=qi(b,this.config.errorMessage);if(S){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(b instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,b):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(b))))}}async continueConversation(){var o,s,a,l,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=gs();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=qi(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(l=this.callbacks).onError)==null||d.call(l,new Error(String(c))))}}async connectStream(e,t){var s,a,l;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(l=(a=this.callbacks).onError)==null||l.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(l=>{this.webMcpApprovalResolvers.set(r,l)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var u,g,h,m,b;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),l={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let S=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}S=w.body}else w instanceof ReadableStream&&(S=w);S?await this.connectStream(S,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(w){let S=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(m=this.callbacks).onError)==null||b.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,g,h,m,b,w,S,B,T,I,R,P;let r=this.messages.find(A=>A.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(b=(m=this.callbacks).onError)==null||b.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let A=(w=e.toolCall)==null?void 0:w.args,W=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(W.length===1){let z=typeof((S=W[0])==null?void 0:S.question)=="string"?W[0].question:"";z&&(a={[z]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof t=="string"?t:Object.entries(t).map(([W,z])=>`${W}: ${Array.isArray(z)?z.join(", "):z}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((W,z)=>{let $=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!$)return;let k=A[$],U=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${l}-${z}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${z}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:t});if(!A.ok){let W=await A.json().catch(()=>null);throw new Error((I=W==null?void 0:W.error)!=null?I:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let W=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(P=(R=this.callbacks).onError)==null||P.call(R,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let l=this.webMcpEpoch;queueMicrotask(()=>{l===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==Vr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,u,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var P,A,W,z,$,k,U;let m=(P=h.toolCall)==null?void 0:P.name,b=(A=h.toolCall)==null?void 0:A.id;if(!m||!b)return null;let w=`${e}:${b}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let S=this.markWebMcpToolRunning(h),B=(z=(W=h.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?z:m;if(m===Vr)return{dedupeKey:w,resumeKey:B,output:Di(),toolMessage:h,startedAt:S,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let I=this.client.executeWebMcpToolCall(m,($=h.toolCall)==null?void 0:$.args,T.signal),R;if(!I)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await I}catch(F){let te=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return te||(U=(k=this.callbacks).onError)==null||U.call(k,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(h,Ys(te?"Aborted by cancel()":rm(F)),S),this.webMcpInflightKeys.delete(w),null}return T.signal.aborted?(this.markWebMcpToolComplete(h,Ys("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:R,toolMessage:h,startedAt:S,completedAt:Date.now()}})),l=[];try{if(l=a.filter(b=>b!==null),l.length===0)return;let h={};for(let b of l)h[b.resumeKey]=b.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let b=await m.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${m.status}`)}for(let b of l)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Vr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,h instanceof Error?h:new Error(String(h)));else for(let b of l)this.markWebMcpToolComplete(b.toolMessage,Ys("Aborted by cancel()"),b.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var b,w,S,B,T,I,R,P,A,W,z,$;let t=(b=e.agentMetadata)==null?void 0:b.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(S=e.toolCall)==null?void 0:S.id;if(!t){(T=(B=this.callbacks).onError)==null||T.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(U){(R=(I=this.callbacks).onError)==null||R.call(I,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let c=r===Vr,u=(P=e.toolCall)==null?void 0:P.args,g=c?null:this.client.executeWebMcpToolCall(r,u,d),h="execute",m=a;try{let k;if(c?k=Di():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Ys("Aborted by cancel()"),a);return}let U=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;h="resume",await this.resumeWithToolOutput(t,U,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,k,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let U=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(h==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(e,Ys(U||d.aborted?"Aborted by cancel()":rm(k)),a),U||($=(z=this.callbacks).onError)==null||$.call(z,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,l;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(l=o==null?void 0:o.onHttpOk)==null||l.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-U77QFUR7.js").then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>qi(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=gs(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Ui(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Da(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Ui(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var u,g,h,m,b,w,S,B,T,I,R,P,A,W,z;if(s!==r)return o;let a={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let $=o.approval,k=t.approval;a.approval={...$,...k,executionId:k.executionId||$.executionId,toolName:k.toolName||$.toolName,description:k.description||$.description,toolType:(m=k.toolType)!=null?m:$.toolType,reason:(b=k.reason)!=null?b:$.reason,parameters:(w=k.parameters)!=null?w:$.parameters}}let l=(S=t.toolCall)==null?void 0:S.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(T=t.toolCall)==null?void 0:T.id;if(l&&om(l)&&d&&c&&((I=t.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let $=`${d}:${c}`,k=this.webMcpInflightKeys.has($),U=this.webMcpResolvedKeys.has($),F=(R=o.toolCall)==null?void 0:R.name,te=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&F!==void 0&&om(F)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(k||U||te)&&(a.agentMetadata={...(z=a.agentMetadata)!=null?z:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,l=(c=r.sequence)!=null?c:0;return a!==l?a-l:t.id.localeCompare(r.id)})}};import{Activity as fh,ArrowDown as hh,ArrowUp as yh,ArrowUpRight as bh,Bot as vh,ChevronDown as wh,ChevronUp as xh,ChevronRight as Ch,ChevronLeft as Ah,Check as Sh,Clipboard as Th,ClipboardCopy as Mh,Copy as Eh,File as kh,FileCode as Lh,FileSpreadsheet as Ph,FileText as Ih,ImagePlus as Wh,Loader as Rh,LoaderCircle as Hh,Mic as Bh,Paperclip as Dh,RefreshCw as Nh,Search as Fh,Send as Oh,ShieldAlert as _h,ShieldCheck as $h,ShieldX as Uh,Square as zh,ThumbsDown as qh,ThumbsUp as jh,Upload as Vh,Volume2 as Kh,X as Gh,User as Qh,Mail as Xh,Phone as Jh,Calendar as Yh,Clock as Zh,Building as ey,MapPin as ty,Lock as ny,Key as ry,CreditCard as oy,AtSign as sy,Hash as ay,Globe as iy,Link as ly,CircleCheck as cy,CircleX as dy,TriangleAlert as py,Info as uy,Ban as my,Shield as gy,ArrowLeft as fy,ArrowRight as hy,ExternalLink as yy,Ellipsis as by,EllipsisVertical as vy,Menu as wy,House as xy,Plus as Cy,Minus as Ay,Pencil as Sy,Trash as Ty,Trash2 as My,Save as Ey,Download as ky,Share as Ly,Funnel as Py,Settings as Iy,RotateCw as Wy,Maximize as Ry,Minimize as Hy,ShoppingCart as By,ShoppingBag as Dy,Package as Ny,Truck as Fy,Tag as Oy,Gift as _y,Receipt as $y,Wallet as Uy,Store as zy,DollarSign as qy,Percent as jy,Play as Vy,Pause as Ky,VolumeX as Gy,Camera as Qy,Image as Xy,Film as Jy,Headphones as Yy,MessageCircle as Zy,MessageSquare as eb,Bell as tb,Heart as nb,Star as rb,Eye as ob,EyeOff as sb,Bookmark as ab,CalendarDays as ib,History as lb,Timer as cb,Folder as db,FolderOpen as pb,Files as ub,Sparkles as mb,Zap as gb,Sun as fb,Moon as hb,Flag as yb,Monitor as bb,Smartphone as vb}from"lucide";var wb={activity:fh,"arrow-down":hh,"arrow-up":yh,"arrow-up-right":bh,bot:vh,"chevron-down":wh,"chevron-up":xh,"chevron-right":Ch,"chevron-left":Ah,check:Sh,clipboard:Th,"clipboard-copy":Mh,copy:Eh,file:kh,"file-code":Lh,"file-spreadsheet":Ph,"file-text":Ih,"image-plus":Wh,loader:Rh,"loader-circle":Hh,mic:Bh,paperclip:Dh,"refresh-cw":Nh,search:Fh,send:Oh,"shield-alert":_h,"shield-check":$h,"shield-x":Uh,square:zh,"thumbs-down":qh,"thumbs-up":jh,upload:Vh,"volume-2":Kh,x:Gh,user:Qh,mail:Xh,phone:Jh,calendar:Yh,clock:Zh,building:ey,"map-pin":ty,lock:ny,key:ry,"credit-card":oy,"at-sign":sy,hash:ay,globe:iy,link:ly,"circle-check":cy,"circle-x":dy,"triangle-alert":py,info:uy,ban:my,shield:gy,"arrow-left":fy,"arrow-right":hy,"external-link":yy,ellipsis:by,"ellipsis-vertical":vy,menu:wy,house:xy,plus:Cy,minus:Ay,pencil:Sy,trash:Ty,"trash-2":My,save:Ey,download:ky,share:Ly,funnel:Py,settings:Iy,"rotate-cw":Wy,maximize:Ry,minimize:Hy,"shopping-cart":By,"shopping-bag":Dy,package:Ny,truck:Fy,tag:Oy,gift:_y,receipt:$y,wallet:Uy,store:zy,"dollar-sign":qy,percent:jy,play:Vy,pause:Ky,"volume-x":Gy,camera:Qy,image:Xy,film:Jy,headphones:Yy,"message-circle":Zy,"message-square":eb,bell:tb,heart:nb,star:rb,eye:ob,"eye-off":sb,bookmark:ab,"calendar-days":ib,history:lb,timer:cb,folder:db,"folder-open":pb,files:ub,sparkles:mb,zap:gb,sun:fb,moon:hb,flag:yb,monitor:bb,smartphone:vb},he=(n,e=24,t="currentColor",r=2)=>{let o=wb[n];return o?xb(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function xb(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Fa={allowedTypes:Kr,maxFileSize:10*1024*1024,maxFiles:4};function Cb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ab(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var Zs=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Fa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Fa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Fa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Fa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,l,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let u=Ju(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Xu(c),h=Ba(c)?URL.createObjectURL(c):null,m={id:Cb(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(l=this.config).onAttachmentsChange)==null||d.call(l,this.getAttachments())}}removeAttachment(e){var s,a,l;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(l=(a=this.config).onAttachmentsChange)==null||l.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Ba(e.file),r=v("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=v("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=Ab(e.file.type),d=he(l,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=v("span");c.textContent=Yu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var sm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function ea(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];sm(s)&&sm(o)?t[r]=ea(s,o):t[r]=o}return t}var Gr="min(440px, calc(100vw - 24px))",im="440px",Sb={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:Gr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Ht={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Sb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function am(n,e){if(!(!n&&!e))return n?e?ea(n,e):n:e}function lm(n){var e,t,r,o,s,a,l,d,c,u,g,h,m,b,w,S,B,T,I,R,P;return n?{...Ht,...n,theme:am(Ht.theme,n.theme),darkTheme:am(Ht.darkTheme,n.darkTheme),launcher:{...Ht.launcher,...n.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...n.copy},sendButton:{...Ht.sendButton,...n.sendButton},statusIndicator:{...Ht.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...n.voiceRecognition},features:(()=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie;let A=(ne=Ht.features)==null?void 0:ne.artifacts,W=(re=n.features)==null?void 0:re.artifacts,z=(ce=Ht.features)==null?void 0:ce.scrollToBottom,$=(Ce=n.features)==null?void 0:Ce.scrollToBottom,k=(_e=Ht.features)==null?void 0:_e.scrollBehavior,U=(V=n.features)==null?void 0:V.scrollBehavior,F=(X=Ht.features)==null?void 0:X.streamAnimation,te=(Ae=n.features)==null?void 0:Ae.streamAnimation,Ee=(J=Ht.features)==null?void 0:J.askUserQuestion,de=(ie=n.features)==null?void 0:ie.askUserQuestion,Y=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Le=z===void 0&&$===void 0?void 0:{...z,...$},Pe=k===void 0&&U===void 0?void 0:{...k,...U},ae=F===void 0&&te===void 0?void 0:{...F,...te},fe=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ht.features,...n.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...Y!==void 0?{artifacts:Y}:{},...ae!==void 0?{streamAnimation:ae}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ht.layout,...n.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(l=n.layout)==null?void 0:l.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(b=Ht.layout)==null?void 0:b.messages)==null?void 0:w.timestamp,...(B=(S=n.layout)==null?void 0:S.messages)==null?void 0:B.timestamp}},slots:{...(T=Ht.layout)==null?void 0:T.slots,...(I=n.layout)==null?void 0:I.slots}},markdown:{...Ht.markdown,...n.markdown,options:{...(R=Ht.markdown)==null?void 0:R.options,...(P=n.markdown)==null?void 0:P.options}},messageActions:{...Ht.messageActions,...n.messageActions}}:Ht}var Tb={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"}},Mb={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"}},Eb={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Gr,maxWidth:im,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ys(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ys(n,r):r}function cm(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let l=`${o}.${s}`;if(typeof a=="string"){let d=ys(n,a);d!==void 0&&(e[l]={path:l,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,l)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function kb(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function dm(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=dm(s,o):t[r]=o}return t}function Lb(n,e){return e?dm(n,e):n}function zo(n,e={}){var o,s,a,l,d,c,u,g,h,m,b,w,S;let t={palette:Tb,semantic:Mb,components:Eb},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(l=n==null?void 0:n.palette)==null?void 0:l.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(u=n==null?void 0:n.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(b=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:b.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(S=n==null?void 0:n.semantic)==null?void 0:S.typography}},components:Lb(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=kb(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function pm(n){var w,S,B,T,I,R,P,A,W,z,$,k,U,F,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue,Q,it,je,Te,we,Ye,qt,ye,pe,Cn,Ct,hn,gr,fr,Ue,M,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Yt,hr,Wr,nr,rr,Qr,jt,or,Rr,Hn,Pn,Bn,sr,yr,Xr,jn,Jr,At,br,vr,Hr,ar,yt,Co,wr,Ao,In,Qo,Yr,Br,Zr,eo,So,To,to,wt,Dn,Nn,An,St,Vn,Kn,Fn,no;let e=cm(n),t={};for(let[xe,Dr]of Object.entries(e)){let Gn=xe.replace(/\./g,"-");t[`--persona-${Gn}`]=Dr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(S=t["--persona-semantic-colors-secondary"])!=null?S:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(T=t["--persona-semantic-colors-surface"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(A=t["--persona-semantic-colors-text-muted"])!=null?A:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(z=t["--persona-semantic-colors-border"])!=null?z:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=($=t["--persona-semantic-colors-divider"])!=null?$:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(k=t["--persona-components-voice-recording-indicator"])!=null?k:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(U=t["--persona-components-voice-recording-background"])!=null?U:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-surface"],t["--persona-approval-border"]=(de=t["--persona-components-approval-requested-border"])!=null?de:t["--persona-border"],t["--persona-approval-text"]=(Y=t["--persona-components-approval-requested-text"])!=null?Y:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Le=t["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Pe=t["--persona-components-approval-approve-background"])!=null?Pe:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ae=t["--persona-components-approval-deny-background"])!=null?ae:t["--persona-container"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ne=t["--persona-components-attachment-image-border"])!=null?ne:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ce=t["--persona-semantic-typography-fontSize"])!=null?ce:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ce=t["--persona-semantic-typography-fontWeight"])!=null?Ce:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(_e=t["--persona-semantic-typography-lineHeight"])!=null?_e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(X=t["--persona-palette-radius-md"])!=null?X:"0.375rem",t["--persona-radius-lg"]=(Ae=t["--persona-palette-radius-lg"])!=null?Ae:"0.5rem",t["--persona-radius-xl"]=(J=t["--persona-palette-radius-xl"])!=null?J:"0.75rem",t["--persona-radius-full"]=(ie=t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-launcher-radius"]=(Je=(Se=t["--persona-components-launcher-borderRadius"])!=null?Se:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-launcher-bg"]=(et=t["--persona-components-launcher-background"])!=null?et:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ft=t["--persona-components-launcher-border"])!=null?ft:t["--persona-border"],t["--persona-button-primary-bg"]=(rt=t["--persona-components-button-primary-background"])!=null?rt:t["--persona-primary"],t["--persona-button-primary-fg"]=(ue=t["--persona-components-button-primary-foreground"])!=null?ue:t["--persona-text-inverse"],t["--persona-button-radius"]=(it=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-panel-radius"]=(Te=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?Te:"0.75rem",t["--persona-panel-border"]=(we=t["--persona-components-panel-border"])!=null?we:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(qt=(Ye=t["--persona-components-panel-shadow"])!=null?Ye:t["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(ye=t["--persona-components-launcher-shadow"])!=null?ye:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(Cn=(pe=t["--persona-components-input-borderRadius"])!=null?pe:t["--persona-radius-lg"])!=null?Cn:"0.5rem",t["--persona-message-user-radius"]=(hn=(Ct=t["--persona-components-message-user-borderRadius"])!=null?Ct:t["--persona-radius-lg"])!=null?hn:"0.5rem",t["--persona-message-assistant-radius"]=(fr=(gr=t["--persona-components-message-assistant-borderRadius"])!=null?gr:t["--persona-radius-lg"])!=null?fr:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(M=t["--persona-components-header-border"])!=null?M:t["--persona-divider"],t["--persona-header-icon-bg"]=(me=t["--persona-components-header-iconBackground"])!=null?me:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ke=t["--persona-components-header-titleForeground"])!=null?ke:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Re=t["--persona-components-header-subtitleForeground"])!=null?Re:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(tt=t["--persona-components-header-actionIconForeground"])!=null?tt:t["--persona-muted"];let r=(Qe=n.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=n.components)==null?void 0:ht.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(H=t["--persona-components-introCard-borderRadius"])!=null?H:"1rem",t["--persona-intro-card-padding"]=(be=t["--persona-components-introCard-padding"])!=null?be:"1.5rem",t["--persona-intro-card-shadow"]=(gt=(le=o==null?void 0:o.shadow)!=null?le:t["--persona-components-introCard-shadow"])!=null?gt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ke=t["--persona-components-input-background"])!=null?Ke:t["--persona-surface"],t["--persona-input-placeholder"]=(Lt=t["--persona-components-input-placeholder"])!=null?Lt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Et=t["--persona-components-message-user-background"])!=null?Et:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Rt=t["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Qt=t["--persona-components-message-assistant-background"])!=null?Qt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ft=t["--persona-components-message-assistant-text"])!=null?Ft:t["--persona-text"],t["--persona-message-assistant-border"]=(Yt=t["--persona-components-message-assistant-border"])!=null?Yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(hr=t["--persona-components-message-assistant-shadow"])!=null?hr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(nr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?nr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Qr=(rr=t["--persona-components-scrollToBottom-foreground"])!=null?rr:t["--persona-button-primary-fg"])!=null?Qr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(jt=t["--persona-components-scrollToBottom-border"])!=null?jt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(or=t["--persona-components-scrollToBottom-size"])!=null?or:"40px",t["--persona-scroll-to-bottom-radius"]=(Pn=(Hn=(Rr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Rr:t["--persona-button-radius"])!=null?Hn:t["--persona-radius-full"])!=null?Pn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(sr=(Bn=t["--persona-components-scrollToBottom-shadow"])!=null?Bn:t["--persona-palette-shadows-sm"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(yr=t["--persona-components-scrollToBottom-padding"])!=null?yr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Xr=t["--persona-components-scrollToBottom-gap"])!=null?Xr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Jr=(jn=t["--persona-components-scrollToBottom-fontSize"])!=null?jn:t["--persona-palette-typography-fontSize-sm"])!=null?Jr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(At=t["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",t["--persona-tool-bubble-shadow"]=(br=t["--persona-components-toolBubble-shadow"])!=null?br:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(vr=t["--persona-components-reasoningBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Hr=t["--persona-components-composer-shadow"])!=null?Hr:"none",t["--persona-md-inline-code-bg"]=(ar=t["--persona-components-markdown-inlineCode-background"])!=null?ar:t["--persona-container"],t["--persona-md-inline-code-color"]=(yt=t["--persona-components-markdown-inlineCode-foreground"])!=null?yt:t["--persona-text"],t["--persona-md-link-color"]=(wr=(Co=t["--persona-components-markdown-link-foreground"])!=null?Co:t["--persona-accent"])!=null?wr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let l=t["--persona-components-markdown-heading-h2-fontSize"];l&&(t["--persona-md-h2-size"]=l);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Ao=t["--persona-components-markdown-codeBlock-background"])!=null?Ao:t["--persona-container"],t["--persona-md-code-block-border-color"]=(In=t["--persona-components-markdown-codeBlock-borderColor"])!=null?In:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Qo=t["--persona-components-markdown-codeBlock-textColor"])!=null?Qo:"inherit",t["--persona-md-table-header-bg"]=(Yr=t["--persona-components-markdown-table-headerBackground"])!=null?Yr:t["--persona-container"],t["--persona-md-table-border-color"]=(Br=t["--persona-components-markdown-table-borderColor"])!=null?Br:t["--persona-border"],t["--persona-md-hr-color"]=(Zr=t["--persona-components-markdown-hr-color"])!=null?Zr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(eo=t["--persona-components-markdown-blockquote-borderColor"])!=null?eo:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(So=t["--persona-components-markdown-blockquote-background"])!=null?So:"transparent",t["--persona-md-blockquote-text-color"]=(To=t["--persona-components-markdown-blockquote-textColor"])!=null?To:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(to=t["--persona-components-collapsibleWidget-container"])!=null?to:t["--persona-surface"],t["--cw-surface"]=(wt=t["--persona-components-collapsibleWidget-surface"])!=null?wt:t["--persona-surface"],t["--cw-border"]=(Dn=t["--persona-components-collapsibleWidget-border"])!=null?Dn:t["--persona-border"],t["--persona-message-border"]=(Nn=t["--persona-components-message-border"])!=null?Nn:t["--persona-border"];let u=n.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=u==null?void 0:u.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let b=u==null?void 0:u.artifact;if(b!=null&&b.toolbar){let xe=b.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(An=t["--persona-dropdown-bg"])!=null?An:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(St=t["--persona-dropdown-border"])!=null?St:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Kn=t["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(b!=null&&b.tab){let xe=b.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(b!=null&&b.pane){let xe=b.pane;if(xe.toolbarBackground){let Dr=(no=ys(n,xe.toolbarBackground))!=null?no:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Dr}}return t}var Pb={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"}}},um=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},ji=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ib=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":ji()},Wb=n=>Ib(n),Rb=n=>zo(n),Hb=n=>{var t;let e=zo(void 0,{validate:!1});return zo({...n,palette:{...e.palette,colors:{...Pb.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Oa=n=>{let e=Wb(n),t=um(n==null?void 0:n.theme),r=um(n==null?void 0:n.darkTheme);return e==="dark"?Hb(ea(t!=null?t:{},r!=null?r:{})):Rb(t)},Bb=n=>pm(n),bs=(n,e)=>{let t=Oa(e),r=Bb(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},mm=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(ji())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(ji());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};import{Idiomorph as Db}from"idiomorph";var _a=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Db.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,l;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(l=s.textContent)!=null?l:"";if(d!==c)return}return!1}}}}})};var gm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var $a={index:-1,draft:""};function fm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let l=t.length-1;return{handled:!0,value:t[l],state:{index:l,draft:r}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:t[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let l=s.index+1;return{handled:!0,value:t[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...$a}}}function hm(n,e){var t,r,o,s,a,l,d,c,u,g,h,m,b,w,S,B,T,I,R,P,A,W,z,$,k,U,F,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(l=n.rawContent)==null?void 0:l.length)!=null?d:0,(u=(c=n.llmContent)==null?void 0:c.length)!=null?u:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(b=(m=n.toolCall)==null?void 0:m.status)!=null?b:"",(S=(w=n.toolCall)==null?void 0:w.name)!=null?S:"",(I=(T=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:T.length)!=null?I:0,(W=(A=(P=(R=n.toolCall)==null?void 0:R.chunks)==null?void 0:P[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((z=n.toolCall)==null?void 0:z.args)=="string"?n.toolCall.args.length:($=n.toolCall)!=null&&$.args?JSON.stringify(n.toolCall.args).length:0,(F=(U=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:U.length)!=null?F:0,(Y=(de=(Ee=(te=n.reasoning)==null?void 0:te.chunks)==null?void 0:Ee[n.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Y:0,(fe=(ae=(Pe=(Le=n.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[n.reasoning.chunks.length-1])==null?void 0:ae.slice(-32))!=null?fe:"",(re=(ne=n.contentParts)==null?void 0:ne.length)!=null?re:0,(ce=n.stopReason)!=null?ce:"",e].join("\0")}function ym(){return new Map}function bm(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function vm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function wm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Ua(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ir(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function vo(n,e){return Ir(n)-n.scrollTop<=e}function za(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function qa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function xm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Cm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Am(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var en={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},wn=1e5,wo=wn+1;var ta={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Nb=["pre","code","a","script","style"],ja=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ta.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ta.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ta.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ta.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ta.buffer}},Fb=[{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"}],Tm=new Map;for(let n of Fb)Tm.set(n.name,n);var vs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Tm.get(n))!=null?r:null},Va=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
19
|
-
`);return s<0?"":n.slice(0,s)}return n},Ob=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},_b=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Vi=/\s/,$b=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Ub=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),l=0;for(;l<s.length;)if(Vi.test(s[l])){let c=l;for(;c<s.length&&Vi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(l,c))),l=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=l;for(;u<s.length&&!Vi.test(s[u]);)c.appendChild(Ob(r,s[u],e,t.value)),t.value+=1,u+=1;a.appendChild(c),l=u}o.replaceChild(a,n)},zb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(_b(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},na=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:Nb).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)$b(d,s)||l.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},u=e==="char"?Ub:zb;for(let m of l)u(m,t,c);return o.innerHTML},Ka=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ra=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Sm=new WeakMap,qb=(n,e)=>{var s;if(!n.styles)return;let t=Sm.get(e);if(t||(t=new Set,Sm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Ki=new WeakMap,jb=(n,e)=>{if(!n.onAttach)return;let t=Ki.get(e);if(t||(t=new Map,Ki.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Mm=n=>{let e=Ki.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Ga=(n,e)=>{qb(n,e),jb(n,e)};function Gi(n,e=wn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var oa=0,xo=null;function Qi(n=document){var t;if(oa++,oa===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;xo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,oa=Math.max(0,oa-1),oa===0&&xo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=xo.originalOverflow,o.style.position=xo.originalPosition,o.style.top=xo.originalTop,o.style.width=xo.originalWidth,s.scrollTo(0,xo.scrollY),xo=null}}}var sa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},fn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},aa=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},ur=n=>{var t,r,o,s,a,l;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:sa.side,width:(o=e==null?void 0:e.width)!=null?o:sa.width,animate:(s=e==null?void 0:e.animate)!=null?s:sa.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:sa.reveal,maxHeight:(l=e==null?void 0:e.maxHeight)!=null?l:sa.maxHeight}};var mr={"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 Vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Qa=(n,e={})=>{var S,B,T,I,R,P;let{showClose:t=!0,wrapperClassName:r=Vb,buttonSize:o,iconSize:s="28px"}=e,a=(S=n==null?void 0:n.launcher)!=null?S:{},l=(B=o!=null?o:a.closeButtonSize)!=null?B:"32px",d=v("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(I=a.closeButtonShowTooltip)!=null?I:!0,g=(R=a.closeButtonIconName)!=null?R:"x",h=(P=a.closeButtonIconText)!=null?P:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Mt("button",{className:Us("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:t?void 0:"none",color:a.closeButtonColor||Ln.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),w=he(g,s,"currentColor",1);if(w?(w.style.display="block",b.appendChild(w)):b.textContent=h,d.appendChild(b),u&&c){let A=null,W=()=>{if(A)return;let $=b.ownerDocument,k=$.body;if(!k)return;A=Pr($,"div","persona-clear-chat-tooltip"),A.textContent=c;let U=Pr($,"div");U.className="persona-clear-chat-tooltip-arrow",A.appendChild(U);let F=b.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(wo),A.style.left=`${F.left+F.width/2}px`,A.style.top=`${F.top-8}px`,A.style.transform="translate(-50%, -100%)",k.appendChild(A)},z=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",z),b.addEventListener("focus",W),b.addEventListener("blur",z),d._cleanupTooltip=()=>{z(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",z),b.removeEventListener("focus",W),b.removeEventListener("blur",z)}}return{button:b,wrapper:d}},Kb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xa=(n,e={})=>{var A,W,z,$,k,U,F,te,Ee,de,Y,Le,Pe;let{wrapperClassName:t=Kb,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},l=(z=r!=null?r:a.size)!=null?z:"32px",d=($=a.iconName)!=null?$:"refresh-cw",c=(k=a.iconColor)!=null?k:"",u=(U=a.backgroundColor)!=null?U:"",g=(F=a.borderWidth)!=null?F:"",h=(te=a.borderColor)!=null?te:"",m=(Ee=a.borderRadius)!=null?Ee:"",b=(de=a.paddingX)!=null?de:"",w=(Y=a.paddingY)!=null?Y:"",S=(Le=a.tooltipText)!=null?Le:"Clear chat",B=(Pe=a.showTooltip)!=null?Pe:!0,T=v("div",t),I=!!(g||h),R=Mt("button",{className:Us("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:l,width:l,color:c||Ln.actionIconColor,backgroundColor:u||void 0,border:I?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),P=he(d,o,"currentColor",1);if(P&&(P.style.display="block",R.appendChild(P)),T.appendChild(R),B&&S){let ae=null,fe=()=>{if(ae)return;let re=R.ownerDocument,ce=re.body;if(!ce)return;ae=Pr(re,"div","persona-clear-chat-tooltip"),ae.textContent=S;let Ce=Pr(re,"div");Ce.className="persona-clear-chat-tooltip-arrow",ae.appendChild(Ce);let _e=R.getBoundingClientRect();ae.style.position="fixed",ae.style.zIndex=String(wo),ae.style.left=`${_e.left+_e.width/2}px`,ae.style.top=`${_e.top-8}px`,ae.style.transform="translate(-50%, -100%)",ce.appendChild(ae)},ne=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};T.addEventListener("mouseenter",fe),T.addEventListener("mouseleave",ne),R.addEventListener("focus",fe),R.addEventListener("blur",ne),T._cleanupTooltip=()=>{ne(),T.removeEventListener("mouseenter",fe),T.removeEventListener("mouseleave",ne),R.removeEventListener("focus",fe),R.removeEventListener("blur",ne)}}return{button:R,wrapper:T}};var Ln={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))"},qo=n=>{var P,A,W,z,$,k,U,F,te,Ee,de,Y,Le,Pe,ae,fe;let{config:e,showClose:t=!0}=n,r=Mt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=e==null?void 0:e.launcher)!=null?P:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",l=(z=o.headerIconHidden)!=null?z:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let ne=parseFloat(s)||24,re=he(d,ne*.6,"currentColor",1);re?c.replaceChildren(re):c.textContent=(k=($=e==null?void 0:e.launcher)==null?void 0:$.agentIconText)!=null?k:"\u{1F4AC}"}else if((U=e==null?void 0:e.launcher)!=null&&U.iconUrl){let ne=v("img");ne.src=e.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=s,ne.style.width=s,c.replaceChildren(ne)}else c.textContent=(te=(F=e==null?void 0:e.launcher)==null?void 0:F.agentIconText)!=null?te:"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=e==null?void 0:e.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Ln.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Le=(Y=e==null?void 0:e.launcher)==null?void 0:Y.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Ln.subtitleColor}});u.append(g,h),l?r.append(u):r.append(c,u);let m=(Pe=o.clearChat)!=null?Pe:{},b=(ae=m.enabled)!=null?ae:!0,w=(fe=m.placement)!=null?fe:"inline",S=null,B=null;if(b){let re=Xa(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=re.button,B=re.wrapper,w==="top-right"&&(B.style.right="48px"),w==="inline"&&r.appendChild(B)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:R}=Qa(e,{showClose:t,wrapperClassName:T});return a!=="top-right"&&r.appendChild(R),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:I,closeButtonWrapper:R,clearChatButton:S,clearChatButtonWrapper:B}},ia=(n,e,t)=>{var a,l,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(l=r.closeButtonPlacement)!=null?l:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function ws(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=v("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(wo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",m.id),m.destructive&&b.setAttribute("data-destructive",""),m.icon){let S=he(m.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let w=document.createElement("span");w.textContent=m.label,b.appendChild(w),b.addEventListener("click",S=>{S.stopPropagation(),u(),t(m.id)}),a.appendChild(b)}let l=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=b=>{!a.contains(b.target)&&!r.contains(b.target)&&u()};document.addEventListener("click",m,!0),l=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),l==null||l(),l=null}function g(){a.classList.contains("persona-hidden")?c():u()}function h(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:g,destroy:h}}function xn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:l}=n,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=he(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),l)for(let[u,g]of Object.entries(l))d.setAttribute(u,g);return d}function Xi(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:l,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=v("button",c);if(u.type="button",u.setAttribute("aria-label",t),e){let h=he(e,s!=null?s:14,"currentColor",2);h&&u.appendChild(h)}let g=v("span");if(g.textContent=t,u.appendChild(g),l&&u.addEventListener("click",l),d)for(let[h,m]of Object.entries(d))u.setAttribute(h,m);return u}function Em(n){var m,b;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:l,hover:d}=n,c=v("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let g=he(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var w,S;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=ws({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let S=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{u.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var Gb=n=>{var r;let e=qo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function Qb(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let l=v("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(l.type="button",l.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&l.appendChild(d)}else a.label&&(l.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(l);let c=ws({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),l.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),n.appendChild(d)}else l.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(l)}}var Xb=n=>{var T,I,R,P,A,W,z,$,k;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(T=e==null?void 0:e.launcher)!=null?T:{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=Em({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Ln.titleColor,u=(R=c.querySelector(".persona-combo-btn-label"))!=null?R:c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Ln.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(u),Qb(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let F=o.onTitleClick;c.addEventListener("click",te=>{te.target.closest("button")||F()}),c.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),F())})}let U=o==null?void 0:o.titleRowHover;U&&(c.style.borderRadius=(W=U.borderRadius)!=null?W:"10px",c.style.padding=(z=U.padding)!=null?z:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,te;c.style.backgroundColor=(F=U.background)!=null?F:"",c.style.borderColor=(te=U.border)!=null?te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let g=($=a.closeButtonSize)!=null?$:"32px",h=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Ln.actionIconColor;let b=(k=a.closeButtonIconName)!=null?k:"x",w=he(b,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),l.appendChild(h);let S=v("div");S.style.display="none";let B=v("span");return B.style.display="none",{header:l,iconHolder:S,headerTitle:u,headerSubtitle:B,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},km={default:Gb,minimal:Xb},Jb=n=>{var e;return(e=km[n])!=null?e:km.default},Ja=(n,e,t)=>{var a,l,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=v("div");u.style.display="none";let g=v("span"),h=v("span"),m=v("button");m.style.display="none";let b=v("div");return b.style.display="none",{header:c,iconHolder:u,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Jb(r)({config:n,showClose:(d=(l=e==null?void 0:e.showCloseButton)!=null?l:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ya=n=>{var a,l;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(l=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?l:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Za=n=>{var P,A,W,z,$,k,U,F,te,Ee,de,Y;let e=(P=n==null?void 0:n.sendButton)!=null?P:{},t=(A=e.useIcon)!=null?A:!1,r=(W=e.iconText)!=null?W:"\u2191",o=e.iconName,s=(z=e.stopIconName)!=null?z:"square",a=($=e.tooltipText)!=null?$:"Send message",l=(k=e.stopTooltipText)!=null?k:"Stop generating",d=(F=(U=n==null?void 0:n.copy)==null?void 0:U.sendButtonLabel)!=null?F:"Send",c=(Ee=(te=n==null?void 0:n.copy)==null?void 0:te.stopButtonLabel)!=null?Ee:"Stop",u=(de=e.showTooltip)!=null?de:!1,g=(Y=e.size)!=null?Y:"40px",h=e.backgroundColor,m=e.textColor,b=v("div","persona-send-button-wrapper"),w=Mt("button",{className:Us("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),S=null,B=null;if(t){let Le=parseFloat(g)||24,Pe=(m==null?void 0:m.trim())||"currentColor";o?(S=he(o,Le,Pe,2),S?w.appendChild(S):w.textContent=r):w.textContent=r,B=he(s,Le,Pe,2)}else w.textContent=d;let T=null;u&&a&&(T=v("div","persona-send-button-tooltip"),T.textContent=a,b.appendChild(T)),w.setAttribute("aria-label",a),b.appendChild(w);let I="send";return{button:w,wrapper:b,setMode:Le=>{if(Le===I)return;I=Le;let Pe=Le==="stop"?l:a;if(w.setAttribute("aria-label",Pe),T&&(T.textContent=Pe),t){if(S&&B){let ae=Le==="stop"?B:S;w.replaceChildren(ae)}}else w.textContent=Le==="stop"?c:d}}},ei=n=>{var T,I,R,P,A,W,z,$,k,U,F,te;let e=(T=n==null?void 0:n.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((I=e.provider)==null?void 0:I.type)==="runtype";if(!(r||o))return null;let a=(P=(R=n==null?void 0:n.sendButton)==null?void 0:R.size)!=null?P:"40px",l=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,u=($=e.backgroundColor)!=null?$:(z=n==null?void 0:n.sendButton)==null?void 0:z.backgroundColor,g=(U=e.iconColor)!=null?U:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,h=v("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=he(l,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let S=(F=e.tooltipText)!=null?F:"Start voice recognition";if(((te=e.showTooltip)!=null?te:!1)&&S){let Ee=v("div","persona-send-button-tooltip");Ee.textContent=S,h.appendChild(Ee)}return{button:m,wrapper:h}},ti=n=>{var b,w,S,B,T,I,R,P;let e=(b=n==null?void 0:n.attachments)!=null?b:{};if(e.enabled!==!0)return null;let t=(S=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?S:"40px",r=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((B=e.allowedTypes)!=null?B:Kr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(I=e.buttonIconName)!=null?I:"paperclip",a=t,l=parseFloat(a)||40,d=Math.round(l*.6),c=v("div","persona-send-button-wrapper"),u=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(R=e.buttonTooltipText)!=null?R:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=he(s,d,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(u);let h=(P=e.buttonTooltipText)!=null?P:"Attach file",m=v("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},ni=n=>{var a,l,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=v("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(l=e.visible)!=null?l:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=v("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},ri=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var oi=n=>{var b,w,S,B,T,I;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ri(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ya(e);a();let l=Za(e),d=ei(e),c=ti(e),u=ni(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(l.wrapper),g.append(h,m),o.append(g),o.addEventListener("click",R=>{R.target!==l.button&&R.target!==l.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(c==null?void 0:c.button)&&R.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:u,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:l.setMode}};var Lm=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),t=he("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},Pm=n=>{var b,w,S,B,T,I;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ri();r.style.display="none";let o=ni(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ya(e);s.style.maxHeight="100px",a();let l=Za(e),d=ei(e),c=ti(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",R=>{R.target!==l.button&&R.target!==l.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(c==null?void 0:c.button)&&R.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(g,s,h),c&&t.append(c.previewsContainer),t.append(u,r,o);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:l.setMode}};var Im=n=>{var u,g,h,m,b,w,S,B,T,I,R,P,A,W,z,$,k;let e=(g=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?g:!0,t=fn(n);if(aa(n)){let U=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},F=v("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(b=U.expandedSize)!=null?b:"anchored",F.style.zIndex=String((S=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?S:wn);let te=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",F.appendChild(te);let Ee=v("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(B=U.expandedSize)!=null?B:"anchored",Ee.style.zIndex=String((I=(T=n==null?void 0:n.launcher)==null?void 0:T.zIndex)!=null?I:wn),{wrapper:F,panel:te,pillRoot:Ee}}if(t){let U=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(F),{wrapper:U,panel:F}}if(!e){let U=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(P=(R=n==null?void 0:n.launcher)==null?void 0:R.width)!=null?P:"100%";return U.style.width=te,F.style.width="100%",U.appendChild(F),{wrapper:U,panel:F}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&mr[o.position]?mr[o.position]:mr["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((z=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?z:wn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=($=n==null?void 0:n.launcher)==null?void 0:$.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:Gr;return l.style.width=c,l.style.maxWidth=c,a.appendChild(l),{wrapper:a,panel:l}},Yb=(n,e)=>{var R,P,A,W,z,$,k,U,F;let t=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Qa(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(P=(R=n==null?void 0:n.launcher)==null?void 0:R.clearChat)==null?void 0:P.enabled)!=null?A:!0,a=null,l=null;if(s){let te=Xa(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=te.button,l=te.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let u=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(z=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?z:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=($=n==null?void 0:n.copy)==null?void 0:$.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),h=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=v("div","persona-flex persona-flex-col persona-gap-3"),b=(U=n==null?void 0:n.layout)==null?void 0:U.contentMaxWidth;b&&(m.style.maxWidth=b,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((F=n==null?void 0:n.copy)==null?void 0:F.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let S=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),B=Pm({config:n}),{root:T,textNode:I}=Lm();return t.append(d,o,c,S),l&&t.appendChild(l),{container:t,body:c,messagesWrapper:m,composerOverlay:S,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:u,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:T,peekTextNode:I}},Wm=(n,e=!0)=>{var S,B,T,I,R,P,A,W,z;if(aa(n))return Yb(n,e);let t=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(S=n==null?void 0:n.layout)==null?void 0:S.header,o=((B=n==null?void 0:n.layout)==null?void 0:B.showHeader)!==!1,s=r?Ja(n,r,{showClose:e}):qo({config:n,showClose:e}),a=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let l=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(T=n==null?void 0:n.copy)==null?void 0:T.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(R=n==null?void 0:n.copy)==null?void 0:R.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:fn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},l,d),u=v("div","persona-flex persona-flex-col persona-gap-3"),g=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((W=n==null?void 0:n.copy)==null?void 0:W.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=oi({config:n}),b=((z=n==null?void 0:n.layout)==null?void 0:z.showFooter)!==!1;o?ia(t,s,n):(s.header.style.display="none",ia(t,s,n)),t.append(a);let w=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return b||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:u,composerOverlay:w,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:l,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Ji=(n,e)=>{let t=v("button");t.type="button",t.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:o}var es=t=>({isError:!0,content:[{type:"text",text:t}]}),Fd=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Od=t=>Yo(t)||t===Nn,ga=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Zr(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Yo(n.name)||n.name===Nn&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Jr(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ji().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return zi(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=ar.isSupported()?new ar({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return ji().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=sr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!Fg(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Jr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=e,f={id:a??(n==="user"?da():n==="assistant"?or():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,C={id:p??(r==="user"?da():r==="assistant"?or():`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(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=e,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
|
+
|
|
20
|
+
`),a=[s,n].filter(Boolean).join(`
|
|
21
|
+
|
|
22
|
+
`),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(rr(s)),d.push(...r.contentParts),d.push(...e.contentParts),e.contentParts=d}else if(p){let d=[];a&&d.push(rr(a)),d.push(...r.contentParts),e.contentParts=d}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.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=da(),s=or();this.activeAssistantMessageId=null;let a=n?.contentParts&&Ld(n.contentParts)?pa:"",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=Vi(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 e=or();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Vi(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):c=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(c=>c.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=e.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let b=c[f],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";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(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Nn?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${e}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Nn)return{dedupeKey:u,resumeKey:f,output:Fi(),toolMessage:p,startedAt:w,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),P;if(!C)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await C}catch(H){let M=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));return M||this.callbacks.onError?.(H instanceof Error?H:new Error(String(H))),this.markWebMcpToolComplete(p,es(M?"Aborted by cancel()":Fd(H)),w),this.webMcpInflightKeys.delete(u),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,es("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:P,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(e,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Nn?{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,es("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Nn,c=e.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let b;if(d?b=Fi():u?b=await u:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,es("Aborted by cancel()"),a);return}let C=e.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,b,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let C=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(w==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,es(C||p.aborted?"Aborted by cancel()":Fd(b)),a),C||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=ko(this.config.features?.artifacts,e.artifactType),r=ta(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Vi(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=or(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Ui(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return fa(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=Ui(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Od(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,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&Od(f)&&r.toolCall?.status==="complete";(u||w||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var ma={allowedTypes:Fn,maxFileSize:10*1024*1024,maxFiles:4};function Og(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _g(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ts=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??ma.allowedTypes,maxFileSize:e.maxFileSize??ma.maxFileSize,maxFiles:e.maxFiles??ma.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:ma.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Rd(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 Id(n),s=ua(n)?URL.createObjectURL(n):null,a={id:Og(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=ua(e.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let a=m("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=_g(e.file.type),p=oe(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Wd(e.file.type,e.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=oe("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};function _d(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=Ne("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=oe(a,s,"currentColor",1.5);c?d.appendChild(c):d.textContent="+",d.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),n()}),p.appendChild(d);let u=m("div","persona-send-button-tooltip");return u.textContent=l,p.appendChild(u),{button:d,wrapper:p}}var{setLoader:tv,load:$g}=Jo({fallbackImport:()=>import("./context-mentions-7S5KVUTG.js")});var qi=$g;var{setLoader:rv,load:zg}=Jo({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var $d=zg;function ns(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Ne("span",{className:Bn("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=oe(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ne("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function zd(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=qc(e).filter(T=>T.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(T=>T.sources.some(I=>typeof I.matchCommand=="function")),r=T=>o.some(I=>I.trigger?I.position==="line-start"?T.split(`
|
|
23
|
+
`).some(N=>N.startsWith(I.trigger)):(I.position==="anywhere"?T:T.split(`
|
|
24
|
+
`)[0]).startsWith(I.trigger):!1),s=(T,I)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:I}))}catch{}},a=Ne("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=t.textarea,c=null,u=null,w=null,f=null,b=()=>{if(l)return Promise.resolve(l);if(p)return p;let T=qi().then(I=>(l=I.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:c??void 0,anchor:t.anchor,contextRow:a,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:M,emit:s}),l)).catch(I=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",I),p===T&&(p=null),null));return p=T,T},C=()=>{$d().then(T=>{let I=T.mountInlineComposer({textarea:t.textarea,renderToken:N=>ns(N,{render:e.renderMentionToken}),onMentionRemoved:N=>l?.untrackMention(N)});c=I.input,u=I.destroy;let z=d;z.replaceWith(I.element),d=I.element,f={next:I.element,prev:z},w?.(I.element,z),l?l.rebindComposer(I.input):p&&p.then(N=>N?.rebindComposer(I.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};e.display==="inline"&&C();let P=[],H=new Map;for(let T of n){if(!T.showButton)continue;let I=_d({config:{...e,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{b().then(z=>z?.openMenu(T.trigger))}});P.push(I),H.set(T.trigger,I.button)}let M=(T,I,z)=>{let N=H.get(I);N&&(N.setAttribute("aria-expanded",T?"true":"false"),T?N.setAttribute("aria-controls",z):N.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:a,handleInput:T=>{if(l){l.handleInput();return}if(!Vc(T))return;let I=d,z=I.selectionStart??0;jc(I.value,z,n)&&b().then(N=>N?.handleInput())},handleKeydown:T=>{if(l?.isMenuOpen())return l.handleKeydown(T);if(T.key==="Backspace"&&l?.hasMentions()&&!f){let I=d,z=I.selectionStart===0&&I.selectionEnd===0;if((I.value.length===0||z)&&l.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(l??await b())?.dispatchInlineCommand(T)??null:null,clear:()=>l?.clear(),prefetch:()=>{qi().catch(()=>{})},onComposerSwap:T=>{w=T,f&&T(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let T of P)T.wrapper.remove();a.remove()}}}var Ud=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function os(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];Ud(s)&&Ud(r)?n[o]=os(s,r):n[o]=r}return n}var On="min(440px, calc(100vw - 24px))",Vd="440px",Ug={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:On,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Ug,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 jd(t,e){if(!(!t&&!e))return t?e?os(t,e):t:e}function qd(t){return t?{...dt,...t,theme:jd(dt.theme,t.theme),darkTheme:jd(dt.darkTheme,t.darkTheme),launcher:{...dt.launcher,...t.launcher,dock:{...dt.launcher?.dock,...t.launcher?.dock},clearChat:{...dt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...dt.copy,...t.copy},sendButton:{...dt.sendButton,...t.sendButton},statusIndicator:{...dt.statusIndicator,...t.statusIndicator},voiceRecognition:{...dt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=dt.features?.artifacts,n=t.features?.artifacts,o=dt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=dt.features?.scrollBehavior,a=t.features?.scrollBehavior,l=dt.features?.streamAnimation,p=t.features?.streamAnimation,d=dt.features?.askUserQuestion,c=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},b=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{...dt.features,...t.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...b!==void 0?{streamAnimation:b}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??dt.suggestionChips,suggestionChipsConfig:{...dt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...dt.layout,...t.layout,header:{...dt.layout?.header,...t.layout?.header},messages:{...dt.layout?.messages,...t.layout?.messages,avatar:{...dt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...dt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...dt.layout?.slots,...t.layout?.slots}},markdown:{...dt.markdown,...t.markdown,options:{...dt.markdown?.options,...t.markdown?.options}},messageActions:{...dt.messageActions,...t.messageActions}}:dt}var ha="16px",ya="transparent",jg={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"}},Vg={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"}},qg={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:On,maxWidth:Vd,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ha,canvasBackground:ya},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"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 Kt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Kt(t,o):o}function Kd(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Kt(t,a);p!==void 0&&(e[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Kg(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Gd(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Gd(s,r):n[o]=r}return n}function Gg(t,e){return e?Gd(t,e):t}function Ro(t,e={}){let n={palette:jg,semantic:Vg,components:qg},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:Gg(n.components,t?.components)};if(e.validate!==!1){let r=Kg(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function Qd(t){let e=Kd(t),n={};for(let[x,U]of Object.entries(e)){let V=x.replace(/\./g,"-");n[`--persona-${V}`]=U.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"]??ha,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ya,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),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=t.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"]=Kt(t,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 U=Kt(t,x.toolbarBackground)??x.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}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"]=Kt(t,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"]=Kt(t,x.chromeBackground)??x.chromeBackground),x.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Kt(t,x.chromeBorder)??x.chromeBorder),x.titleColor&&(n["--persona-artifact-inline-title-color"]=Kt(t,x.titleColor)??x.titleColor),x.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Kt(t,x.mutedColor)??x.mutedColor),x.frameHeight&&(n["--persona-artifact-inline-frame-height"]=x.frameHeight)}let b=d?.code;b&&(b.keywordColor&&(n["--persona-code-keyword-color"]=b.keywordColor),b.stringColor&&(n["--persona-code-string-color"]=b.stringColor),b.commentColor&&(n["--persona-code-comment-color"]=b.commentColor),b.numberColor&&(n["--persona-code-number-color"]=b.numberColor),b.tagColor&&(n["--persona-code-tag-color"]=b.tagColor),b.attrColor&&(n["--persona-code-attr-color"]=b.attrColor),b.propertyColor&&(n["--persona-code-property-color"]=b.propertyColor),b.lineNumberColor&&(n["--persona-code-line-number-color"]=b.lineNumberColor),b.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=b.gutterBorderColor),b.background&&(n["--persona-code-bg"]=Kt(t,b.background)??b.background));let C=n["--persona-surface"],P=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",T=n["--persona-palette-colors-gray-300"]??"#d1d5db",I=!P||P===C,z=I?H:P,N=I?M:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??N,I&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??T),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var Qg={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"}}},Xd=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ki=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Xg=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Ki()},Jd=t=>Xg(t),Jg=t=>Ro(t),Yg=t=>{let e=Ro(void 0,{validate:!1});return Ro({...t,palette:{...e.palette,colors:{...Qg.colors,...t?.palette?.colors}}},{validate:!1})},ir=t=>{let e=Jd(t),n=Xd(t?.theme),o=Xd(t?.darkTheme);return e==="dark"?Yg(os(n??{},o??{})):Jg(n)},Zg=t=>Qd(t),rs=(t,e)=>{let n=ir(e),o=Zg(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Jd(e))},ba=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Ki())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Ki());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};function Mn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Yd(t){let e=Mn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function va(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
25
|
+
`);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
|
|
26
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ss(t){let e=Yd(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function oo(t){switch(ss(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Yd(t.path);return e?e.toUpperCase():"File"}}}function Zd(t){let e=t.markdown??"";return t.file?{filename:Mn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:va(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var Gi="http://www.w3.org/2000/svg";function ep(t){let e=document.createElementNS(Gi,"svg");e.setAttribute("class",Bn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Gi,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Gi,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var ro=(t,e,n)=>{let o=n;for(let r of e){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function tp(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),ro(t,e,0)}var Qi="persona-artifact-status-label",np="persona-artifact-status-detail",op="data-artifact-status-label",Xi=new Map,rp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function lr(t){t&&Xi.delete(t)}function em(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?oo(e):t.artifactType==="component"?"Component":"Document"}function cr(t,e,n){let o=em(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Xi.get(a);t.status!=="complete"&&l===void 0&&(l=rp(),Xi.set(a,l));let p=l===void 0?0:Math.max(0,rp()-l),d=t.artifactType==="component",c=!d&&typeof t.markdown=="string"?t.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
|
|
27
|
+
`).length,f=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:w,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(b);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 tm(t){t.className=Qi,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function Wo(t,e,n){let o=t.querySelector(`:scope > .${Qi}`);o||(o=m("span",Qi),t.appendChild(o)),o.getAttribute(op)!==e.label&&(tm(o),tp(o,e.label,n),o.setAttribute(op,e.label));let r=t.querySelector(`:scope > .${np}`),s=e.detail;s?(r||(r=m("span",np),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var nm={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"},om=15e4,wa={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 rm(t,e){let n=(t||"").trim().toLowerCase();if(n&&wa[n])return wa[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(wa[r])return wa[r]}}return null}function xa(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}var sm=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"]),am=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>sm.has(t)?"keyword":"plain"}];function sp(t){return xa(t,am)}var im=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function lm(t){let e=xa(t,im);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var cm=[{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 ap(t){let e=xa(t,cm),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var dm=[{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 pm(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,p=t.slice(r,l);for(let c of xa(p,dm))e.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(t.slice(r)),f=w?r+w.index:o,b=t.slice(r,f),C=c==="script"?sp(b):ap(b);for(let P of C)e.push(P);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function um(t,e){switch(e){case"html":return pm(t);case"css":return ap(t);case"js":return sp(t);case"json":return lm(t)}}function fm(t){let e=zc(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=nm[r];if(a){let l=m("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
|
|
28
|
+
`);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
|
|
29
|
+
`)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function ip(t,e,n){let o=t.length<=om?rm(e,n):null,r=o?um(t,o):[{type:"plain",value:t}];return fm(r)}var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,so=zt+1;function dr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(so)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",f.id),f.destructive&&b.setAttribute("data-destructive",""),f.icon){let P=oe(f.icon,16,"currentColor",1.5);P&&b.appendChild(P)}let C=document.createElement("span");C.textContent=f.label,b.appendChild(C),b.addEventListener("click",P=>{P.stopPropagation(),c(),n(f.id)}),a.appendChild(b)}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=b=>{!a.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Wt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=oe(e,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Bo(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=t,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),e){let w=oe(e,s??14,"currentColor",2);w&&c.appendChild(w)}let u=m("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function Ca(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of e){let u;c.icon?u=Wt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function lp(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=t,d=m("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",e);let c=m("span","persona-combo-btn-label");c.textContent=e,d.appendChild(c);let u=oe(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=dr({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 b=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"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 Aa="persona-artifact-custom-action-btn";function pr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Aa+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Aa+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=m("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Bo({icon:t.icon,label:t.label,className:Aa+(n?" persona-artifact-doc-copy-btn":"")}):o=Wt({icon:t.icon,label:t.label,className:Aa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function as(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function cp(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Mn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=n?oo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let w=document.createElement("div");w.className="persona-truncate persona-text-sm persona-font-medium",w.style.color="var(--persona-text, #1f2937)",w.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let b=e?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},P=cr(C,b,"card");Wo(f,P,b)}else s&&lr(s),f.textContent=p;if(u.append(w,f),d.append(c,u),a==="complete"){let b=e?.config?.features?.artifacts?.cardActions;if(b&&b.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let H of b)try{if(H.visible===void 0||H.visible(P)){let M=pr(H);M.setAttribute("data-artifact-custom-action",H.id),M.className=`${M.className} persona-flex-shrink-0`,d.append(M)}}catch{}}let C=Bo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var Sa=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>cp(t,e)});if(l)return l}return cp(t,e)};var ao=new WeakMap;function Ji(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=ao.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function gp(t){return ao.has(t)}function gm(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete";if(t.artifactType==="component"){let s=t.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:a}}let r=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...r?{file:r}:{}}}function dp(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Mn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?oo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function mm(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var pp=180,hm=240,ym=.8,bm=300,vm=500,wm="cubic-bezier(0.2, 0, 0, 1)",up=240,xm=.35;function Cm(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:pp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let H of a)H.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let d=Math.abs(e-p),c=Math.round(Math.min(vm,Math.max(bm,hm+d*ym))),u=Math.round(c*xm),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:up,delay:u,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:wm});t.style.height=`${p}px`;let C=!1,P=()=>{C||(C=!0,l(),r())};Promise.allSettled([b.finished,f?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+up)+120)},pp)}function Am(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var is="--persona-artifact-inline-body-height";function Sm(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,d,c,u=e?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function fp(t,e){let n=gm(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Am(o),p=o?.inlineActions??[],d=Sm(o),c=d.completeDisplay==="card",u=null,w=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let b=Y=>Sa(mm(Y),e),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(is),f.replaceChildren(b(Y)),ao.set(f,le=>{f.replaceChildren(b(le))})};if(c&&n.status==="complete")return C(n),f;let P=Ta(n,{config:e.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),H=m("div","persona-artifact-inline-body");H.appendChild(P.el);let M=Y=>{let le=Y.status!=="complete",Z=le?d.streamingHeight:d.completeHeight,be=typeof Z=="number";be?f.style.setProperty(is,`${Z}px`):f.style.removeProperty(is);let ve=!!P.el.querySelector(".persona-code-pre"),ue=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");H.classList.toggle("persona-artifact-content-flush",ve),H.classList.toggle("persona-artifact-inline-body--sized",be&&ue),H.classList.toggle("persona-artifact-inline-body--cap",!le&&!ue&&typeof d.completeHeight=="number")},T=n.status,I=(Y,le)=>{T!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(is,`${d.completeHeight}px`):f.style.removeProperty(is),hp(H,le?.suppressTransition?"none":d.transition,Y.id,()=>{P.update(Y),M(Y)})):P.update(Y),M(Y),T=Y.status};M(n);let z=d.overflow==="clip"&&a&&!!n.id;if(z&&(H.setAttribute("data-expand-artifact-inline",n.id),H.setAttribute("role","button"),H.setAttribute("tabindex","0"),H.classList.add("persona-cursor-pointer"),H.setAttribute("aria-label",`Open ${dp(n).title} in panel`)),!r)return f.appendChild(H),ao.set(f,I),f;let N=m("div","persona-artifact-inline-chrome");N.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let x=m("div","persona-artifact-inline-chrome-lead"),U=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=oe("file-text",16,"currentColor",2);V&&U.appendChild(V);let J=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=m("span","persona-artifact-inline-type");x.append(U,J,D);let $=m("div","persona-artifact-inline-chrome-actions"),fe=m("span","persona-flex persona-items-center persona-gap-1"),he=()=>u??d.viewMode,Ee=l?Ca({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let le=Y==="source"?"source":"rendered";le!==he()&&(u=le,P.update(w),M(w))}}):null,xe=s?Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;xe&&n.id&&xe.setAttribute("data-copy-artifact",n.id);let te=a?Wt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(fe),Ee&&$.appendChild(Ee.element),xe&&$.appendChild(xe),te&&$.appendChild(te),N.append(x,$),f.append(N,H);let ge=Y=>{let{title:le,typeLabel:Z}=dp(Y);J.textContent=le,J.title=le,z&&H.setAttribute("aria-label",`Open ${le} in panel`);let be=Y.status!=="complete";if(be){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let ve=cr(Y,o,"inline-chrome");Wo(D,ve,o)}else lr(Y.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=Z;if(xe&&xe.classList.toggle("persona-hidden",be),Ee){let ve=Y.artifactType==="markdown"?Y.file:void 0,ue=!1;if(!be&&ve&&d.viewMode!=="source"){let Te=ss(ve);Te==="markdown"?ue=!0:(Te==="html"||Te==="svg")&&(ue=o?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!ue),Ee.setSelected(he())}if(fe.replaceChildren(),!be&&p.length>0){let ve=as(Y);if(ve)for(let ue of p)try{if(ue.visible===void 0||ue.visible(ve)){let Te=pr(ue,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",ue.id),Te.classList.add("persona-flex-shrink-0"),fe.appendChild(Te)}}catch{}}};return ge(n),ao.set(f,(Y,le)=>{if(c&&T!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;T="complete";let be=Y,ve=!1,ue=Te=>{be=Te,ve=!0};ao.set(f,ue),Cm(f,Z,{swap:()=>{C(be),ve=!1,ao.set(f,ue)},onSettled:()=>{ve?C(be):ao.set(f,Te=>{f.replaceChildren(b(Te))})}});return}(Y.status!=="complete"||Y.id!==w.id)&&(u=null),w=Y,I(Y,le),ge(Y)}),f}var mp=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>fp(t,e)});if(l)return l}return fp(t,e)};var Yi=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},_n=new Yi;_n.register("PersonaArtifactCard",Sa,{bubbleChrome:!1});_n.register("PersonaArtifactInline",mp,{bubbleChrome:!1});function ls(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?va(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Zi=!1;function Tm(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function hp(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Zi||s){o();return}Zi=!0;let a=Tm(n);t.style.setProperty("view-transition-name",a);let l=()=>{Zi=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Mm="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Em="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function km(t){let e=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function Lm(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var Pm=220;function Im(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Rm(t){return`
|
|
30
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Wm(t,e,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(ep());let s=null;return n.label!==!1&&(s=m("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function Bm(t,e,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},u=(T,I)=>{let z=setTimeout(()=>{d.delete(z),T()},I);d.add(z)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let T=Wm(r,s,o);a=T.el,t.appendChild(a),l=Date.now(),o.label!==!1&&u(T.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,Pm))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",H):e.removeEventListener("load",M)},P=()=>{if(p||(p=!0,C(),c(),!a))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-l));T>0?u(b,T):b()};function H(T){if(n===null)return;let I=T.data;!I||I.persona!=="artifact-preview-ready"||I.token!==n||T.source===e.contentWindow&&P()}function M(){let T=I=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>I()):setTimeout(I,0)};T(()=>T(()=>P()))}return u(f,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",H):e.addEventListener("load",M),()=>{p=!0,c(),C(),w()}}function Ta(t,e){let{config:n}=e,o=e.registry??_n,r=e.bodyLayout,s=n.markdown?Js(n.markdown):null,a=Ys(n.sanitize),l=t,p=!1,d=te=>{let ge=Hn()!==null;s&&!ge&&!p&&(p=!0,Xs(()=>xe(l)));let Y=s?s(te):Zn(te);return s&&ge&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,w=null,f=null,b=()=>{f&&(f(),f=null),u=null,w=null},C=null,P=null,H=null,M=!1,T=()=>{C=null,P=null,H=null,M=!1},I=null,z=null,N=()=>{I=null,z=null},x=40,U=0,V=te=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>te()):setTimeout(te,0),J=te=>te.scrollHeight-te.clientHeight-te.scrollTop<=x,D=te=>{if(!r)return;let ge=te.scrollHeight-te.clientHeight>1,Y=te.scrollHeight-te.clientHeight-te.scrollTop;te.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&te.scrollTop>1),te.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Y>1)},$=te=>{U||(U=V(()=>{U=0,te.scrollTop=te.scrollHeight,D(te)}))},fe=(te,ge,Y,le)=>{let Z=!!r,be=Y.id+"|"+(Z?"w":"p");if(!C||H!==be||C.parentElement!==c){b(),N(),c.replaceChildren();let Te=m("pre",Mm+" persona-code-pre"),Ce=m("code","persona-code");if(Te.appendChild(Ce),Z){let je=m("div","persona-artifact-source-window");if(je.appendChild(Te),c.appendChild(je),!(r?.overflow==="clip")&&typeof je.addEventListener=="function"){let Pe=()=>je.scrollHeight-je.clientHeight>1;je.addEventListener("scroll",()=>{J(je)&&(M=!1),D(je)},{passive:!0}),je.addEventListener("wheel",Be=>{Pe()&&Be.deltaY<0&&(M=!0)},{passive:!0}),je.addEventListener("touchmove",()=>{Pe()&&(M=!0)},{passive:!0})}C=je}else c.appendChild(Te),C=Te;P=Ce,H=be}let ve=Z?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",le),ve.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let ue=ve?J(ve):!0;if(P.replaceChildren(ip(te,ge?.language,ge?.path)),ve){let Te=Y.status!=="complete";le&&Te&&r?.followOutput&&!M&&ue?$(ve):Te||(M=!1),D(ve)}},he=te=>{b(),T(),N(),c.replaceChildren();let ge=m("div",Em);ge.innerHTML=d(te),c.appendChild(ge)},Ee=te=>{let ge=te.id,Y=n.features?.artifacts,le=cr(te,Y,"status-body");if(I&&z===ge&&I.parentElement===c){let ve=I.querySelector(".persona-artifact-status-view-text");ve&&Wo(ve,le,Y);return}b(),T(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),be=m("div","persona-artifact-status-view-text");Wo(be,le,Y),Z.appendChild(be),c.appendChild(Z),I=Z,z=ge},xe=te=>{l=te;let ge=e.resolveViewMode?.(te)??r?.viewMode??"rendered",Y=te.artifactType==="markdown"?te.file:void 0,le=te.status!=="complete";le||lr(te.id);let Z=le?r?.streamingHeight:r?.completeHeight,be=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){Ee(te);return}if(Y){let ue=va(te.markdown??""),Te=ss(Y),Ce=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ge==="rendered"&&Ce&&(Te==="html"||Te==="svg")){let Fe=te.id+"\0"+ue;if(u&&w===Fe&&u.parentElement===c)return;T(),N(),b(),c.replaceChildren();let Pe=n.features?.artifacts?.filePreview,Be=Pe?.iframeSandbox??"allow-scripts";!Pe?.dangerouslyAllowSameOrigin&&Be.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."),Be=Be.split(/\s+/).filter(Et=>Et&&Et!=="allow-same-origin").join(" "));let at=Lm(Pe?.loading),_e=m("div","persona-artifact-frame"),Xe=m("iframe","persona-artifact-iframe");Xe.setAttribute("sandbox",Be),Xe.setAttribute("data-artifact-id",te.id);let an=null;at.enabled&&at.injectReadySignal?(an=Im(),Xe.srcdoc=ue+Rm(an)):Xe.srcdoc=ue,_e.appendChild(Xe),c.appendChild(_e),at.enabled&&(f=Bm(_e,Xe,an,at,te.id,n)),u=_e,w=Fe;return}if(b(),!le&&Te==="markdown"&&ge==="rendered"){he(ue);return}fe(ue,{language:Y.language,path:Y.path},te,be);return}if(te.artifactType==="markdown"){if(ge==="source"){b(),fe(te.markdown??"",void 0,te,be);return}he(te.markdown??"");return}b(),T(),N(),c.replaceChildren();let ve=te.component?o.get(te.component):void 0;if(ve){let Te={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ce=ve(te.props??{},Te);if(Ce){c.appendChild(Ce);return}}catch{}}c.appendChild(km(te))};return xe(t),{el:c,update(te){xe(te)}}}import{Idiomorph as Hm}from"idiomorph";var Ma=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Hm.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var yp=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var el={index:-1,draft:""};function bp(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function vp(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function wp(){return new Map}function xp(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Cp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Ap(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Ea(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function En(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function io(t,e){return En(t)-t.scrollTop<=e}function ka(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=t,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!e&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:e&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function La(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function Sp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Tp(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Mp(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Dm=["pre","code","a","script","style"],Pa=t=>({type:t?.type??cs.type,placeholder:t?.placeholder??cs.placeholder,speed:t?.speed??cs.speed,duration:t?.duration??cs.duration,buffer:t?.buffer??cs.buffer}),Nm=[{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"}],kp=new Map;for(let t of Nm)kp.set(t.name,t);var ur=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:kp.get(t)??null,Ia=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
31
|
+
`);return s<0?"":t.slice(0,s)}return t},Fm=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},Om=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},tl=/\s/,_m=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},$m=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(tl.test(s[l])){let p=l;for(;p<s.length&&tl.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&&!tl.test(s[d]);)p.appendChild(Fm(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},zm=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(Om(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},ds=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??Dm).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)_m(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?$m:zm;for(let u of l)c(u,n,d);return r.innerHTML},Ra=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ps=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Ep=new WeakMap,Um=(t,e)=>{if(!t.styles)return;let n=Ep.get(e);if(n||(n=new Set,Ep.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},nl=new WeakMap,jm=(t,e)=>{if(!t.onAttach)return;let n=nl.get(e);if(n||(n=new Map,nl.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Lp=t=>{let e=nl.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Wa=(t,e)=>{Um(t,e),jm(t,e)};function ol(t,e=zt){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var us=0,lo=null;function rl(t=document){if(us++,us===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;lo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,us=Math.max(0,us-1),us===0&&lo)){let n=t.body,o=t.defaultView??window;n.style.overflow=lo.originalOverflow,n.style.position=lo.originalPosition,n.style.top=lo.originalTop,n.style.width=lo.originalWidth,o.scrollTo(0,lo.scrollY),lo=null}}}var fs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ft=t=>(t?.launcher?.mountMode??"floating")==="docked",gs=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",fn=t=>{let e=t?.launcher?.dock;return{side:e?.side??fs.side,width:e?.width??fs.width,animate:e?.animate??fs.animate,reveal:e?.reveal??fs.reveal,maxHeight:e?.maxHeight??fs.maxHeight}};var xn={"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 Vm="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ba=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Vm,buttonSize:r,iconSize:s="28px"}=e,a=t?.launcher??{},l=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Ne("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Gt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=oe(u,s,"currentColor",1);if(C?(C.style.display="block",b.appendChild(C)):b.textContent=w,p.appendChild(b),c&&d){let P=null,H=()=>{if(P)return;let T=b.ownerDocument,I=T.body;if(!I)return;P=Tn(T,"div","persona-clear-chat-tooltip"),P.textContent=d;let z=Tn(T,"div");z.className="persona-clear-chat-tooltip-arrow",P.appendChild(z);let N=b.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(so),P.style.left=`${N.left+N.width/2}px`,P.style.top=`${N.top-8}px`,P.style.transform="translate(-50%, -100%)",I.appendChild(P)},M=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};p.addEventListener("mouseenter",H),p.addEventListener("mouseleave",M),b.addEventListener("focus",H),b.addEventListener("blur",M),p._cleanupTooltip=()=>{M(),p.removeEventListener("mouseenter",H),p.removeEventListener("mouseleave",M),b.removeEventListener("focus",H),b.removeEventListener("blur",M)}}return{button:b,wrapper:p}},qm="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ha=(t,e={})=>{let{wrapperClassName:n=qm,buttonSize:o,iconSize:r="20px"}=e,a=(t?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",b=a.paddingX??"",C=a.paddingY??"",P=a.tooltipText??"Clear chat",H=a.showTooltip??!0,M=m("div",n),T=!!(u||w),I=Ne("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Gt.actionIconColor,backgroundColor:c||void 0,border:T?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=oe(p,r,"currentColor",1);if(z&&(z.style.display="block",I.appendChild(z)),M.appendChild(I),H&&P){let N=null,x=()=>{if(N)return;let V=I.ownerDocument,J=V.body;if(!J)return;N=Tn(V,"div","persona-clear-chat-tooltip"),N.textContent=P;let D=Tn(V,"div");D.className="persona-clear-chat-tooltip-arrow",N.appendChild(D);let $=I.getBoundingClientRect();N.style.position="fixed",N.style.zIndex=String(so),N.style.left=`${$.left+$.width/2}px`,N.style.top=`${$.top-8}px`,N.style.transform="translate(-50%, -100%)",J.appendChild(N)},U=()=>{N&&N.parentNode&&(N.parentNode.removeChild(N),N=null)};M.addEventListener("mouseenter",x),M.addEventListener("mouseleave",U),I.addEventListener("focus",x),I.addEventListener("blur",U),M._cleanupTooltip=()=>{U(),M.removeEventListener("mouseenter",x),M.removeEventListener("mouseleave",U),I.removeEventListener("focus",x),I.removeEventListener("blur",U)}}return{button:I,wrapper:M}};var Gt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=t=>{let{config:e,showClose:n=!0}=t,o=Ne("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Ne("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 z=parseFloat(s)||24,N=oe(p,z*.6,"currentColor",1);N?d.replaceChildren(N):d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=m("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,d.replaceChildren(z)}else d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ne("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Gt.titleColor}}),w=Ne("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Gt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},b=f.enabled??!0,C=f.placement??"inline",P=null,H=null;if(b){let N=Ha(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=N.button,H=N.wrapper,C==="top-right"&&(H.style.right="48px"),C==="inline"&&o.appendChild(H)}let M=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&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:T,wrapper:I}=Ba(e,{showClose:n,wrapperClassName:M});return a!=="top-right"&&o.appendChild(I),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:T,closeButtonWrapper:I,clearChatButton:P,clearChatButtonWrapper:H}},ms=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var Km=t=>{let e=Ho({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function Gm(t,e,n){if(e?.length)for(let o of e){let r=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=oe(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=dr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var Qm=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=lp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Gt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Gt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Gm(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let T=r.onTitleClick;d.addEventListener("click",I=>{I.target.closest("button")||T()}),d.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),T())})}let M=r?.titleRowHover;M&&(d.style.borderRadius=M.borderRadius??"10px",d.style.padding=M.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=M.background??"",d.style.borderColor=M.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Gt.actionIconColor;let b=a.closeButtonIconName??"x",C=oe(b,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let P=m("div");P.style.display="none";let H=m("span");return H.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:H,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},Pp={default:Km,minimal:Qm},Xm=t=>Pp[t]??Pp.default,Da=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=m("div");l.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=Xm(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Na=t=>{let e=m("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let a=parseFloat(e.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,r());e.style.height=`${a}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Fa=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",d=t?.copy?.stopButtonLabel??"Stop",c=e.showTooltip??!1,u=e.size??"40px",w=e.backgroundColor,f=e.textColor,b=m("div","persona-send-button-wrapper"),C=Ne("button",{className:Bn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&w||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),P=null,H=null;if(n){let z=parseFloat(u)||24,N=f?.trim()||"currentColor";r?(P=oe(r,z,N,2),P?C.appendChild(P):C.textContent=o):C.textContent=o,H=oe(s,z,N,2)}else C.textContent=p;let M=null;c&&a&&(M=m("div","persona-send-button-tooltip"),M.textContent=a,b.appendChild(M)),C.setAttribute("aria-label",a),b.appendChild(C);let T="send";return{button:C,wrapper:b,setMode:z=>{if(z===T)return;T=z;let N=z==="stop"?l:a;if(C.setAttribute("aria-label",N),M&&(M.textContent=N),n){if(P&&H){let x=z==="stop"?H:P;C.replaceChildren(x)}}else C.textContent=z==="stop"?d:p}}},Oa=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??a,d=parseFloat(p)||24,c=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,w=m("div","persona-send-button-wrapper"),f=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),C=oe(l,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",w.appendChild(f);let P=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&P){let M=m("div","persona-send-button-tooltip");M.textContent=P,w.appendChild(M)}return{button:f,wrapper:w}},_a=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Fn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=m("div","persona-send-button-wrapper"),c=Ne("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=oe(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",b=>{b.preventDefault(),r.click()}),d.appendChild(c);let w=e.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=w,d.appendChild(f),{button:c,wrapper:d,input:r,previewsContainer:o}},$a=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=m("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},za=()=>Ne("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ua=t=>{let{config:e}=t,n=Ne("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=za(),r=Ne("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Na(e);a();let l=Fa(e),p=Oa(e),d=_a(e),c=$a(e);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Ne("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&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 Ip=()=>{let t=Ne("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=m("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=oe("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},Rp=t=>{let{config:e}=t,n=Ne("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=za(),r=$a(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=Na(e);s.style.maxHeight="100px",a();let l=Fa(e),p=Oa(e),d=_a(e);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ne("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&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 Wp=t=>{let e=t?.launcher?.enabled??!0,n=Ft(t);if(gs(t)){let c=t?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??zt);let w=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??zt),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!e){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=t?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=t?.launcher??{},s=r.position&&xn[r.position]?xn[r.position]:xn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??zt);let l=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=t?.launcher?.width??t?.launcherWidth??On;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},Jm=(t,e)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Ba(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let I=Ha(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=I.button,l=I.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Ne("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ne("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=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=Ne("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=m("div","persona-flex persona-flex-col persona-gap-3"),b=t?.layout?.contentMaxWidth;b&&(f.style.maxWidth=b,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let P=Ne("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"}}),H=Rp({config:t}),{root:M,textNode:T}=Ip();return n.append(p,r,d,P),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:P,suggestions:H.suggestions,textarea:H.textarea,sendButton:H.sendButton,sendButtonWrapper:H.sendButtonWrapper,micButton:H.micButton,micButtonWrapper:H.micButtonWrapper,composerForm:H.composerForm,statusText:H.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:H.footer,attachmentButton:H.attachmentButton,attachmentButtonWrapper:H.attachmentButtonWrapper,attachmentInput:H.attachmentInput,attachmentPreviewsContainer:H.attachmentPreviewsContainer,actionsRow:H.actionsRow,leftActions:H.leftActions,rightActions:H.rightActions,setSendButtonMode:H.setSendButtonMode,peekBanner:M,peekTextNode:T}},Bp=(t,e=!0)=>{if(gs(t))return Jm(t,e);let n=Ne("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Da(t,o,{showClose:e}):Ho({config:t,showClose:e}),a=Ne("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=Ne("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ne("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Ne("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Ft(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=Ua({config:t}),b=t?.layout?.showFooter!==!1;r?ms(n,s,t):(s.header.style.display="none",ms(n,s,t)),n.append(a);let C=Ne("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||(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 sl=(t,e)=>{let n=m("button");n.type="button",n.innerHTML=`
|
|
20
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>
|
|
21
33
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
22
34
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -24,14 +36,14 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
24
36
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
25
37
|
</span>
|
|
26
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>
|
|
27
|
-
`,t.addEventListener("click",e);let r=s=>{var I,R,P,A,W,z,$,k,U,F,te,Ee,de;let a=(I=s.launcher)!=null?I:{},l=fn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let Y=(R=a.title)!=null?R:"Chat Assistant";d.textContent=Y,d.setAttribute("title",Y)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let Y=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=Y,c.setAttribute("title",Y)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let g=t.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let Y=(A=a.agentIconSize)!=null?A:"40px";if(g.style.height=Y,g.style.width=Y,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let Le=parseFloat(Y)||24,Pe=he(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(g.appendChild(Pe),g.style.display=""):(g.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(z=a.agentIconText)!=null?z:"\u{1F4AC}",g.style.display="")}let h=t.querySelector("[data-role='launcher-image']");if(h){let Y=($=a.agentIconSize)!=null?$:"40px";h.style.height=Y,h.style.width=Y,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Y=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=Y,m.style.width=Y,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",a.callToActionIconName){let Pe=parseFloat(Y)||24,ae=Math.max(Pe-Le,8),fe=he(a.callToActionIconName,ae,"currentColor",2);fe?m.appendChild(fe):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let b=a.position&&mr[a.position]?mr[a.position]:mr["bottom-right"],w="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=l?S:`${w} ${b}`,l||(t.style.zIndex=String((te=a.zIndex)!=null?te:wn));let B="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Ee=a.border)!=null?Ee:B,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,l?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var Rm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=Im(n),s=Wm(n,e),a={wrapper:t,panel:r,pillRoot:o},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:d,composer:c,replaceHeader:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{c.footer.replaceWith(h),c.footer=h}}},Yi=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>Ji(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Ji(n,t);return{instance:o,element:o.element}};var Zb=n=>{switch(n){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},ev=(n,e)=>{if(!n)return null;let t=Zb(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},tv=(n,e)=>{let t=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},nv=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},Zi=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},el=320,Bm=320,rv=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ov=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),sv=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),av=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),iv=(n,e,t)=>{if(n.length===0)return null;try{let r=v("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((l,d)=>{var g;let c=v("img");c.alt=((g=l.alt)==null?void 0:g.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${el}px`,c.style.maxHeight=`${Bm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),nv(l.image)?(c.src=l.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},lv=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!Zi(r.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${el}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},cv=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!Zi(r.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${el}px`,o.style.maxHeight=`${Bm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},dv=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!Zi(r.data))return;let o=v("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},la=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},pv=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:la};if(e){let o=e(r);if(o!==null)return o}return la()},uv=(n,e)=>{let t=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=v("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Hm=(n,e,t="div")=>{let r=v(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},mv=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},gv=(n,e,t)=>{var b,w,S,B,T,I,R;let r=(b=e.showCopy)!=null?b:!0,o=(w=e.showUpvote)!=null?w:!0,s=(S=e.showDownvote)!=null?S:!0,a=(B=e.showReadAloud)!=null?B:!1;if(!r&&!o&&!s&&!a){let P=v("div");return P.style.display="none",P.id=`actions-${n.id}`,P.setAttribute("data-actions-for",n.id),P}let l=(T=e.visibility)!=null?T:"hover",d=(I=e.align)!=null?I:"right",c=(R=e.layout)!=null?R:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],h=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);h.id=`actions-${n.id}`,h.setAttribute("data-actions-for",n.id);let m=(P,A,W)=>{let z=xn({icon:P,label:A,size:14,className:"persona-message-action-btn"});return z.setAttribute("data-action",W),z};return r&&h.appendChild(m("copy","Copy message","copy")),a&&h.appendChild(m("volume-2","Read aloud","read-aloud")),o&&h.appendChild(m("thumbs-up","Upvote","upvote")),s&&h.appendChild(m("thumbs-down","Downvote","downvote")),h},tl=(n,e,t,r,o,s)=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue;let a=t!=null?t:{},l=(ne=a.layout)!=null?ne:"bubble",d=a.avatar,c=a.timestamp,u=(re=d==null?void 0:d.show)!=null?re:!1,g=(ce=c==null?void 0:c.show)!=null?ce:!1,h=(Ce=d==null?void 0:d.position)!=null?Ce:"left",m=(_e=c==null?void 0:c.position)!=null?_e:"below",b=mv(n.role,l),w=v("div",b.join(" "));w.id=`bubble-${n.id}`,w.setAttribute("data-message-id",n.id),w.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=rv(n),B=(X=(V=n.content)==null?void 0:V.trim())!=null?X:"",I=S.length>0&&B===Ha,R=ja((J=(Ae=s==null?void 0:s.widgetConfig)==null?void 0:Ae.features)==null?void 0:J.streamAnimation),P=(Je=(Se=(ie=s==null?void 0:s.widgetConfig)==null?void 0:ie.features)==null?void 0:Se.streamAnimation)==null?void 0:Je.plugins,A=n.role==="assistant"&&R.type!=="none"?vs(R.type,P):null,W=n.role==="assistant"&&((et=A==null?void 0:A.isAnimating)==null?void 0:et.call(A,n))===!0,z=n.role==="assistant"&&A!==null&&(!!n.streaming||W);z&&(A!=null&&A.bubbleClass)&&w.classList.add(A.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),n.streaming&&$.classList.add("persona-content-streaming"),z&&A&&(A.containerClass&&$.classList.add(A.containerClass),$.style.setProperty("--persona-stream-step",`${R.speed}ms`),$.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let k=z?Va((Wt=n.content)!=null?Wt:"",R.buffer,A,n,!!n.streaming):(ft=n.content)!=null?ft:"",U=e({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),F=U;z&&(A==null?void 0:A.wrap)==="char"?F=na(U,"char",n.id,{skipTags:A.skipTags}):z&&(A==null?void 0:A.wrap)==="word"&&(F=na(U,"word",n.id,{skipTags:A.skipTags}));let te=null;if(I?(te=document.createElement("div"),te.innerHTML=F,te.style.display="none",$.appendChild(te)):$.innerHTML=F,z&&(A!=null&&A.useCaret)&&!I&&B){let Q=Ka(),it=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),je=it[it.length-1];if(je!=null&&je.parentNode)je.parentNode.insertBefore(Q,je.nextSibling);else{let Te=$.lastElementChild;Te?Te.appendChild(Q):$.appendChild(Q)}}if(g&&m==="inline"&&n.createdAt){let Q=Hm(n,c,"span");Q.classList.add("persona-timestamp-inline");let it=$.lastElementChild;it?it.appendChild(Q):$.appendChild(Q)}if(S.length>0){let Q=iv(S,!I&&!!B,()=>{I&&te&&(te.style.display="")});Q?w.appendChild(Q):I&&te&&(te.style.display="")}let Ee=ov(n);if(Ee.length>0){let Q=lv(Ee);Q&&w.appendChild(Q)}let de=sv(n);if(de.length>0){let Q=cv(de);Q&&w.appendChild(Q)}let Y=av(n);if(Y.length>0){let Q=dv(Y);Q&&w.appendChild(Q)}if(w.appendChild($),g&&m==="below"&&n.createdAt){let Q=Hm(n,c);Q.classList.add("persona-mt-1"),w.appendChild(Q)}let Le=n.role==="assistant"?ev(n.stopReason,(ue=(rt=s==null?void 0:s.widgetConfig)==null?void 0:rt.copy)==null?void 0:ue.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let Q=!!(k&&k.trim()),it=R.placeholder==="skeleton",je=it&&R.buffer==="line"&&Q;if(Q)je&&w.appendChild(ra());else if(it)w.appendChild(ra());else{let Te=pv("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Te&&w.appendChild(Te)}}if(Le&&n.stopReason&&!n.streaming&&(B||($.style.display="none"),w.appendChild(tv(n.stopReason,Le))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=gv(n,r,o);w.appendChild(Q)}if(!u||n.role==="system")return w;let ae=v("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),fe=uv(d,n.role);return h==="right"||h==="left"&&n.role==="user"?ae.append(w,fe):ae.append(fe,w),w.classList.remove("persona-max-w-[85%]"),w.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ae};var xs=new Set,fv=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),hv=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
-
`):""},
|
|
29
|
-
`);let
|
|
30
|
-
`):""},rl=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},vv=(n,e)=>{var u,g,h,m,b;let t=n.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(g=r==null?void 0:r.collapsedMode)!=null?g:"tool-call",s=bv(n,(h=r==null?void 0:r.previewMaxLines)!=null?h:3),a=t?Uu(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let l=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((b=t.name)==null?void 0:b.trim())||a:o==="tool-preview"&&s&&(c=s),l&&d.activeTextTemplate?c=Fi(t,d.activeTextTemplate,c):!l&&d.completeTextTemplate&&(c=Fi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},Nm=(n,e,t)=>{var u;let r=Cs.has(n),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let g=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",h=he(r?"chevron-up":"chevron-down",16,g,2);h?c.appendChild(h):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",l&&(l.style.display=r?"none":l.textContent||l.childNodes.length?"":"none")},ol=(n,e)=>{var F,te,Ee,de,Y,Le,Pe,ae,fe;let t=n.toolCall,r=(F=e==null?void 0:e.toolCall)!=null?F:{},o=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(Ee=(te=e==null?void 0:e.features)==null?void 0:te.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,l=a&&Cs.has(n.id),{summary:d,previewText:c,isActive:u}=vv(n,e),g=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let b=String((de=t.startedAt)!=null?de:Date.now()),w=()=>{let ne=v("span","");return ne.setAttribute("data-tool-elapsed",b),ne.textContent=Vs(t),ne},S=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(Y=s.collapsedMode)!=null?Y:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Vs(t),createElapsedElement:w});typeof S=="string"&&S.trim()?(m.textContent=S,h.appendChild(m)):S instanceof HTMLElement?h.appendChild(S):(m.textContent=d,h.appendChild(m));let B=(Pe=s.loadingAnimation)!=null?Pe:"none",T=r.activeTextTemplate,I=r.completeTextTemplate,R=u?T:I,P=S instanceof HTMLElement,A=(ne,re,ce)=>{let Ce=ce;for(let _e of re){let V=v("span","persona-tool-char");V.style.setProperty("--char-index",String(Ce)),V.textContent=_e===" "?"\xA0":_e,ne.appendChild(V),Ce++}return Ce},W=(ne,re)=>{var V;m.textContent="";let ce=((V=t.name)==null?void 0:V.trim())||"tool",Ce=Ia(ne,ce),_e=0;for(let X of Ce){let Ae=X.styles.length>0?(()=>{let J=v("span",X.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(J),J})():m;if(X.isDuration&&u)Ae.appendChild(w());else{let J=X.isDuration?Vs(t):X.text;re?_e=A(Ae,J,_e):Ae.appendChild(document.createTextNode(J))}}};if(!P)if(u&&B!=="none"){let ne=(ae=r.loadingAnimationDuration)!=null?ae:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),R&&W(R,!1);else if(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${ne}ms`),B==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),R)W(R,!0);else{let re=m.textContent||d;m.textContent="",A(m,re,0)}}else R&&W(R,!1);let z=null;if(a){z=v("div","persona-flex persona-items-center");let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",re=he(l?"chevron-up":"chevron-down",16,ne,2);re?z.appendChild(re):z.textContent=l?"Hide":"Show";let ce=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ce.append(z),g.append(h,ce)}else g.append(h);let $=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!l&&u&&s.activePreview&&c){let ne=(fe=r.renderCollapsedPreview)==null?void 0:fe.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:u,config:e!=null?e:{}});yv($,ne)||($.textContent=c),$.style.display=""}if(!l&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(g,$),o;let k=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=l?"":"none",r.contentBackgroundColor&&(k.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(k.style.color=r.contentTextColor),r.contentPaddingX&&(k.style.paddingLeft=r.contentPaddingX,k.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(k.style.paddingTop=r.contentPaddingY,k.style.paddingBottom=r.contentPaddingY),t.name){let ne=v("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?ne.style.color=r.contentTextColor:r.headerTextColor&&(ne.style.color=r.headerTextColor),ne.textContent=t.name,k.appendChild(ne)}if(t.args!==void 0){let ne=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Arguments";let ce=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",rl(ce,r),ce.textContent=bo(t.args),ne.append(re,ce),k.appendChild(ne)}if(t.chunks&&t.chunks.length){let ne=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Activity";let ce=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",rl(ce,r),ce.textContent=t.chunks.join(""),ne.append(re,ce),k.appendChild(ne)}if(t.status==="complete"&&t.result!==void 0){let ne=v("div","persona-space-y-1"),re=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(re.style.color=r.labelTextColor),re.textContent="Result";let ce=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ce.style.fontSize="0.75rem",ce.style.lineHeight="1rem",rl(ce,r),ce.textContent=bo(t.result),ne.append(re,ce),k.appendChild(ne)}if(t.status==="complete"&&typeof t.duration=="number"){let ne=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(ne.style.color=r.contentTextColor),ne.textContent=`Duration: ${t.duration}ms`,k.appendChild(ne)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),z){z.innerHTML="";let ne=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",re=he(l?"chevron-up":"chevron-down",16,ne,2);re?z.appendChild(re):z.textContent=l?"Hide":"Show"}k.style.display=l?"":"none",$.style.display=l?"none":$.textContent||$.childNodes.length?"":"none"})(),o.append(g,$,k),o};var jo=new Map,si=n=>{let t=(n.startsWith(jr)?n.slice(jr.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Fm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Om=(n,e)=>{var r,o,s;let t=(o=(r=Fm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=jo.get(n))!=null?s:t==="expanded"},_m=(n,e,t)=>{var a,l;let r=Fm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(l=r==null?void 0:r.showDetailsLabel)!=null?l:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=he(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},$m=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=Om(n,t);_m(r,s,t),o.style.display=s?"":"none"};var ai=(n,e)=>{var W,z,$,k,U,F,te,Ee,de,Y,Le,Pe,ae,fe,ne;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(z=r==null?void 0:r.borderColor)!=null?z:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":($=r==null?void 0:r.titleColor)!=null?$:"currentColor",u=he(d,20,c,2);u&&l.appendChild(u);let g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",h.appendChild(m),!o){let re=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");re.setAttribute("data-approval-status",t.status),t.status==="approved"?(re.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",re.style.color="var(--persona-palette-colors-success-700, #15803d)",re.textContent="Approved"):t.status==="denied"?(re.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",re.style.color="var(--persona-palette-colors-error-700, #b91c1c)",re.textContent="Denied"):t.status==="timeout"&&(re.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",re.style.color="var(--persona-palette-colors-warning-700, #b45309)",re.textContent="Timeout"),h.appendChild(re)}g.appendChild(h);let w=t.toolType==="webmcp"||t.toolName.startsWith(jr)?$s(t.toolName):void 0,S=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...w?{displayTitle:w}:{},...t.reason?{reason:t.reason}:{}}),B=!t.toolName,T=S||(B?t.description:`The assistant wants to use \u201C${w!=null?w:si(t.toolName)}\u201D.`),I=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(I.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(I.style.color=r.descriptionColor),I.textContent=T,g.appendChild(I),t.reason){let re=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");re.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?re.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(re.style.color=r.descriptionColor);let ce=v("span","persona-font-medium");ce.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,re.appendChild(ce),re.appendChild(document.createTextNode(t.reason)),g.appendChild(re)}let R=(te=r==null?void 0:r.detailsDisplay)!=null?te:"collapsed",P=!!t.description&&!B,A=P||!!t.parameters;if(R!=="hidden"&&A){let re=Om(n.id,e),ce=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ce.type="button",ce.setAttribute("data-expand-header","true"),ce.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ce.style.color=r.descriptionColor);let Ce=v("span");Ce.setAttribute("data-approval-details-label","true");let _e=v("span","persona-inline-flex persona-items-center");_e.setAttribute("data-approval-details-chevron","true"),ce.append(Ce,_e),_m(ce,re,e),g.appendChild(ce);let V=v("div");if(V.setAttribute("data-approval-details","true"),V.style.display=re?"":"none",P){let X=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=t.description,V.appendChild(X)}if(t.parameters){let X=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=bo(t.parameters),V.appendChild(X)}g.appendChild(V)}if(o){let re=v("div","persona-flex persona-gap-2 persona-mt-2");re.setAttribute("data-approval-buttons","true");let ce=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ce.type="button",ce.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ce.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ce.setAttribute("data-approval-action","approve");let Ce=he("shield-check",14,(Y=r==null?void 0:r.approveButtonTextColor)!=null?Y:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",ce.appendChild(Ce));let _e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ce.appendChild(_e);let V=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ae=r==null?void 0:r.denyButtonTextColor)!=null?ae:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let X=he("shield-x",14,(fe=r==null?void 0:r.denyButtonTextColor)!=null?fe:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let Ae=document.createTextNode((ne=r==null?void 0:r.denyLabel)!=null?ne:"Deny");V.appendChild(Ae),re.append(ce,V),g.appendChild(re)}return a.append(l,g),s.appendChild(a),s};function wv(n){var t,r;let e=(t=n.getRootNode)==null?void 0:t.call(n);return e instanceof ShadowRoot?e:((r=n.ownerDocument)!=null?r:document).body}function Um(n){var w;let{anchor:e,content:t,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:l,onDismiss:d}=n,c=(w=n.container)!=null?w:wv(e),u=!1,g=null,h=()=>{if(!u)return;let S=e.getBoundingClientRect();t.style.position="fixed",s&&(t.style.minWidth=`${S.width}px`);let B=r==="top-start"||r==="top-end"?S.top-o-t.getBoundingClientRect().height:S.bottom+o,T=r==="bottom-end"||r==="top-end"?S.right-t.getBoundingClientRect().width:S.left;t.style.top=`${B}px`,t.style.left=`${T}px`},m=()=>{u&&(u=!1,g&&(g(),g=null),t.remove())},b=()=>{var P,A,W;if(u)return;u=!0,a!=null&&(t.style.zIndex=String(a)),c.appendChild(t),h();let S=(A=((P=e.ownerDocument)!=null?P:document).defaultView)!=null?A:window,B=(W=e.ownerDocument)!=null?W:document,T=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}h()},I=z=>{let $=typeof z.composedPath=="function"?z.composedPath():[];$.includes(t)||$.includes(e)||(m(),d==null||d("outside"))},R=S.setTimeout(()=>{B.addEventListener("pointerdown",I,!0)},0);S.addEventListener("scroll",T,!0),S.addEventListener("resize",T),g=()=>{S.clearTimeout(R),B.removeEventListener("pointerdown",I,!0),S.removeEventListener("scroll",T,!0),S.removeEventListener("resize",T)},l==null||l()};return{get isOpen(){return u},open:b,close:m,toggle:()=>u?m():b(),reposition:h,destroy:m}}function zm(n){return(typeof n.composedPath=="function"?n.composedPath():[]).some(t=>t instanceof HTMLElement&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}var xv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qm=(n,e)=>{let t=n.keyHandlers.get(e);t&&(document.removeEventListener("keydown",t),n.keyHandlers.delete(e));let r=n.popovers.get(e);r&&(r.destroy(),n.popovers.delete(e))},Vo=(n,e)=>{qm(n,e);let t=n.pendingOrder.indexOf(e);t!==-1&&n.pendingOrder.splice(t,1),n.latestPendingApprovalId===e&&(n.latestPendingApprovalId=n.pendingOrder.length?n.pendingOrder[n.pendingOrder.length-1]:null)},Cv=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Av=(n,e)=>{var r,o;let t=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=jo.get(n))!=null?o:t==="expanded"},sl=n=>{let e=v("span","persona-approval-kbd");return e.textContent=n,e},Sv=(n,e)=>{var c,u;let t=v("span","persona-approval-title");e!=null&&e.titleColor&&(t.style.color=e.titleColor);let o=n.toolType==="webmcp"||n.toolName.startsWith(jr)?$s(n.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:n.toolName,toolType:n.toolType,description:(c=n.description)!=null?c:"",parameters:n.parameters,...o?{displayTitle:o}:{},...n.reason?{reason:n.reason}:{}});if(s)return t.textContent=s,t;let a=o!=null?o:si(n.toolName),l=n.toolType&&n.toolType!=="webmcp"?n.toolType:null;t.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,t.appendChild(d),l){t.append(" from ");let g=document.createElement("strong");g.textContent=l,t.appendChild(g)}return t},Tv=n=>{let e=v("div","persona-approval-resolved"),t=he("ban",15,"currentColor",2);t&&e.appendChild(t);let r=v("span","persona-approval-resolved-name");return r.textContent=n.toolName?si(n.toolName):"Tool",e.append(r,document.createTextNode(n.status==="timeout"?" timed out":" denied")),e},Mv=(n,e,t,r,o,s,a)=>{var z,$,k,U,F,te,Ee;let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(l.style.background=r.backgroundColor),r!=null&&r.borderColor&&(l.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(l.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(z=r==null?void 0:r.detailsDisplay)!=null?z:"collapsed",c=!!t.description&&d!=="hidden",u=t.parameters!=null&&d!=="hidden",g=c||u,h=g&&Av(e.id,r),m=($=r==null?void 0:r.showDetailsLabel)!=null?$:"Show details",b=(k=r==null?void 0:r.hideDetailsLabel)!=null?k:"Hide details",w=v("button","persona-approval-head");w.type="button",g?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",h?"true":"false"),w.setAttribute("aria-label",h?b:m)):w.setAttribute("data-static","true");let S=v("span","persona-approval-logo"),B=he("shield-check",16,"currentColor",2);B&&S.appendChild(B),w.appendChild(S);let T=Sv(t,r);if(g){let de=v("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let Y=he("chevron-down",14,"currentColor",2);Y&&de.appendChild(Y),T.append(" "),T.appendChild(de)}w.appendChild(T),l.appendChild(w);let I=v("div","persona-approval-body");if(g){let de=v("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!h,c){let Y=v("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Y.style.color=r.descriptionColor),Y.textContent=t.description,de.appendChild(Y)}if(u){let Y=v("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(Y.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Y.style.color=r.parameterTextColor),Y.textContent=bo(t.parameters),de.appendChild(Y)}I.appendChild(de)}if(t.reason){let de=v("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Y=v("span","persona-approval-reason-label");Y.textContent=`${(U=r==null?void 0:r.reasonLabel)!=null?U:"Agent's stated reason:"} `,de.append(Y,document.createTextNode(t.reason)),I.appendChild(de)}let R=v("div","persona-approval-actions"),P=null,A=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(W.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let de=v("div","persona-approval-split"),Y=v("button","persona-approval-primary");Y.type="button",Y.setAttribute("data-action","always"),A(Y),Y.append((te=r==null?void 0:r.approveLabel)!=null?te:"Always allow",sl("\u23CE"));let Le=v("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),A(Le);let Pe=he("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(Y,Le),R.append(de,W),W.append(sl("Esc"));let ae=v("div","persona-approval-menu"),fe=v("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",sl("\u2318\u23CE")),ae.appendChild(fe),P=Um({anchor:de,content:ae,placement:"bottom-start",matchAnchorWidth:!0}),n.popovers.set(e.id,P),fe.addEventListener("click",()=>{Vo(n,e.id),o()})}else{let de=v("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),A(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),R.append(de,W)}return I.appendChild(R),l.appendChild(I),l.addEventListener("click",de=>{let Y=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!Y)return;let Le=Y.getAttribute("data-action");if(Le==="toggle-params"){let Pe=l.querySelector('[data-role="params"]');if(Pe){let ae=Pe.hidden;Pe.hidden=!ae,w.setAttribute("aria-expanded",ae?"true":"false"),w.setAttribute("aria-label",ae?b:m),jo.set(e.id,ae)}return}if(Le==="toggle-menu"){P==null||P.toggle();return}if(Le==="always"){Vo(n,e.id),o({remember:!0});return}if(Le==="allow"){Vo(n,e.id),o();return}if(Le==="deny"){Vo(n,e.id),s();return}}),l},jm=()=>{let n=xv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let l=r==null?void 0:r.approval;if(!l)return null;let d=Cv(a);if(l.status!=="pending"){if(Vo(n,r.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return Tv(l)}qm(n,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=Mv(n,r,l,d,o,s,c);if(c){n.pendingOrder.includes(r.id)||n.pendingOrder.push(r.id),n.latestPendingApprovalId=n.pendingOrder[n.pendingOrder.length-1];let g=h=>{zm(h)||r.id===n.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Vo(n,r.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?o():o({remember:!0})))};n.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return u}},teardown:()=>{for(let r of[...n.keyHandlers.keys(),...n.popovers.keys()])Vo(n,r);n.latestPendingApprovalId=null}}};var Vm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,l,d,c)=>{n.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(t=null),!o||!o.length||!u&&(l!=null?l:s?s.getMessages():[]).some(S=>S.role==="user"))return;let g=document.createDocumentFragment(),h=s?s.isStreaming():!1,m=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(b=>{let w=v("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");w.type="button",w.textContent=b,w.disabled=h,d!=null&&d.fontFamily&&(w.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(w.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY),w.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),g.appendChild(w),e.push(w)}),n.appendChild(g),u){let b=JSON.stringify(o);b!==t&&(t=b,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ca=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var da=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Ev=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),kv=new Set(["step_start","execution_start"]),Lv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Pv=new Set(["step_complete","agent_turn_complete"]),Iv=new Set(["flow_complete","agent_complete"]),Km=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Qm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),qn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Ko=(n,e)=>{let t=n[e];return Qm(t)?t:void 0};function al(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ii(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Wv(n,e){return typeof e.type=="string"?e.type:n}function Rv(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Hv(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Gm(n){var r,o,s,a,l;let e=Ko(n,"result"),t=[Ko(n,"tokens"),Ko(n,"totalTokens"),e?Ko(e,"tokens"):void 0,Ko(n,"usage"),e?Ko(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(l=(s=qn(n.outputTokens))!=null?s:qn(n.completionTokens))!=null?l:e?(a=qn(e.outputTokens))!=null?a:qn(e.completionTokens):void 0}function Bv(n){var t,r,o,s,a;let e=Ko(n,"result");return(a=(o=(r=(t=qn(n.executionTime))!=null?t:qn(n.executionTimeMs))!=null?r:qn(n.execution_time))!=null?o:qn(n.duration))!=null?a:e?(s=qn(e.executionTime))!=null?s:qn(e.executionTimeMs):void 0}function Dv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var pa=class{constructor(e=Dv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:ii(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!Qm(t)){Km.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Wv(e,t),o=this.now();if(Ev.has(r)){this.startRun(o);return}if(kv.has(r)){this.run||this.startRun(o);return}if(Lv.has(r)){if(!Hv(r,t))return;let a=Rv(t);if(!a)return;this.run||this.startRun(o);let l=this.run;(s=l.firstDeltaAt)!=null||(l.firstDeltaAt=o),l.visibleCharCount+=a.length;let d=l.exactOutputTokens+al(l.visibleCharCount),c=o-l.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ii(d,c),outputTokens:d,durationMs:c,source:l.exactOutputTokens>0?"usage":"estimate"};return}if(Pv.has(r)){if(!this.run)return;let a=this.run,l=Gm(t);l!==void 0&&(a.exactOutputTokens+=l,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+al(a.visibleCharCount),u=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:ii(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(Iv.has(r)){if(!this.run)return;let a=this.run,l=Gm(t),d=l!=null?l:a.exactOutputTokens+al(a.visibleCharCount),c=l!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:ii(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(Km.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Bv(t);return s!=null?s:r-e.startedAt}};function As(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Nv={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)"}},Fv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ov=["flowName","stepName","reasoningText","text","name","tool","toolName"],_v=100;function $v(n,e){let t={...Nv,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Fv}function Uv(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function zv(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function qv(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function jv(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Vv(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Kv(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Gv(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function Qv(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let l=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(l)return l}return a();function a(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,l.appendChild(d),l}}function il(n,e,t,r,o,s,a,l){var h;let d=o.has(n.id),c=v("div","persona-border-b persona-border-persona-divider persona-text-xs");As(c,(h=r.classNames)==null?void 0:h.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&l){let m=u.renderEventStreamRow({event:n,index:e,config:l,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(g()),c;function g(){var F,te;let m=v("div",""),b=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");b.setAttribute("data-event-id",n.id);let w=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=he(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&w.appendChild(S);let B=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(F=r.timestampFormat)!=null?F:"relative";B.textContent=T==="relative"?Uv(n.timestamp,t):zv(n.timestamp);let I=null;r.showSequenceNumbers!==!1&&(I=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(e+1));let R=$v(n.type,r.badgeColors),P=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=R.bg,P.style.color=R.text,P.style.borderColor=R.text+"50",P.textContent=n.type;let A=(te=r.descriptionFields)!=null?te:Ov,W=qv(n.payload,A),z=null;W&&(z=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),z.textContent=W);let $=v("div","persona-flex-1 persona-min-w-0"),k=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),U=he("clipboard","12px","currentColor",1.5);return U&&k.appendChild(U),k.addEventListener("click",async Ee=>{Ee.stopPropagation(),await jv(Vv(n)),k.innerHTML="";let de=he("check","12px","currentColor",1.5);de&&k.appendChild(de),setTimeout(()=>{k.innerHTML="";let Y=he("clipboard","12px","currentColor",1.5);Y&&k.appendChild(Y)},1500)}),b.appendChild(w),b.appendChild(B),I&&b.appendChild(I),b.appendChild(P),z&&b.appendChild(z),b.appendChild($),b.appendChild(k),m.appendChild(b),d&&m.appendChild(Qv(n,a,l)),m}}function Xm(n){var b,w,S,B,T;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,l=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(l==null?void 0:l.enabled)!==!1,c=(w=l==null?void 0:l.iconName)!=null?w:"arrow-down",u=(S=l==null?void 0:l.label)!=null?S:"",g=(T=(B=o==null?void 0:o.features)==null?void 0:B.eventStream)!=null?T:{},h=s.find(I=>I.renderEventStreamView);if(h!=null&&h.renderEventStreamView&&o){let I=h.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return m();function m(){let I=g.classNames,R=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");As(R,I==null?void 0:I.panel);let P=[],A="",W="",z=null,$=[],k={},U=0,F=Ua(),te=0,Ee=0,de=!1,Y=null,Le=!1,Pe=0,ae=new Set,fe=new Map,ne="",re="",ce=null,Ce,_e,V,X,Ae=null,J=null,ie=null;function Se(){let ge=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),H=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(As(H,I==null?void 0:I.headerBar),a){J=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Ae=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",ie=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ie.style.display="none",ie.style.pointerEvents="none";let Ft=J,Yt=ie,hr=()=>{if(!Yt.textContent)return;let nr=Ft.getBoundingClientRect(),rr=ge.getBoundingClientRect();Yt.style.left=`${nr.left-rr.left}px`,Yt.style.top=`${nr.bottom-rr.top+4}px`,Yt.style.display="block"},Wr=()=>{Yt.style.display="none"};J.addEventListener("mouseenter",hr),J.addEventListener("mouseleave",Wr),J.appendChild(Ae)}let be=v("div","persona-flex-1");Ce=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let le=v("option","");le.value="",le.textContent="All events (0)",Ce.appendChild(le),_e=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),_e.type="button",_e.title="Copy All";let Ke=he("clipboard-copy","12px","currentColor",1.5);Ke&&_e.appendChild(Ke);let Lt=v("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",_e.appendChild(Lt),J&&H.appendChild(J),H.appendChild(be),H.appendChild(Ce),H.appendChild(_e);let Et=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");As(Et,I==null?void 0:I.searchBar);let vt=he("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");vt&&Rt.appendChild(vt),V=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),As(V,I==null?void 0:I.searchInput),V.type="text",V.placeholder="Search event payloads...",X=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),X.type="button",X.style.display="none";let Qt=he("x","12px","currentColor",2);return Qt&&X.appendChild(Qt),Et.appendChild(Rt),Et.appendChild(V),Et.appendChild(X),ge.appendChild(H),ge.appendChild(Et),ie&&ge.appendChild(ie),ge}let Je,et=s.find(ge=>ge.renderEventStreamToolbar);if(et!=null&&et.renderEventStreamToolbar&&o){let ge=et.renderEventStreamToolbar({config:o,defaultRenderer:()=>Se(),eventCount:e.getSize(),filteredCount:0,onFilterChange:H=>{A=H,ye(),Ct()},onSearchChange:H=>{W=H,ye(),Ct()}});Je=ge!=null?ge:Se()}else Je=Se();let Wt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Wt.style.display="none";function ft(){if(!a||!Ae||!J)return;let ge=a(),H=Kv(ge);Ae.textContent=H;let be=Gv(ge);ie&&(ie.textContent=be,be||(ie.style.display="none")),J.setAttribute("aria-label",be?`Throughput: ${H}, ${be}`:`Throughput: ${H}`)}let rt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),ue=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ue.style.height="100%";let Q=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");As(Q,I==null?void 0:I.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let it=he(c,"14px","currentColor",2);it&&Q.appendChild(it);let je=v("span","");je.textContent=u,Q.appendChild(je);let Te=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Te.style.display="none",rt.appendChild(ue),rt.appendChild(Te),rt.appendChild(Q),R.setAttribute("tabindex","0"),R.appendChild(Je),R.appendChild(Wt),R.appendChild(rt);function we(){let ge=e.getAll(),H={};for(let Et of ge)H[Et.type]=(H[Et.type]||0)+1;let be=Object.keys(H).sort(),le=be.length!==$.length||!be.every((Et,vt)=>Et===$[vt]),gt=!le&&be.some(Et=>H[Et]!==k[Et]),Ke=ge.length!==Object.values(k).reduce((Et,vt)=>Et+vt,0);if(!le&&!gt&&!Ke||($=be,k=H,!Ce))return;let Lt=Ce.value;if(Ce.options[0].textContent=`All events (${ge.length})`,le){for(;Ce.options.length>1;)Ce.remove(1);for(let Et of be){let vt=v("option","");vt.value=Et,vt.textContent=`${Et} (${H[Et]||0})`,Ce.appendChild(vt)}Lt&&be.includes(Lt)?Ce.value=Lt:Lt&&(Ce.value="",A="")}else for(let Et=1;Et<Ce.options.length;Et++){let vt=Ce.options[Et];vt.textContent=`${vt.value} (${H[vt.value]||0})`}}function Ye(){let ge=e.getAll();if(A&&(ge=ge.filter(H=>H.type===A)),W){let H=W.toLowerCase();ge=ge.filter(be=>be.type.toLowerCase().includes(H)||be.payload.toLowerCase().includes(H))}return ge}function qt(){return A!==""||W!==""}function ye(){U=0,te=0,F.resume(),Q.style.display="none"}function pe(ge){ae.has(ge)?ae.delete(ge):ae.add(ge),ce=ge;let H=ue.scrollTop,be=F.isFollowing();Le=!0,F.pause(),Ct(),ue.scrollTop=H,be&&F.resume(),Le=!1}function Cn(){return vo(ue,50)}function Ct(){Ee=Date.now(),de=!1,ft(),we();let ge=e.getEvictedCount();ge>0?(Wt.textContent=`${ge.toLocaleString()} older events truncated`,Wt.style.display=""):Wt.style.display="none",P=Ye();let H=P.length,be=e.getSize()>0;H===0&&be&&qt()?(Te.textContent=W?`No events matching '${W}'`:"No events matching filter",Te.style.display="",ue.style.display="none"):(Te.style.display="none",ue.style.display=""),_e&&(_e.title=qt()?`Copy Filtered (${H})`:"Copy All"),d&&!F.isFollowing()&&H>U&&(te+=H-U,je.textContent=u?`${u}${te>0?` (${te})`:""}`:"",Q.style.display=""),U=H;let le=e.getAll(),gt=le.length>0?le[0].timestamp:0,Ke=new Set(P.map(vt=>vt.id));for(let vt of ae)Ke.has(vt)||ae.delete(vt);let Lt=A!==ne||W!==re,Et=fe.size===0&&P.length>0;if(Lt||Et||P.length===0){ue.innerHTML="",fe.clear();let vt=document.createDocumentFragment();for(let Rt=0;Rt<P.length;Rt++){let Qt=il(P[Rt],Rt,gt,g,ae,pe,s,o);fe.set(P[Rt].id,Qt),vt.appendChild(Qt)}ue.appendChild(vt),ne=A,re=W,ce=null}else{if(ce!==null){let Rt=fe.get(ce);if(Rt&&Rt.parentNode===ue){let Qt=P.findIndex(Ft=>Ft.id===ce);if(Qt>=0){let Ft=il(P[Qt],Qt,gt,g,ae,pe,s,o);ue.insertBefore(Ft,Rt),Rt.remove(),fe.set(ce,Ft)}}ce=null}let vt=new Set(P.map(Rt=>Rt.id));for(let[Rt,Qt]of fe)vt.has(Rt)||(Qt.remove(),fe.delete(Rt));for(let Rt=0;Rt<P.length;Rt++){let Qt=P[Rt];if(!fe.has(Qt.id)){let Ft=il(Qt,Rt,gt,g,ae,pe,s,o);fe.set(Qt.id,Ft),ue.appendChild(Ft)}}}F.isFollowing()&&(ue.scrollTop=ue.scrollHeight)}function hn(){if(Date.now()-Ee>=_v){Y!==null&&(cancelAnimationFrame(Y),Y=null),Ct();return}de||(de=!0,Y=requestAnimationFrame(()=>{Y=null,Ct()}))}let gr=(ge,H)=>{if(!_e)return;_e.innerHTML="";let be=he(ge,"12px","currentColor",1.5);be&&_e.appendChild(be);let le=v("span","persona-text-xs");le.textContent="Copy All",_e.appendChild(le),setTimeout(()=>{_e.innerHTML="";let gt=he("clipboard-copy","12px","currentColor",1.5);gt&&_e.appendChild(gt);let Ke=v("span","persona-text-xs");Ke.textContent="Copy All",_e.appendChild(Ke),_e.disabled=!1},H)},fr=async()=>{if(_e){_e.disabled=!0;try{let ge;qt()?ge=P:t?(ge=await t(),ge.length===0&&(ge=e.getAll())):ge=e.getAll();let H=ge.map(be=>{try{return JSON.parse(be.payload)}catch{return be.payload}});await navigator.clipboard.writeText(JSON.stringify(H,null,2)),gr("check",1500)}catch{gr("x",1500)}}},Ue=()=>{Ce&&(A=Ce.value,ye(),Ct())},M=()=>{!V||!X||(X.style.display=V.value?"":"none",z&&clearTimeout(z),z=setTimeout(()=>{W=V.value,ye(),Ct()},150))},me=()=>{!V||!X||(V.value="",W="",X.style.display="none",z&&clearTimeout(z),ye(),Ct())},Me=()=>{if(Le)return;let ge=ue.scrollTop,{action:H,nextLastScrollTop:be}=za({following:F.isFollowing(),currentScrollTop:ge,lastScrollTop:Pe,nearBottom:Cn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=be,H==="resume"?(F.resume(),te=0,Q.style.display="none"):H==="pause"&&(F.pause(),d&&(je.textContent=u,Q.style.display=""))},ke=ge=>{let H=qa({following:F.isFollowing(),deltaY:ge.deltaY,nearBottom:Cn(),resumeWhenNearBottom:!0});H==="pause"?(F.pause(),d&&(je.textContent=u,Q.style.display="")):H==="resume"&&(F.resume(),te=0,Q.style.display="none")},Re=()=>{d&&(ue.scrollTop=ue.scrollHeight,F.resume(),te=0,Q.style.display="none")},tt=ge=>{let H=ge.target;if(!H||H.closest("button"))return;let be=H.closest("[data-event-id]");if(!be)return;let le=be.getAttribute("data-event-id");le&&pe(le)},Qe=ge=>{if((ge.metaKey||ge.ctrlKey)&&ge.key==="f"){ge.preventDefault(),V==null||V.focus(),V==null||V.select();return}ge.key==="Escape"&&(V&&document.activeElement===V?(me(),V.blur(),R.focus()):r&&r())};_e&&_e.addEventListener("click",fr),Ce&&Ce.addEventListener("change",Ue),V&&V.addEventListener("input",M),X&&X.addEventListener("click",me),ue.addEventListener("scroll",Me),ue.addEventListener("wheel",ke,{passive:!0}),ue.addEventListener("click",tt),Q.addEventListener("click",Re),R.addEventListener("keydown",Qe);function ht(){z&&clearTimeout(z),Y!==null&&(cancelAnimationFrame(Y),Y=null),de=!1,fe.clear(),_e&&_e.removeEventListener("click",fr),Ce&&Ce.removeEventListener("change",Ue),V&&V.removeEventListener("input",M),X&&X.removeEventListener("click",me),ue.removeEventListener("scroll",Me),ue.removeEventListener("wheel",ke),ue.removeEventListener("click",tt),Q.removeEventListener("click",Re),R.removeEventListener("keydown",Qe)}return{element:R,update:hn,destroy:ht}}}function Jm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",l=document.createElement("div");l.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",l.style.border="1px solid var(--persona-border, #e5e7eb)",l.style.backgroundColor="var(--persona-surface, #ffffff)",l.style.cursor="pointer",l.tabIndex=0,l.setAttribute("role","button"),l.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&l.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let h=document.createElement("span");h.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",h.style.backgroundColor="var(--persona-primary, #171717)",h.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(h);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(c.append(u,g),l.append(d,c),o==="complete"){let h=document.createElement("button");h.type="button",h.textContent="Download",h.title=`Download ${t}`,h.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",h.style.border="1px solid var(--persona-border, #e5e7eb)",h.style.color="var(--persona-text, #1f2937)",h.style.backgroundColor="transparent",h.style.cursor="pointer",h.setAttribute("data-download-artifact",r),l.append(h)}return l}var Ym=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",l=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",u=t({artifact:{artifactId:l,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Jm(n,e)});if(u)return u}return Jm(n,e)};var ll=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Go=new ll;Go.register("PersonaArtifactCard",Ym);function Xv(n){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=v("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function Zm(n,e){var _e,V,X,Ae;let t=(V=(_e=n.features)==null?void 0:_e.artifacts)==null?void 0:V.layout,o=((X=t==null?void 0:t.toolbarPreset)!=null?X:"default")==="document",s=(Ae=t==null?void 0:t.panePadding)==null?void 0:Ae.trim(),a=n.markdown?xa(n.markdown):null,l=Ca(n.sanitize),d=J=>{let ie=a?a(J):fo(J);return l?l(ie):ie},c=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let g=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),o&&g.classList.add("persona-artifact-pane-document");let h=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");h.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&h.classList.add("persona-artifact-toolbar-document");let m=v("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let b=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let w="rendered",S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),B=o?xn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):xn({icon:"eye",label:"Rendered view"}),T=o?xn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):xn({icon:"code-2",label:"Source"}),I=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),R=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,A=t==null?void 0:t.documentToolbarCopyMenuItems,W=!!(P&&A&&A.length>0),z=null,$,k=null,U=null;if(o&&(R||P)&&!W){if($=R?Xi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):xn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let J=he("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else o&&W?(z=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=R?Xi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):xn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=xn({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"}}),z.append($,k)):o?$=xn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=xn({icon:"copy",label:"Copy"});let F=o?xn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):xn({icon:"refresh-cw",label:"Refresh"}),te=o?xn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):xn({icon:"x",label:"Close"}),Ee=()=>{var et,Wt,ft;let J=(et=fe.find(rt=>rt.id===ne))!=null?et:fe[fe.length-1],ie=(Wt=J==null?void 0:J.id)!=null?Wt:null,Se=(J==null?void 0:J.artifactType)==="markdown"&&(ft=J.markdown)!=null?ft:"",Je=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Se,jsonPayload:Je,id:ie}},de=async()=>{var et;let{markdown:J,jsonPayload:ie}=Ee(),Se=(et=fe.find(Wt=>Wt.id===ne))!=null?et:fe[fe.length-1],Je=(Se==null?void 0:Se.artifactType)==="markdown"?J:Se?ie:"";try{await navigator.clipboard.writeText(Je)}catch{}};if($.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&W){let{markdown:ie,jsonPayload:Se,id:Je}=Ee();try{await J({actionId:"primary",artifactId:Je,markdown:ie,jsonPayload:Se})}catch{}return}await de()}),k&&(A!=null&&A.length)){let J=()=>{var Se;return(Se=g.closest("[data-persona-root]"))!=null?Se:document.body},ie=()=>{U=ws({items:A.map(Se=>({id:Se.id,label:Se.label})),onSelect:async Se=>{let{markdown:Je,jsonPayload:et,id:Wt}=Ee(),ft=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ft?await ft({actionId:Se,artifactId:Wt,markdown:Je,jsonPayload:et}):Se==="markdown"||Se==="md"?await navigator.clipboard.writeText(Je):Se==="json"||Se==="source"?await navigator.clipboard.writeText(et):await navigator.clipboard.writeText(Je||et)}catch{}},anchor:z!=null?z:k,position:"bottom-right",portal:J()})};g.isConnected?ie():requestAnimationFrame(ie),k.addEventListener("click",Se=>{Se.stopPropagation(),U==null||U.toggle()})}F.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}ce()}),te.addEventListener("click",()=>{var J;u(),(J=e.onDismiss)==null||J.call(e)});let Y=()=>{o&&(B.setAttribute("aria-pressed",w==="rendered"?"true":"false"),T.setAttribute("aria-pressed",w==="source"?"true":"false"))};B.addEventListener("click",()=>{w="rendered",Y(),ce()}),T.addEventListener("click",()=>{w="source",Y(),ce()});let Le=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(h.replaceChildren(),S.append(B,T),z?I.append(z,F,te):I.append($,F,te),h.append(S,Le,I),Y()):(h.appendChild(m),h.appendChild(b)),s&&(h.style.paddingLeft=s,h.style.paddingRight=s);let Pe=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ae=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ae.style.padding=s),g.appendChild(h),g.appendChild(Pe),g.appendChild(ae);let fe=[],ne=null,re=!1,ce=()=>{var Je,et,Wt,ft;let J=o&&fe.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let rt of fe){let ue=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ue.type="button",ue.textContent=rt.title||rt.id.slice(0,8),rt.id===ne&&ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),ue.addEventListener("click",()=>e.onSelect(rt.id)),Pe.appendChild(ue)}ae.replaceChildren();let ie=ne&&fe.find(rt=>rt.id===ne)||fe[fe.length-1];if(!ie)return;if(o){let rt=ie.artifactType==="markdown"?"MD":(Je=ie.component)!=null?Je:"Component",Q=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${Q} \xB7 ${rt}`}else m.textContent="Artifacts";if(ie.artifactType==="markdown"){if(o&&w==="source"){let ue=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ue.textContent=(et=ie.markdown)!=null?et:"",ae.appendChild(ue);return}let rt=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");rt.innerHTML=d((Wt=ie.markdown)!=null?Wt:""),ae.appendChild(rt);return}let Se=ie.component?Go.get(ie.component):void 0;if(Se){let ue={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Q=Se((ft=ie.props)!=null?ft:{},ue);if(Q){ae.appendChild(Q);return}}catch{}}ae.appendChild(Xv(ie))},Ce=()=>{var ie;let J=fe.length>0;if(g.classList.toggle("persona-hidden",!J),c){let Se=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,et=((ie=Se==null?void 0:Se.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&et&&re?(c.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:c,update(J){var ie,Se,Je;fe=J.artifacts,ne=(Je=(Se=J.selectedId)!=null?Se:(ie=J.artifacts[J.artifacts.length-1])==null?void 0:ie.id)!=null?Je:null,fe.length>0&&(re=!0),ce(),Ce()},setMobileOpen(J){re=J,!J&&c?(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):Ce()}}}function tr(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function eg(n,e){var s,a,l,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!tr(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(l=t==null?void 0:t.paneBorder)==null?void 0:l.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function Jv(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function li(n,e){var d,c,u,g,h,m,b,w,S,B;if(!tr(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),Jv(n),eg(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(g=t==null?void 0:t.paneWidth)!=null?g:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(h=t==null?void 0:t.paneMaxWidth)!=null?h:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(b=t==null?void 0:t.panePadding)==null?void 0:b.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(w=t==null?void 0:t.documentToolbarIconColor)==null?void 0:w.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let l=(B=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:B.trim();l?n.style.setProperty("--persona-artifact-doc-toggle-active-border",l):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),eg(n,e)}var tg=["panel","seamless"];function ci(n,e){var l,d,c,u,g,h;for(let m of tg)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!tr(e))return;let t=(d=(l=e.features)==null?void 0:l.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=tg.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=t==null?void 0:t.paneShadow)==null?void 0:g.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((h=t.unifiedSplitOuterRadius)==null?void 0:h.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ng(n,e){var t,r,o;return!e||!tr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Yv(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function Zv(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function ew(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function tw(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function rg(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function og(n,e,t,r,o,s){let a=Yv(o,200),l=tw(e,t,r,200);l=Math.max(a,l);let d=Zv(s);return d!==null&&(l=Math.min(l,d)),ew(n,a,l)}var sg={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"}},cl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,w,S;if(s.dataset.enhanced==="true")return;let a=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let l=(w=sg[a])!=null?w:sg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),c=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let B=v("p","persona-text-sm persona-text-persona-muted");B.textContent=l.description,d.appendChild(B)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(B=>{var A,W;let T=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${B.name}`;let I=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=B.label,T.appendChild(I);let R=(A=B.type)!=null?A:"text",P;R==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=R),P.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",P.id=`${e.id}-${a}-${B.name}`,P.name=B.name,P.placeholder=(W=B.placeholder)!=null?W:"",B.required&&(P.required=!0),T.appendChild(P),u.appendChild(T)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(S=l.submitLabel)!=null?S:"Submit",g.appendChild(h),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async B=>{var P,A;B.preventDefault();let T=(P=t.formEndpoint)!=null?P:"/form",I=new FormData(u),R={};I.forEach((W,z)=>{R[z]=W}),R.type=a,m.disabled=!0,h.textContent="Submitting\u2026";try{let W=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let z=await W.json();h.textContent=(A=z.message)!=null?A:"Thanks! We'll be in touch soon.",z.success&&z.nextPrompt&&await r.sendMessage(String(z.nextPrompt))}catch(W){h.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var dl=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var l,d;return((l=a.priority)!=null?l:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},pl=new dl;var ag=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(l=>{try{l(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var nw=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},rw=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},ml=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=nw(n),t=rw(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ul=n=>typeof n=="string"?n:n==null?"":String(n),ua={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:ul(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=ul(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ul(t.text)}}},ig=n=>Array.isArray(n)?n.map(e=>String(e)):[],gl=n=>{let e=new Set(ig(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(ig(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?n.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),r();let d={action:l,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let u=()=>{n.emit("action:resubmit",d)},g=c(l,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let h=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:h,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var ow=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},sw=n=>n.map(e=>({...e,streaming:!1})),aw=n=>n.map(e=>({...e,status:"complete"})),lg=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?ow(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?sw(t.messages):void 0,artifacts:t.artifacts?aw(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as hS,STR as yS,OBJ as bS}from"partial-json";function cg(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Go.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:l=>{o&&o(l)}};try{return s(n.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function dg(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function fl(n){let e=dg(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function pg(n){let e=dg(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ug(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:c=iw}=n,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=r,m.appendChild(b);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,m.appendChild(w),h.appendChild(m);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let A=1;A<=5;A++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),W.title=c[A-1],W.dataset.rating=String(A),W.innerHTML=`
|
|
39
|
+
`,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Ft(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=a.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let T=a.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let T=a.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let I=parseFloat(T)||24,z=oe(a.agentIconName,I*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let T=a.agentIconSize??"40px";w.style.height=T,w.style.width=T,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=a.callToActionIconSize??"32px";f.style.height=T,f.style.width=T,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 I=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,I=(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 z=parseFloat(T)||24,N=Math.max(z-I,8),x=oe(a.callToActionIconName,N,"currentColor",2);x?f.appendChild(x):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&xn[a.position]?xn[a.position]:xn["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",P="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?P:`${C} ${b}`,l||(n.style.zIndex=String(a.zIndex??zt));let H="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??H,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}};var Hp=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=Wp(t),s=Bp(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},al=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>sl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=sl(t,n);return{instance:r,element:r.element}};var Ym=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Zm=(t,e)=>{if(!t)return null;let n=Ym(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},eh=(t,e)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},th=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},il=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},ll=320,Op=320,nh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),oh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),rh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),sh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),ah=t=>{if(!t||t.length===0)return null;let e=Ne("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Ne("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=oe(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ne("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},ih=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ns(o.ref,{readonly:!0,render:e}))}return n},Dp="\uE000",Np="\uE001",lh=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${Dp}${r}:${w}${Np}`,a=e.map((w,f)=>w.kind==="text"?w.text:s(f)).join(""),l=n(a);if(!e.every((w,f)=>w.kind==="text"||l.includes(s(f)))){t.replaceChildren(ih(e,o));return}t.innerHTML=l;let d=new RegExp(`${Dp}${r}:(\\d+)${Np}`),c=document.createTreeWalker(t,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 b=d.exec(f.data);b;b=d.exec(f.data)){let C=e[Number(b[1])],P=f.splitText(b.index);P.data=P.data.slice(b[0].length),C?.kind==="mention"&&P.parentNode?.insertBefore(ns(C.ref,{readonly:!0,render:o}),P),f=P}}},ch=(t,e,n)=>{if(t.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let d=m("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${ll}px`,d.style.maxHeight=`${Op}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}),th(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}},dh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!il(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ll}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},ph=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!il(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${ll}px`,r.style.maxHeight=`${Op}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},uh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!il(o.data))return;let r=m("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},hs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},fh=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:hs};if(e){let r=e(o);if(r!==null)return r}return hs()},gh=(t,e)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Fp=(t,e,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},mh=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},hh=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let b=m("div");return b.style.display="none",b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id),b}let l=e.visibility??"hover",p=e.align??"right",d=e.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${t.id}`,w.setAttribute("data-actions-for",t.id);let f=(b,C,P)=>{let H=Wt({icon:b,label:C,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",P),H};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},cl=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",b=mh(t.role,l),C=m("div",b.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=nh(t),H=t.content?.trim()??"",T=P.length>0&&H===pa,I=Pa(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,N=t.role==="assistant"&&I.type!=="none"?ur(I.type,z):null,x=t.role==="assistant"&&N?.isAnimating?.(t)===!0,U=t.role==="assistant"&&N!==null&&(!!t.streaming||x);U&&N?.bubbleClass&&C.classList.add(N.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),t.streaming&&V.classList.add("persona-content-streaming"),U&&N&&(N.containerClass&&V.classList.add(N.containerClass),V.style.setProperty("--persona-stream-step",`${I.speed}ms`),V.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let J=U?Ia(t.content??"",I.buffer,N,t,!!t.streaming):t.content??"",D=()=>{let Z=e({text:J,message:t,streaming:!!t.streaming,raw:t.rawContent});return U&&N?.wrap==="char"?ds(Z,"char",t.id,{skipTags:N.skipTags}):U&&N?.wrap==="word"?ds(Z,"word",t.id,{skipTags:N.skipTags}):Z},$=null;if(T?($=document.createElement("div"),$.innerHTML=D(),$.style.display="none",V.appendChild($)):t.contentSegments?.length?lh(V,t.contentSegments,Z=>e({text:Z,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=D(),U&&N?.useCaret&&!T&&H){let Z=Ra(),be=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=be[be.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(Z,ve.nextSibling);else{let ue=V.lastElementChild;ue?ue.appendChild(Z):V.appendChild(Z)}}if(u&&f==="inline"&&t.createdAt){let Z=Fp(t,d,"span");Z.classList.add("persona-timestamp-inline");let be=V.lastElementChild;be?be.appendChild(Z):V.appendChild(Z)}if(P.length>0){let Z=ch(P,!T&&!!H,()=>{T&&$&&($.style.display="")});Z?C.appendChild(Z):T&&$&&($.style.display="")}let fe=oh(t);if(fe.length>0){let Z=dh(fe);Z&&C.appendChild(Z)}let he=rh(t);if(he.length>0){let Z=ph(he);Z&&C.appendChild(Z)}let Ee=sh(t);if(Ee.length>0){let Z=uh(Ee);Z&&C.appendChild(Z)}let xe=t.contentSegments?.length?null:ah(t.contextMentions);if(xe&&C.appendChild(xe),C.appendChild(V),u&&f==="below"&&t.createdAt){let Z=Fp(t,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let te=t.role==="assistant"?Zm(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Z=!!(J&&J.trim()),be=I.placeholder==="skeleton",ve=be&&I.buffer==="line"&&Z;if(Z)ve&&C.appendChild(ps());else if(be)C.appendChild(ps());else{let ue=fh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ue&&C.appendChild(ue)}}if(te&&t.stopReason&&!t.streaming&&(H||(V.style.display="none"),C.appendChild(eh(t.stopReason,te))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=hh(t,o,r);C.appendChild(Z)}if(!c||t.role==="system")return C;let Y=m("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),le=gh(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Y.append(C,le):Y.append(le,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y};var fr=new Set,yh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),bh=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
40
|
+
`):""},_p=(t,e)=>{let n=fr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=oe(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")},dl=(t,e)=>{let n=t.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&fr.has(t.id),l=n.status!=="complete",p=bh(t,r.previewMaxLines??3),d=m("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",f=e?.reasoning??{},b=String(n.startedAt??Date.now()),C=()=>{let he=m("span","");return he.setAttribute("data-tool-elapsed",b),he.textContent=ia(n),he},P=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:ia(n),createElapsedElement:C});typeof P=="string"&&P.trim()?(u.textContent=P,c.appendChild(u)):P instanceof HTMLElement?c.appendChild(P):(u.textContent=w,c.appendChild(u));let H=m("span","persona-text-xs persona-text-persona-primary");H.textContent=xd(n),c.appendChild(H);let M=r.loadingAnimation??"none",T=f.activeTextTemplate,I=f.completeTextTemplate,z=l?T:I,N=P instanceof HTMLElement,x=(he,Ee)=>{u.textContent="";let xe=la(he,""),te=0;for(let ge of xe){let Y=ge.styles.length>0?(()=>{let le=m("span",ge.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(ge.isDuration&&l)Y.appendChild(C());else{let le=ge.isDuration?ia(n):ge.text;Ee?te=ro(Y,le,te):Y.appendChild(document.createTextNode(le))}}};if(!N&&z)if(H.style.display="none",u.style.display="",l&&M!=="none"){let he=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),M==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),x(z,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),x(z,!0))}else x(z,!1);else if(!N&&l&&M!=="none"){u.style.display="";let he=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${he}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||w;u.textContent="",ro(u,Ee,0)}n.status==="complete"&&(u.style.display="none")}else N||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=m("div","persona-flex persona-items-center");let Ee=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?U.appendChild(Ee):U.textContent=a?"Hide":"Show";let xe=m("div","persona-flex persona-items-center persona-ml-auto");xe.append(U),d.append(c,xe)}else d.append(c);let V=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let he=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});yh(V,he)||(V.textContent=p),V.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,V),o;let J=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");J.style.display=a?"":"none";let D=n.chunks.join(""),$=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return $.textContent=D||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),J.appendChild($),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let Ee=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?U.appendChild(Ee):U.textContent=a?"Hide":"Show"}J.style.display=a?"":"none",V.style.display=a?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(d,V,J),o};var gr=new Set,vh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),wh=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
|
|
41
|
+
`);let r=no(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
42
|
+
`):""},pl=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},xh=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=wh(t,o?.previewMaxLines??3),a=n?Cd(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=_i(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=_i(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},$p=(t,e,n)=>{let o=gr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=oe(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")},ul=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&gr.has(t.id),{summary:p,previewText:d,isActive:c}=xh(t,e),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),C=()=>{let D=m("span","");return D.setAttribute("data-tool-elapsed",b),D.textContent=Gr(n),D},P=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:Gr(n),createElapsedElement:C});typeof P=="string"&&P.trim()?(f.textContent=P,w.appendChild(f)):P instanceof HTMLElement?w.appendChild(P):(f.textContent=p,w.appendChild(f));let H=s.loadingAnimation??"none",M=o.activeTextTemplate,T=o.completeTextTemplate,I=c?M:T,z=P instanceof HTMLElement,N=(D,$)=>{f.textContent="";let fe=n.name?.trim()||"tool",he=la(D,fe),Ee=0;for(let xe of he){let te=xe.styles.length>0?(()=>{let ge=m("span",xe.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(ge),ge})():f;if(xe.isDuration&&c)te.appendChild(C());else{let ge=xe.isDuration?Gr(n):xe.text;$?Ee=ro(te,ge,Ee):te.appendChild(document.createTextNode(ge))}}};if(!z)if(c&&H!=="none"){let D=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),H==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),I&&N(I,!1);else if(f.classList.add(`persona-tool-loading-${H}`),f.style.setProperty("--persona-tool-anim-duration",`${D}ms`),H==="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)),I)N(I,!0);else{let $=f.textContent||p;f.textContent="",ro(f,$,0)}}else I&&N(I,!1);let x=null;if(a){x=m("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(l?"chevron-up":"chevron-down",16,D,2);$?x.appendChild($):x.textContent=l?"Hide":"Show";let fe=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");fe.append(x),u.append(w,fe)}else u.append(w);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:d,isActive:c,config:e??{}});vh(U,D)||(U.textContent=d),U.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,U),r;let V=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=l?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let D=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,V.appendChild(D)}if(n.args!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let fe=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",pl(fe,o),fe.textContent=no(n.args),D.append($,fe),V.appendChild(D)}if(n.chunks&&n.chunks.length){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let fe=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",pl(fe,o),fe.textContent=n.chunks.join(""),D.append($,fe),V.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let fe=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");fe.style.fontSize="0.75rem",fe.style.lineHeight="1rem",pl(fe,o),fe.textContent=no(n.result),D.append($,fe),V.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,V.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),x){x.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(l?"chevron-up":"chevron-down",16,D,2);$?x.appendChild($):x.textContent=l?"Hide":"Show"}V.style.display=l?"":"none",U.style.display=l?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(u,U,V),r};var Do=new Map,ja=t=>{let n=(t.startsWith(Dn)?t.slice(Dn.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},zp=t=>t?.approval!==!1?t?.approval:void 0,Up=(t,e)=>{let n=zp(e)?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},jp=(t,e,n)=>{let o=zp(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=oe(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Vp=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Up(t,n);jp(o,s,n),r.style.display=s?"":"none"};var Va=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=m("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=oe(p,20,d,2);c&&l.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),w=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",w.appendChild(f),!r){let x=m("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(Dn)?jr(n.toolName):void 0,P=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),H=!n.toolName,M=P||(H?n.description:`The assistant wants to use \u201C${C??ja(n.toolName)}\u201D.`),T=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=M,u.appendChild(T),n.reason){let x=m("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 U=m("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,x.appendChild(U),x.appendChild(document.createTextNode(n.reason)),u.appendChild(x)}let I=o?.detailsDisplay??"collapsed",z=!!n.description&&!H,N=z||!!n.parameters;if(I!=="hidden"&&N){let x=Up(t.id,e),U=m("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let V=m("span");V.setAttribute("data-approval-details-label","true");let J=m("span","persona-inline-flex persona-items-center");J.setAttribute("data-approval-details-chevron","true"),U.append(V,J),jp(U,x,e),u.appendChild(U);let D=m("div");if(D.setAttribute("data-approval-details","true"),D.style.display=x?"":"none",z){let $=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,D.appendChild($)}if(n.parameters){let $=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=no(n.parameters),D.appendChild($)}u.appendChild(D)}if(r){let x=m("div","persona-flex persona-gap-2 persona-mt-2");x.setAttribute("data-approval-buttons","true");let U=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let V=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",U.appendChild(V));let J=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(J);let D=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let $=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",D.appendChild($));let fe=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(fe),x.append(U,D),u.appendChild(x)}return a.append(l,u),s.appendChild(a),s};var Ch=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qp=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},No=(t,e)=>{qp(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Ah=t=>t?.approval!==!1?t?.approval:void 0,Sh=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},fl=t=>{let e=m("span","persona-approval-kbd");return e.textContent=t,e},Th=(t,e)=>{let n=m("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Dn)?jr(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??ja(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Mh=t=>{let e=m("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&e.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=t.toolName?ja(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Eh=(t,e,n,o,r,s,a)=>{let l=m("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&Sh(e.id,o),f=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=m("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?b:f)):C.setAttribute("data-static","true");let P=m("span","persona-approval-logo"),H=oe("shield-check",16,"currentColor",2);H&&P.appendChild(H),C.appendChild(P);let M=Th(n,o);if(u){let U=m("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let V=oe("chevron-down",14,"currentColor",2);V&&U.appendChild(V),M.append(" "),M.appendChild(U)}C.appendChild(M),l.appendChild(C);let T=m("div","persona-approval-body");if(u){let U=m("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!w,d){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,U.appendChild(V)}if(c){let V=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=no(n.parameters),U.appendChild(V)}T.appendChild(U)}if(n.reason){let U=m("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(V,document.createTextNode(n.reason)),T.appendChild(U)}let I=m("div","persona-approval-actions"),z=null,N=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},x=m("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 U=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),N(V),V.append(o?.approveLabel??"Always allow",fl("\u23CE"));let J=m("button","persona-approval-caret");J.type="button",J.setAttribute("data-action","toggle-menu"),J.setAttribute("aria-label","More options"),N(J);let D=oe("chevron-down",15,"currentColor",2);D&&J.appendChild(D),U.append(V,J),I.append(U,x),x.append(fl("Esc"));let $=m("div","persona-approval-menu"),fe=m("button","persona-approval-menu-item");fe.type="button",fe.append("Allow once",fl("\u2318\u23CE")),$.appendChild(fe),z=Kc({anchor:U,content:$,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),fe.addEventListener("click",()=>{No(t,e.id),r()})}else{let U=m("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),N(U),U.append(o?.approveLabel??"Allow"),I.append(U,x)}return T.appendChild(I),l.appendChild(T),l.addEventListener("click",U=>{let V=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!V)return;let J=V.getAttribute("data-action");if(J==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let $=D.hidden;D.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?b:f),Do.set(e.id,$)}return}if(J==="toggle-menu"){z?.toggle();return}if(J==="always"){No(t,e.id),r({remember:!0});return}if(J==="allow"){No(t,e.id),r();return}if(J==="deny"){No(t,e.id),s();return}}),l},Kp=()=>{let t=Ch();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=Ah(a);if(l.status!=="pending"){if(No(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Mh(l)}qp(t,o.id);let d=p?.enableAlwaysAllow===!0,c=Eh(t,o,l,p,r,s,d);if(d){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=w=>{Gc(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),No(t,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])No(t,o);t.latestPendingApprovalId=null}}};var Gp=t=>{let e=[],n=null;return{buttons:e,render:(r,s,a,l,p,d)=>{t.innerHTML="",e.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(P=>P.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=b=>{switch(b){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(b=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=b,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&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(C),e.push(C)}),t.appendChild(u),c){let b=JSON.stringify(r);b!==n&&(n=b,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var ys=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var bs=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var kh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lh=new Set(["step_start","execution_start"]),Ph=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ih=new Set(["step_complete","agent_turn_complete"]),Rh=new Set(["flow_complete","agent_complete"]),Qp=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Jp=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),sn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Fo=(t,e)=>{let n=t[e];return Jp(n)?n:void 0};function gl(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function qa(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Wh(t,e){return typeof e.type=="string"?e.type:t}function Bh(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Hh(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Xp(t){let e=Fo(t,"result"),n=[Fo(t,"tokens"),Fo(t,"totalTokens"),e?Fo(e,"tokens"):void 0,Fo(t,"usage"),e?Fo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=sn(o.output)??sn(o.outputTokens)??sn(o.completionTokens);if(r!==void 0)return r}return sn(t.outputTokens)??sn(t.completionTokens)??(e?sn(e.outputTokens)??sn(e.completionTokens):void 0)}function Dh(t){let e=Fo(t,"result");return sn(t.executionTime)??sn(t.executionTimeMs)??sn(t.execution_time)??sn(t.duration)??(e?sn(e.executionTime)??sn(e.executionTimeMs):void 0)}function Nh(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var vs=class{constructor(e=Nh){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:qa(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!Jp(n)){Qp.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Wh(e,n),r=this.now();if(kh.has(o)){this.startRun(r);return}if(Lh.has(o)){this.run||this.startRun(r);return}if(Ph.has(o)){if(!Hh(o,n))return;let s=Bh(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+gl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:qa(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Ih.has(o)){if(!this.run)return;let s=this.run,a=Xp(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+gl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:qa(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Rh.has(o)){if(!this.run)return;let s=this.run,a=Xp(n),l=a??s.exactOutputTokens+gl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:qa(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Qp.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Dh(n)??o-e.startedAt}};function mr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Fh={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)"}},Oh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_h=["flowName","stepName","reasoningText","text","name","tool","toolName"],$h=100;function zh(t,e){let n={...Fh,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Oh}function Uh(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function jh(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Vh(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function qh(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function Kh(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function Gh(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Qh(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Xh(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function ml(t,e,n,o,r,s,a,l){let p=r.has(t.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");mr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",t.id);let b=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&b.appendChild(C);let P=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),H=o.timestampFormat??"relative";P.textContent=H==="relative"?Uh(t.timestamp,n):jh(t.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let T=zh(t.type,o.badgeColors),I=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=T.bg,I.style.color=T.text,I.style.borderColor=T.text+"50",I.textContent=t.type;let z=o.descriptionFields??_h,N=Vh(t.payload,z),x=null;N&&(x=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),x.textContent=N);let U=m("div","persona-flex-1 persona-min-w-0"),V=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),J=oe("clipboard","12px","currentColor",1.5);return J&&V.appendChild(J),V.addEventListener("click",async D=>{D.stopPropagation(),await qh(Kh(t)),V.innerHTML="";let $=oe("check","12px","currentColor",1.5);$&&V.appendChild($),setTimeout(()=>{V.innerHTML="";let fe=oe("clipboard","12px","currentColor",1.5);fe&&V.appendChild(fe)},1500)}),f.appendChild(b),f.appendChild(P),M&&f.appendChild(M),f.appendChild(I),x&&f.appendChild(x),f.appendChild(U),f.appendChild(V),w.appendChild(f),p&&w.appendChild(Xh(t,a,l)),w}}function Yp(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(b=>b.renderEventStreamView);if(w?.renderEventStreamView&&r){let b=w.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return f();function f(){let b=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");mr(C,b?.panel);let P=[],H="",M="",T=null,I=[],z={},N=0,x=Ea(),U=0,V=0,J=!1,D=null,$=!1,fe=0,he=new Set,Ee=new Map,xe="",te="",ge=null,Y,le,Z,be,ve=null,ue=null,Te=null;function Ce(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(mr(j,b?.headerBar),a){ue=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ue.style.cursor="help",ve=m("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),ve.textContent="-- tok/s",Te=m("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Te.style.display="none",Te.style.pointerEvents="none";let Je=ue,co=Te,po=()=>{if(!co.textContent)return;let Ss=Je.getBoundingClientRect(),Xt=B.getBoundingClientRect();co.style.left=`${Ss.left-Xt.left}px`,co.style.top=`${Ss.bottom-Xt.top+4}px`,co.style.display="block"},Qa=()=>{co.style.display="none"};ue.addEventListener("mouseenter",po),ue.addEventListener("mouseleave",Qa),ue.appendChild(ve)}let ae=m("div","persona-flex-1");Y=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let tt=m("option","");tt.value="",tt.textContent="All events (0)",Y.appendChild(tt),le=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let lt=oe("clipboard-copy","12px","currentColor",1.5);lt&&le.appendChild(lt);let q=m("span","persona-event-copy-all persona-text-xs");q.textContent="Copy All",le.appendChild(q),ue&&j.appendChild(ue),j.appendChild(ae),j.appendChild(Y),j.appendChild(le);let ze=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");mr(ze,b?.searchBar);let Re=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),We=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Re&&We.appendChild(Re),Z=m("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),mr(Z,b?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",be=m("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),be.type="button",be.style.display="none";let Le=oe("x","12px","currentColor",2);return Le&&be.appendChild(Le),ze.appendChild(We),ze.appendChild(Z),ze.appendChild(be),B.appendChild(j),B.appendChild(ze),Te&&B.appendChild(Te),B}let je,Fe=s.find(B=>B.renderEventStreamToolbar);Fe?.renderEventStreamToolbar&&r?je=Fe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ce(),eventCount:e.getSize(),filteredCount:0,onFilterChange:j=>{H=j,Ie(),ye()},onSearchChange:j=>{M=j,Ie(),ye()}})??Ce():je=Ce();let Pe=m("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Pe.style.display="none";function Be(){if(!a||!ve||!ue)return;let B=a(),j=Gh(B);ve.textContent=j;let ae=Qh(B);Te&&(Te.textContent=ae,ae||(Te.style.display="none")),ue.setAttribute("aria-label",ae?`Throughput: ${j}, ${ae}`:`Throughput: ${j}`)}let at=m("div","persona-flex-1 persona-min-h-0 persona-relative"),_e=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");_e.style.height="100%";let Xe=m("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");mr(Xe,b?.scrollIndicator),Xe.style.display="none",Xe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let an=oe(d,"14px","currentColor",2);an&&Xe.appendChild(an);let Et=m("span","");Et.textContent=c,Xe.appendChild(Et);let ft=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");ft.style.display="none",at.appendChild(_e),at.appendChild(ft),at.appendChild(Xe),C.setAttribute("tabindex","0"),C.appendChild(je),C.appendChild(Pe),C.appendChild(at);function ke(){let B=e.getAll(),j={};for(let ze of B)j[ze.type]=(j[ze.type]||0)+1;let ae=Object.keys(j).sort(),tt=ae.length!==I.length||!ae.every((ze,Re)=>ze===I[Re]),Me=!tt&&ae.some(ze=>j[ze]!==z[ze]),lt=B.length!==Object.values(z).reduce((ze,Re)=>ze+Re,0);if(!tt&&!Me&&!lt||(I=ae,z=j,!Y))return;let q=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,tt){for(;Y.options.length>1;)Y.remove(1);for(let ze of ae){let Re=m("option","");Re.value=ze,Re.textContent=`${ze} (${j[ze]||0})`,Y.appendChild(Re)}q&&ae.includes(q)?Y.value=q:q&&(Y.value="",H="")}else for(let ze=1;ze<Y.options.length;ze++){let Re=Y.options[ze];Re.textContent=`${Re.value} (${j[Re.value]||0})`}}function me(){let B=e.getAll();if(H&&(B=B.filter(j=>j.type===H)),M){let j=M.toLowerCase();B=B.filter(ae=>ae.type.toLowerCase().includes(j)||ae.payload.toLowerCase().includes(j))}return B}function it(){return H!==""||M!==""}function Ie(){N=0,U=0,x.resume(),Xe.style.display="none"}function pe(B){he.has(B)?he.delete(B):he.add(B),ge=B;let j=_e.scrollTop,ae=x.isFollowing();$=!0,x.pause(),ye(),_e.scrollTop=j,ae&&x.resume(),$=!1}function ie(){return io(_e,50)}function ye(){V=Date.now(),J=!1,Be(),ke();let B=e.getEvictedCount();B>0?(Pe.textContent=`${B.toLocaleString()} older events truncated`,Pe.style.display=""):Pe.style.display="none",P=me();let j=P.length,ae=e.getSize()>0;j===0&&ae&&it()?(ft.textContent=M?`No events matching '${M}'`:"No events matching filter",ft.style.display="",_e.style.display="none"):(ft.style.display="none",_e.style.display=""),le&&(le.title=it()?`Copy Filtered (${j})`:"Copy All"),p&&!x.isFollowing()&&j>N&&(U+=j-N,Et.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Xe.style.display=""),N=j;let tt=e.getAll(),Me=tt.length>0?tt[0].timestamp:0,lt=new Set(P.map(Re=>Re.id));for(let Re of he)lt.has(Re)||he.delete(Re);let q=H!==xe||M!==te,ze=Ee.size===0&&P.length>0;if(q||ze||P.length===0){_e.innerHTML="",Ee.clear();let Re=document.createDocumentFragment();for(let We=0;We<P.length;We++){let Le=ml(P[We],We,Me,u,he,pe,s,r);Ee.set(P[We].id,Le),Re.appendChild(Le)}_e.appendChild(Re),xe=H,te=M,ge=null}else{if(ge!==null){let We=Ee.get(ge);if(We&&We.parentNode===_e){let Le=P.findIndex(Je=>Je.id===ge);if(Le>=0){let Je=ml(P[Le],Le,Me,u,he,pe,s,r);_e.insertBefore(Je,We),We.remove(),Ee.set(ge,Je)}}ge=null}let Re=new Set(P.map(We=>We.id));for(let[We,Le]of Ee)Re.has(We)||(Le.remove(),Ee.delete(We));for(let We=0;We<P.length;We++){let Le=P[We];if(!Ee.has(Le.id)){let Je=ml(Le,We,Me,u,he,pe,s,r);Ee.set(Le.id,Je),_e.appendChild(Je)}}}x.isFollowing()&&(_e.scrollTop=_e.scrollHeight)}function bt(){if(Date.now()-V>=$h){D!==null&&(cancelAnimationFrame(D),D=null),ye();return}J||(J=!0,D=requestAnimationFrame(()=>{D=null,ye()}))}let F=(B,j)=>{if(!le)return;le.innerHTML="";let ae=oe(B,"12px","currentColor",1.5);ae&&le.appendChild(ae);let tt=m("span","persona-text-xs");tt.textContent="Copy All",le.appendChild(tt),setTimeout(()=>{le.innerHTML="";let Me=oe("clipboard-copy","12px","currentColor",1.5);Me&&le.appendChild(Me);let lt=m("span","persona-text-xs");lt.textContent="Copy All",le.appendChild(lt),le.disabled=!1},j)},ne=async()=>{if(le){le.disabled=!0;try{let B;it()?B=P:n?(B=await n(),B.length===0&&(B=e.getAll())):B=e.getAll();let j=B.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),F("check",1500)}catch{F("x",1500)}}},De=()=>{Y&&(H=Y.value,Ie(),ye())},Se=()=>{!Z||!be||(be.style.display=Z.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{M=Z.value,Ie(),ye()},150))},E=()=>{!Z||!be||(Z.value="",M="",be.style.display="none",T&&clearTimeout(T),Ie(),ye())},Q=()=>{if($)return;let B=_e.scrollTop,{action:j,nextLastScrollTop:ae}=ka({following:x.isFollowing(),currentScrollTop:B,lastScrollTop:fe,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});fe=ae,j==="resume"?(x.resume(),U=0,Xe.style.display="none"):j==="pause"&&(x.pause(),p&&(Et.textContent=c,Xe.style.display=""))},v=B=>{let j=La({following:x.isFollowing(),deltaY:B.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});j==="pause"?(x.pause(),p&&(Et.textContent=c,Xe.style.display="")):j==="resume"&&(x.resume(),U=0,Xe.style.display="none")},S=()=>{p&&(_e.scrollTop=_e.scrollHeight,x.resume(),U=0,Xe.style.display="none")},k=B=>{let j=B.target;if(!j||j.closest("button"))return;let ae=j.closest("[data-event-id]");if(!ae)return;let tt=ae.getAttribute("data-event-id");tt&&pe(tt)},W=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(E(),Z.blur(),C.focus()):o&&o())};le&&le.addEventListener("click",ne),Y&&Y.addEventListener("change",De),Z&&Z.addEventListener("input",Se),be&&be.addEventListener("click",E),_e.addEventListener("scroll",Q),_e.addEventListener("wheel",v,{passive:!0}),_e.addEventListener("click",k),Xe.addEventListener("click",S),C.addEventListener("keydown",W);function G(){T&&clearTimeout(T),D!==null&&(cancelAnimationFrame(D),D=null),J=!1,Ee.clear(),le&&le.removeEventListener("click",ne),Y&&Y.removeEventListener("change",De),Z&&Z.removeEventListener("input",Se),be&&be.removeEventListener("click",E),_e.removeEventListener("scroll",Q),_e.removeEventListener("wheel",v),_e.removeEventListener("click",k),Xe.removeEventListener("click",S),C.removeEventListener("keydown",W)}return{element:C,update:bt,destroy:G}}}function Zp(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&e.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return t.addEventListener("keydown",d),t.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,b)=>{f.setAttribute("role","tab");let C=b===w;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||w<0&&b===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",d),t.removeEventListener("focusin",c)}}}function eu(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=F=>({start:F===!1?!1:typeof F=="object"&&F?F.start!==!1:!0,end:F===!1?!1:typeof F=="object"&&F?F.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),$?.hide()};w&&w.addEventListener("click",()=>{f(),e.onDismiss?.()});let b=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let P=m("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let H=Wt({icon:"x",label:a});H.addEventListener("click",()=>{f(),e.onDismiss?.()});let M="rendered",T=Ca({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:F=>{M=F==="source"?"source":"rendered",ie()}}),I=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,N=n?.documentToolbarShowCopyChevron===!0,x=n?.documentToolbarCopyMenuItems,U=!!(N&&x&&x.length>0),V=null,J,D=null,$=null;if(r&&(z||N)&&!U){if(J=z?Bo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N){let F=oe("chevron-down",14,"currentColor",2);F&&J.appendChild(F)}}else r&&U?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),J=z?Bo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),V.append(J,D)):r?J=Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(J=Wt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&J.classList.add("persona-hidden"));let fe=r?Wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wt({icon:"refresh-cw",label:"Refresh"}),he=r?Wt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Wt({icon:"x",label:a}),Ee=Wt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let xe=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),te=t.features?.artifacts?.toolbarActions??[],ge=()=>{let F=Pe.find(E=>E.id===Be)??Pe[Pe.length-1],ne=F?.id??null,De=F?.artifactType==="markdown"?F.markdown??"":"",Se=F?JSON.stringify({component:F.component,props:F.props},null,2):"";return{markdown:De,jsonPayload:Se,id:ne}},Y=async()=>{let F=Pe.find(ne=>ne.id===Be)??Pe[Pe.length-1];try{await navigator.clipboard.writeText(ls(F))}catch{}};if(J.addEventListener("click",async()=>{let F=n?.onDocumentToolbarCopyMenuSelect;if(F&&U){let{markdown:ne,jsonPayload:De,id:Se}=ge();try{await F({actionId:"primary",artifactId:Se,markdown:ne,jsonPayload:De})}catch{}return}await Y()}),D&&x?.length){let F=()=>b.closest("[data-persona-root]")??document.body,ne=()=>{$=dr({items:x.map(De=>({id:De.id,label:De.label})),onSelect:async De=>{let{markdown:Se,jsonPayload:E,id:Q}=ge(),v=n?.onDocumentToolbarCopyMenuSelect;try{v?await v({actionId:De,artifactId:Q,markdown:Se,jsonPayload:E}):De==="markdown"||De==="md"?await navigator.clipboard.writeText(Se):De==="json"||De==="source"?await navigator.clipboard.writeText(E):await navigator.clipboard.writeText(Se||E)}catch{}},anchor:V??D,position:"bottom-right",portal:F()})};b.isConnected?ne():requestAnimationFrame(ne),D.addEventListener("click",De=>{De.stopPropagation(),$?.toggle()})}fe.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ie()}),he.addEventListener("click",()=>{f(),e.onDismiss?.()});let le=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),V?I.append(V,fe,he):I.append(J,fe,he),I.insertBefore(xe,he),I.insertBefore(Ee,he),C.append(T.element,le,I);else{let F=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");F.append(J,xe,Ee,H),C.appendChild(P),C.appendChild(F)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let Z=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let be=t.features?.artifacts?.renderTabBar,ve=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ue=Zp(Z,{onSelect:F=>e.onSelect(Pe[F].id)}),Te=F=>{let ne=F.scrollWidth-F.clientWidth,De=ne>1,Se=Math.abs(F.scrollLeft);F.classList.toggle("persona-artifact-tab-fade-start",c&&De&&Se>1),F.classList.toggle("persona-artifact-tab-fade-end",u&&De&&Se<ne-1)},Ce=0,je=()=>{if(Ce)return;let F=()=>{Ce=0,Te(Z)};Ce=typeof requestAnimationFrame=="function"?requestAnimationFrame(F):setTimeout(F,0)};Z.addEventListener("scroll",()=>je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(Z)).observe(Z);let Fe=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let F of[Z,ve])F.style.paddingLeft=l,F.style.paddingRight=l;Fe.style.padding=l}b.appendChild(C),b.appendChild(Z),b.appendChild(ve),b.appendChild(Fe);let Pe=[],Be=null,at=!1,_e=!0,Xe=!1,an=null,Et="",ft=null,ke=!1,me=F=>F.artifactType==="markdown"&&!!F.file||r?M:"rendered",it=F=>{r||(F&&!ke?(C.insertBefore(T.element,P),ke=!0):!F&&ke&&(T.element.remove(),ke=!1))},Ie=()=>Be&&Pe.find(F=>F.id===Be)||Pe[Pe.length-1],pe=()=>{let F=as(Ie());if(!F){xe.replaceChildren();return}let ne=te.filter(De=>De.visible===void 0||De.visible(F)).map(De=>pr(De,{documentChrome:r,onClick:()=>{let Se=as(Ie());if(Se)try{Promise.resolve(De.onClick(Se)).catch(()=>{})}catch{}}}));xe.replaceChildren(...ne)},ie=()=>{pe();let F=r&&Pe.length<=1,ne=!!be;if(Z.classList.toggle("persona-hidden",F||ne),ve.classList.toggle("persona-hidden",F||!ne),ne&&be){let E=Pe.map(Q=>Q.id).join("|")+" "+(Be??"");if(E!==Et){Et=E;let Q=be({records:Pe,selectedId:Be,onSelect:e.onSelect});ve.firstElementChild!==Q&&ve.replaceChildren(Q)}}else{ue.beforeRender(),Z.replaceChildren();let E=[],Q=-1;for(let[v,S]of Pe.entries()){let k=m("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");k.type="button";let W=S.artifactType==="markdown"?S.file:void 0,G=W?Mn(W.path):S.title||S.id.slice(0,8),B=W?.path||S.title||G;k.textContent=G,k.title=B,k.setAttribute("aria-label",B),S.id===Be&&(k.classList.add("persona-bg-persona-container","persona-border-persona-border"),Q=v),k.addEventListener("click",()=>e.onSelect(S.id)),Z.appendChild(k),E.push(k)}if(ue.render(E,Q),Q>=0&&Be!==an){an=Be;let v=E[Q];typeof v.scrollIntoView=="function"&&v.scrollIntoView({block:"nearest",inline:"nearest"})}Te(Z)}let De=Be&&Pe.find(E=>E.id===Be)||Pe[Pe.length-1];if(!De){Fe.replaceChildren(),ft=null,it(!1);return}let Se=De.artifactType==="markdown"?De.file:void 0;if(it(!!Se),r){let E=Se?oo(Se):De.artifactType==="markdown"?"MD":De.component??"Component",Q=(De.title||"Document").trim(),v=Se?Mn(Se.path):Q.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${v} \xB7 ${E}`}else P.textContent=Se?Mn(Se.path):s;ft?(ft.el.parentElement!==Fe&&Fe.replaceChildren(ft.el),ft.update(De)):(ft=Ta(De,{config:t,resolveViewMode:me}),Fe.replaceChildren(ft.el)),Fe.classList.toggle("persona-artifact-content-flush",!!Fe.querySelector(".persona-code-pre"))},ye=()=>{let F=Pe.length>0;if(b.classList.toggle("persona-hidden",!F),w){let Se=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;F&&Se&&at?(w.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},bt=()=>{Xe=!1,ie(),ye()};return{element:b,backdrop:w,update(F){Pe=F.artifacts,Be=F.selectedId??F.artifacts[F.artifacts.length-1]?.id??null,Pe.length>0&&(at=!0),Xe=!0,_e&&bt()},setMobileOpen(F){at=F,!F&&w?(w.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ye()},setExpanded(F){let ne=oe(F?"minimize":"maximize",16,"currentColor",2);ne&&Ee.replaceChildren(ne);let De=F?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",De),Ee.title=De},setExpandToggleVisible(F){Ee.classList.toggle("persona-hidden",!F)},setCopyButtonVisible(F){r||J.classList.toggle("persona-hidden",!F)},setCustomActions(F){te=F,pe()},setTabFade(F){let ne=d(F);ne.start===c&&ne.end===u||(c=ne.start,u=ne.end,Te(Z))},setRenderTabBar(F){F!==be&&(be=F,Et="",ie())},setVisible(F){F!==_e&&(_e=F,F&&Xe&&bt())}}}function Qt(t){return t?.features?.artifacts?.enabled===!0}function tu(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Qt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function Jh(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var nu=["panel","seamless","detached"];function hl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&nu.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function yl(t){return!t||!Qt(t)?!1:hl(t)==="detached"}function ws(t,e){if(!Qt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Jh(t),tu(t,e);return}let n=e.features?.artifacts?.layout,o=hl(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),tu(t,e)}function xs(t,e){for(let l of nu)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Qt(e))return;let n=e.features?.artifacts?.layout,o=hl(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function ou(t,e){return!e||!Qt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function Yh(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Zh(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function ey(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function ty(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function bl(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function ru(t,e,n,o,r,s){let a=Yh(r,200),l=ty(e,n,o,200);l=Math.max(a,l);let p=Zh(s);return p!==null&&(l=Math.min(l,p)),ey(t,a,l)}var su={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"}},vl=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=su[a]??su.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let b=m("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${a}-${b.name}`;let P=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=b.label,C.appendChild(P);let H=b.type??"text",M;H==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=H),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${e.id}-${a}-${b.name}`,M.name=b.name,M.placeholder=b.placeholder??"",b.required&&(M.required=!0),C.appendChild(M),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",P=new FormData(c),H={};P.forEach((M,T)=>{H[T]=M}),H.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let M=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let T=await M.json();w.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(M){w.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var wl=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},xl=new wl;var au=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var ny=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},oy=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Al=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=ny(t),n=oy(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Cl=t=>typeof t=="string"?t:t==null?"":String(t),Cs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Cl(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Cl(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Cl(n.text)}}},iu=t=>Array.isArray(t)?t.map(e=>String(e)):[],Sl=t=>{let e=new Set(iu(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(iu(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let d of t.handlers)if(d)try{let c=()=>{t.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var ry=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},sy=t=>t.map(e=>({...e,streaming:!1})),ay=t=>t.map(e=>({...e,status:"complete"})),lu=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?ry(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?sy(n.messages):void 0,artifacts:n.artifacts?ay(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as DC,STR as NC,OBJ as FC}from"partial-json";function cu(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=_n.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function du(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Tl(t){let e=du(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function pu(t){let e=du(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var iy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function uu(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=iy}=t,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,f.appendChild(b);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),w.appendChild(f);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let H=[];for(let N=1;N<=5;N++){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",`${N} star${N>1?"s":""}: ${d[N-1]}`),x.title=d[N-1],x.dataset.rating=String(N),x.innerHTML=`
|
|
31
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
32
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>
|
|
33
45
|
</svg>
|
|
34
|
-
`,W.addEventListener("click",()=>{g=A,B.forEach((z,$)=>{let k=$<A;z.classList.toggle("selected",k),z.setAttribute("aria-checked",$===A-1?"true":"false")})}),B.push(W),S.appendChild(W)}h.appendChild(S);let T=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),A.appendChild(T),h.appendChild(A)}let I=document.createElement("div");I.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=l,R.addEventListener("click",()=>{t==null||t(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(g===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let A=(T==null?void 0:T.value.trim())||void 0;await e(g,A),u.remove()}catch(A){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),I.appendChild(R),I.appendChild(P),h.appendChild(I),u.appendChild(h),u}function mg(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,b.appendChild(w);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,b.appendChild(S),m.appendChild(b);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 T=document.createElement("div");T.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=c;let R=document.createElement("span");R.className="persona-feedback-label-high",R.textContent=u,T.appendChild(I),T.appendChild(R);let P=document.createElement("div");P.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-number-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`Rating ${U} out of 10`),F.textContent=String(U),F.dataset.rating=String(U),U<=6?F.classList.add("persona-feedback-detractor"):U<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{h=U,A.forEach((te,Ee)=>{te.classList.toggle("selected",Ee===U),te.setAttribute("aria-checked",Ee===U?"true":"false")})}),A.push(F),P.appendChild(F)}B.appendChild(T),B.appendChild(P),m.appendChild(B);let W=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),U.appendChild(W),m.appendChild(U)}let z=document.createElement("div");z.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=l,$.addEventListener("click",()=>{t==null||t(),g.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(h===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let U=(W==null?void 0:W.value.trim())||void 0;await e(h,U),g.remove()}catch(U){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),z.appendChild($),z.appendChild(k),m.appendChild(z),g.appendChild(m),g}var Ss="persona-chat-history",lw=30*1e3,cw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function dw(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let l=a.getAsFile();if(!l)continue;if(l.name){e.push(l);continue}let d=(o=cw[l.type])!=null?o:"png";e.push(new File([l],`clipboard-image-${Date.now()}.${d}`,{type:l.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function di(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function pw(n){var e,t,r,o,s,a,l,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(l=n.persist)==null?void 0:l.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function uw(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var hl=n=>!n||typeof n!="object"?{}:{...n},gg=n=>n.map(e=>({...e,streaming:!1})),fg=(n,e,t)=>{let r=n!=null&&n.markdown?xa(n.markdown):null,o=Ca(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var u,g,h;let a=(u=s.text)!=null?u:"",l=(g=s.message.rawContent)!=null?g:null;if(e){let m=e.process({text:a,raw:l!=null?l:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&t&&t())}let d=Oo()!==null,c;if(n!=null&&n.postprocessMessage){let m=n.postprocessMessage({...s,text:a,raw:(h=l!=null?l:s.text)!=null?h:""});c=o?o(m):m}else if(r){let m=s.streaming?bu(a):a,b=r(m);c=o&&d?o(b):b}else c=fo(a);return c}};function hg(n){var l,d,c,u;let e=v("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(l=n==null?void 0:n.iconName)!=null?l:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(u=n==null?void 0:n.iconStrokeWidth)!=null?u:.5,a=he(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let g=v("span","persona-drop-overlay-label");g.textContent=n.label,e.appendChild(g)}return e}var yg=(n,e,t)=>{var cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,wc,xc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,zc,qc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=lm(e),o=pl.getForInstance(r.plugins),{plugin:s,teardown:a}=jm();r.components&&Go.registerAll(r.components);let l=ag(),c=r.persistState===!1?null:(cc=r.storageAdapter)!=null?cc:lg(),u={},g=null,h=!1,m=i=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(i);if(p&&typeof p=="object"&&"state"in p){let{state:f,open:y}=p;return y&&(h=!0),f}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return i};if(c!=null&&c.load)try{let i=c.load();if(i&&typeof i.then=="function")g=i.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return m(f)});else{let p=i!=null?i:{messages:[],metadata:{}},f=m(p);f.metadata&&(u=hl(f.metadata)),(dc=f.messages)!=null&&dc.length&&(r={...r,initialMessages:f.messages}),(pc=f.artifacts)!=null&&pc.length&&(r={...r,initialArtifacts:f.artifacts,initialSelectedArtifactId:(uc=f.selectedArtifactId)!=null?uc:null})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(r.onStateLoaded)try{let i=m({messages:[],metadata:{}});(mc=i.messages)!=null&&mc.length&&(r={...r,initialMessages:i.messages})}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let b=()=>u,w=i=>{var f;u=(f=i({...u}))!=null?f:{},Er()},S=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ml],B=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ua.message,ua.messageAndClick],T=gl({parsers:S,handlers:B,getSessionMetadata:b,updateSessionMetadata:w,emit:l.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let I=(fc=(gc=r.launcher)==null?void 0:gc.enabled)!=null?fc:!0,R=(yc=(hc=r.launcher)==null?void 0:hc.autoExpand)!=null?yc:!1,P=(bc=r.autoFocusInput)!=null?bc:!1,A=R,W=I,z=(wc=(vc=r.layout)==null?void 0:vc.header)==null?void 0:wc.layout,$=!1,k=()=>aa(r),U=()=>I||k(),F=k()?!1:I?R:!0,te=!1,Ee=null,de=()=>{te=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{te&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),te=!1)},1e4)},Y=fg(r,T,de),Le=(Cc=(xc=r.features)==null?void 0:xc.showReasoning)!=null?Cc:!0,Pe=(Sc=(Ac=r.features)==null?void 0:Ac.showToolCalls)!=null?Sc:!0,ae=(Mc=(Tc=r.features)==null?void 0:Tc.showEventStreamToggle)!=null?Mc:!1,fe=(kc=(Ec=r.features)==null?void 0:Ec.scrollToBottom)!=null?kc:{},ne=(Pc=(Lc=r.features)==null?void 0:Lc.scrollBehavior)!=null?Pc:{},ce=`${(Wc=typeof r.persistState=="object"?(Ic=r.persistState)==null?void 0:Ic.keyPrefix:void 0)!=null?Wc:"persona-"}event-stream`,Ce=ae?new da(ce):null,_e=(Bc=(Hc=(Rc=r.features)==null?void 0:Rc.eventStream)==null?void 0:Hc.maxEvents)!=null?Bc:2e3,V=ae?new ca(_e,Ce):null,X=ae?new pa:null,Ae=null,J=!1,ie=null,Se=0;Ce==null||Ce.open().then(()=>V==null?void 0:V.restore()).catch(i=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Je={onCopy:i=>{var p,f;l.emit("message:copy",i),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(i.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(f=(p=r.messageActions)==null?void 0:p.onCopy)==null||f.call(p,i)},onFeedback:i=>{var p,f;l.emit("message:feedback",i),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(i.messageId,i.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(f=(p=r.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,i)}},et=(Dc=r.statusIndicator)!=null?Dc:{},Wt=i=>{var p,f,y,C,E,_;return i==="idle"?(p=et.idleText)!=null?p:en.idle:i==="connecting"?(f=et.connectingText)!=null?f:en.connecting:i==="connected"?(y=et.connectedText)!=null?y:en.connected:i==="error"?(C=et.errorText)!=null?C:en.error:i==="paused"?(E=et.pausedText)!=null?E:en.paused:i==="resuming"?(_=et.resumingText)!=null?_:en.resuming:en[i]};function ft(i,p,f,y){if(y==="idle"&&f.idleLink){i.textContent="";let C=document.createElement("a");C.href=f.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=p,C.style.color="inherit",C.style.textDecoration="none",i.appendChild(C)}else i.textContent=p}let rt=Rm({config:r,showClose:U()}),{wrapper:ue,panel:Q,pillRoot:it}=rt.shell,je=rt.panelElements,{container:Te,body:we,messagesWrapper:Ye,suggestions:qt,textarea:ye,sendButton:pe,sendButtonWrapper:Cn,composerForm:Ct,statusText:hn,introTitle:gr,introSubtitle:fr,closeButton:Ue,iconHolder:M,headerTitle:me,headerSubtitle:Me,header:ke,footer:Re,actionsRow:tt,leftActions:Qe,rightActions:ht}=je,ge=je.setSendButtonMode,H=je.micButton,be=je.micButtonWrapper,le=je.attachmentButton,gt=je.attachmentButtonWrapper,Ke=je.attachmentInput,Lt=je.attachmentPreviewsContainer;Te.classList.add("persona-relative"),we.classList.add("persona-relative");let Et=12,vt=()=>{var i;return(i=fe.label)!=null?i:""},Rt=()=>{var i;return(i=fe.iconName)!=null?i:"arrow-down"},Qt=()=>fe.enabled!==!1,Ft=()=>{var i;return(i=ne.mode)!=null?i:"anchor-top"},Yt=()=>Ft()==="follow"||Ft()==="anchor-top"&&oo,hr=()=>{var i;return(i=ne.anchorTopOffset)!=null?i:16},Wr=()=>{var i;return(i=ne.restorePosition)!=null?i:"bottom"},nr=()=>ne.pauseOnInteraction===!0,rr=()=>ne.showActivityWhilePinned!==!1,Qr=()=>ne.announce===!0,jt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");jt.type="button",jt.style.display="none",jt.setAttribute("data-persona-scroll-to-bottom","true");let or=v("span","persona-flex persona-items-center"),Rr=v("span",""),Hn=v("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",jt.append(or,Rr,Hn),Te.appendChild(jt);let Pn=v("div","persona-stream-anchor-spacer");Pn.setAttribute("aria-hidden","true"),Pn.setAttribute("data-persona-anchor-spacer",""),Pn.style.flexShrink="0",Pn.style.pointerEvents="none",Pn.style.height="0px",we.appendChild(Pn);let Bn=v("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Te.appendChild(Bn);let sr=null,yr=null,Xr=i=>{!Qr()||!i||(yr=i,sr===null&&(sr=setTimeout(()=>{sr=null,yr&&Qr()&&(Bn.textContent=yr),yr=null},400)))},jn=()=>{let p=Re.style.display==="none"?0:Re.offsetHeight;jt.style.bottom=`${p+Et}px`};jn();let Jr=()=>{let i=!!vt();jt.setAttribute("aria-label",vt()||"Jump to latest"),jt.title=vt(),jt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),or.innerHTML="";let p=he(Rt(),"14px","currentColor",2);p?(or.appendChild(p),or.style.display=""):or.style.display="none",Rr.textContent=vt(),Rr.style.display=i?"":"none"};Jr();let At=null,br=null,vr=o.find(i=>i.renderHeader);if(vr!=null&&vr.renderHeader){let i=vr.renderHeader({config:r,defaultRenderer:()=>{let p=qo({config:r,showClose:U()});return ia(Te,p,r),p.header},onClose:()=>_t(!1,"user")});if(i){let p=Te.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(i),ke=i,rt.header.element=i)}}let Hr=()=>{var p,f,y,C;if(!V)return;if(J=!0,!Ae&&V&&(Ae=Xm({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>ar(),config:r,plugins:o,getThroughput:()=>{var E;return(E=X==null?void 0:X.getMetric())!=null?E:{status:"idle"}}})),Ae&&(we.style.display="none",(p=Re.parentNode)==null||p.insertBefore(Ae.element,Re),Ae.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let E=(C=(y=(f=r.features)==null?void 0:f.eventStream)==null?void 0:y.classNames)==null?void 0:C.toggleButtonActive;E&&E.split(/\s+/).forEach(_=>_&&yt.classList.add(_))}let i=()=>{if(!J)return;let E=Date.now();E-Se>=200&&(Ae==null||Ae.update(),Se=E),ie=requestAnimationFrame(i)};Se=0,ie=requestAnimationFrame(i),On(),l.emit("eventStream:opened",{timestamp:Date.now()})},ar=()=>{var i,p,f;if(J){if(J=!1,Ae&&Ae.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let y=(f=(p=(i=r.features)==null?void 0:i.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;y&&y.split(/\s+/).forEach(C=>C&&yt.classList.remove(C))}ie!==null&&(cancelAnimationFrame(ie),ie=null),On(),l.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ae){let i=(Fc=(Nc=r.features)==null?void 0:Nc.eventStream)==null?void 0:Fc.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!=null&&i.toggleButton?" "+i.toggleButton:"");yt=v("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ln.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let f=he("activity","18px","currentColor",1.5);f&&yt.appendChild(f);let y=je.clearChatButtonWrapper,C=je.closeButtonWrapper,E=y||C;E&&E.parentNode===ke?ke.insertBefore(yt,E):ke.appendChild(yt),yt.addEventListener("click",()=>{J?ar():Hr()})}let Co=i=>{var C,E,_,N,D;let p=r.attachments;if(!(p!=null&&p.enabled))return;let f=(C=i.querySelector("[data-persona-composer-attachment-previews]"))!=null?C:i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let se=i.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(f,se):i.insertBefore(f,i.firstChild)}if(!((E=i.querySelector("[data-persona-composer-attachment-input]"))!=null?E:i.querySelector('input[type="file"]'))){let se=v("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((_=p.allowedTypes)!=null?_:Kr).join(","),se.multiple=((N=p.maxFiles)!=null?N:4)>1,se.style.display="none",se.setAttribute("aria-label",(D=p.buttonTooltipText)!=null?D:"Attach files"),i.appendChild(se)}},wr=o.find(i=>i.renderComposer);if(wr!=null&&wr.renderComposer){let i=r.composer,p=wr.renderComposer({config:r,defaultRenderer:()=>oi({config:r}).footer,onSubmit:f=>{var _;if(!O||O.isStreaming())return;let y=f.trim(),C=(_=At==null?void 0:At.hasAttachments())!=null?_:!1;if(!y&&!C)return;Fl();let E;C&&(E=[],E.push(...At.getContentParts()),y&&E.push(_i(y))),O.sendMessage(y,{contentParts:E}),C&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ke==null||Ke.click()},models:i==null?void 0:i.models,selectedModelId:i==null?void 0:i.selectedModelId,onModelChange:f=>{r.composer={...r.composer,selectedModelId:f},r.agent&&(r.agent={...r.agent,model:f})},onVoiceToggle:((Oc=r.voiceRecognition)==null?void 0:Oc.enabled)===!0?()=>{br==null||br()}:void 0});p&&(rt.replaceComposer(p),Re=rt.composer.footer)}let Ao=i=>{let p=(...oe)=>{for(let Z of oe){let ve=i.querySelector(Z);if(ve)return ve}return null},f=i.querySelector("[data-persona-composer-form]"),y=i.querySelector("[data-persona-composer-input]"),C=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),_=i.querySelector("[data-persona-composer-status]");f&&(Ct=f),y&&(ye=y),C&&(pe=C),E&&(H=E,be=E.parentElement),_&&(hn=_);let N=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(qt=N);let D=p("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(le=D,gt=D.parentElement),Ke=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(tt=se)};Co(Re),Ao(Re);let In=(qc=(_c=r.layout)==null?void 0:_c.contentMaxWidth)!=null?qc:k()?(zc=(Uc=($c=r.launcher)==null?void 0:$c.composerBar)==null?void 0:Uc.contentMaxWidth)!=null?zc:"720px":void 0;if(In&&(Ye.style.maxWidth=In,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),In&&Ct&&!k()&&(Ct.style.maxWidth=In,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),In&&qt&&!k()&&(qt.style.maxWidth=In,qt.style.marginLeft="auto",qt.style.marginRight="auto"),In&&Lt&&!k()&&(Lt.style.maxWidth=In,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(jc=r.attachments)!=null&&jc.enabled&&Ke&&Lt){At=Zs.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Ke.addEventListener("change",f=>{let y=f.target;At==null||At.handleFileSelect(y.files),y.value=""});let i=r.attachments.dropOverlay,p=hg(i);Te.appendChild(p)}(()=>{var y,C;let i=(C=(y=r.layout)==null?void 0:y.slots)!=null?C:{},p=E=>{switch(E){case"body-top":return Te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return hn;default:return null}},f=(E,_)=>{var N;switch(E){case"header-left":case"header-center":case"header-right":if(E==="header-left")ke.insertBefore(_,ke.firstChild);else if(E==="header-right")ke.appendChild(_);else{let D=ke.querySelector(".persona-flex-col");D?(N=D.parentNode)==null||N.insertBefore(_,D.nextSibling):ke.appendChild(_)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(_):we.insertBefore(_,we.firstChild);break}case"body-bottom":we.appendChild(_);break;case"footer-top":qt.replaceWith(_);break;case"footer-bottom":hn.replaceWith(_);break;default:break}};for(let[E,_]of Object.entries(i))if(_)try{let N=_({config:r,defaultContent:()=>p(E)});N&&f(E,N)}catch(N){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${E}":`,N)}})();let Yr=i=>{var _,N;let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let y=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let C=y.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-bubble-type");if(E==="reasoning")xs.has(C)?xs.delete(C):xs.add(C),Dm(C,y);else if(E==="tool")Cs.has(C)?Cs.delete(C):Cs.add(C),Nm(C,y,r);else if(E==="approval"){let D=r.approval!==!1?r.approval:void 0,se=((_=D==null?void 0:D.detailsDisplay)!=null?_:"collapsed")==="expanded",oe=(N=jo.get(C))!=null?N:se;jo.set(C,!oe),$m(C,y,r)}Sr.delete(C)};Ye.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Yr(i))}),Ye.addEventListener("keydown",i=>{let p=i.target;(i.key==="Enter"||i.key===" ")&&p.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Yr(i))}),Ye.addEventListener("copy",i=>{let{clipboardData:p}=i;if(!p)return;let f=Ye.getRootNode(),y=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let C=y.toString(),E=gm(C);!E||E===C||(p.setData("text/plain",E),i.preventDefault())});let Br=new Map,Zr=null,eo="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(i,p)=>{let{icon:f,label:y}=So[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 C=he(f,14,"currentColor",2);C&&(i.innerHTML="",i.appendChild(C))},to=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var E;let f=p.closest("[data-actions-for]"),y=(E=f==null?void 0:f.getAttribute("data-actions-for"))!=null?E:null;To(p,y&&y===Zr?eo:"idle")})};Ye.addEventListener("click",i=>{var _;let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest("[data-actions-for]");if(!y)return;let C=y.getAttribute("data-actions-for");if(!C)return;let E=f.getAttribute("data-action");if(E==="copy"){let D=O.getMessages().find(se=>se.id===C);if(D&&Je.onCopy){let se=D.content||"";navigator.clipboard.writeText(se).then(()=>{f.classList.add("persona-message-action-success");let oe=he("check",14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let Z=he("copy",14,"currentColor",2);Z&&(f.innerHTML="",f.appendChild(Z))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),Je.onCopy(D)}}else if(E==="read-aloud")O.toggleReadAloud(C);else if(E==="upvote"||E==="downvote"){let D=((_=Br.get(C))!=null?_:null)===E,se=E==="upvote"?"thumbs-up":"thumbs-down";if(D){Br.delete(C),f.classList.remove("persona-message-action-active");let oe=he(se,14,"currentColor",2);oe&&(f.innerHTML="",f.appendChild(oe))}else{let oe=E==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${oe}"]`);if(Z){Z.classList.remove("persona-message-action-active");let ze=he(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Z.innerHTML="",Z.appendChild(ze))}Br.set(C,E),f.classList.add("persona-message-action-active");let ve=he(se,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ve)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Fe=O.getMessages().find($e=>$e.id===C);Fe&&Je.onFeedback&&Je.onFeedback({type:E,messageId:Fe.id,message:Fe})}}}),Ye.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.closest(".persona-approval-bubble");if(!y)return;let C=y.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-approval-action");if(!E)return;let _=E==="approve"?"approved":"denied",D=O.getMessages().find(oe=>oe.id===C);if(!(D!=null&&D.approval))return;let se=y.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?O.resolveWebMcpApproval(C,_):O.resolveApproval(D.approval,_)});let wt=null,Dn=null,Nn={artifacts:[],selectedId:null},An=!1,St={current:null};Ye.addEventListener("click",i=>{var Z,ve,Ne,Fe,$e;let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let y=f.getAttribute("data-download-artifact");if(!y||((Ne=(ve=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Ne.call(ve,{type:"download",artifactId:y}))===!0)return;let E=O.getArtifactById(y),_=E==null?void 0:E.markdown,N=(E==null?void 0:E.title)||"artifact";if(!_){let ze=f.closest("[data-open-artifact]"),ut=ze==null?void 0:ze.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Ie=O.getMessages().find(qe=>qe.id===st);if(Ie!=null&&Ie.rawContent)try{let qe=JSON.parse(Ie.rawContent);_=(Fe=qe==null?void 0:qe.props)==null?void 0:Fe.markdown,N=(($e=qe==null?void 0:qe.props)==null?void 0:$e.title)||N}catch{}}}if(!_)return;let D=new Blob([_],{type:"text/markdown"}),se=URL.createObjectURL(D),oe=document.createElement("a");oe.href=se,oe.download=`${N}.md`,oe.click(),URL.revokeObjectURL(se)}),Ye.addEventListener("click",i=>{var E,_,N;let f=i.target.closest("[data-open-artifact]");if(!f)return;let y=f.getAttribute("data-open-artifact");!y||((N=(_=(E=r.features)==null?void 0:E.artifacts)==null?void 0:_.onArtifactAction)==null?void 0:N.call(_,{type:"open",artifactId:y}))===!0||(i.preventDefault(),i.stopPropagation(),An=!1,O.selectArtifact(y),xr())}),Ye.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let p=i.target;p.hasAttribute("data-open-artifact")&&(i.preventDefault(),p.click())});let Vn=je.composerOverlay,Kn=(i,p,f)=>{var N,D,se,oe;let y=p.trim();if(!y||!St.current)return;let C=(N=i.getAttribute("data-tool-call-id"))!=null?N:"",E=f.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:y,answers:f.structured,values:(D=f.values)!=null?D:f.source==="multi"?y.split(", "):[y],isFreeText:E,source:f.source},bubbles:!0,composed:!0})),ms(Vn,C);let _=St.current.getMessages().find(Z=>{var ve;return((ve=Z.toolCall)==null?void 0:ve.id)===C});(se=_==null?void 0:_.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(_,(oe=f.structured)!=null?oe:y):St.current.sendMessage(y)},Fn=i=>{var C;let p=St.current;if(!p)return;let f=(C=i.getAttribute("data-tool-call-id"))!=null?C:"",y=p.getMessages().find(E=>{var _;return((_=E.toolCall)==null?void 0:_.id)===f});y&&p.persistAskUserQuestionProgress(y,{answers:Ta(i,y),currentIndex:er(i)})},no=i=>Object.entries(i).map(([p,f])=>`${p}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),xe=i=>{var C,E,_;if(((E=(C=r.features)==null?void 0:C.askUserQuestion)==null?void 0:E.groupedAutoAdvance)===!1)return;let p=er(i),f=us(i);if(p>=f-1)return;let y=(_=St.current)==null?void 0:_.getMessages().find(N=>{var D;return((D=N.toolCall)==null?void 0:D.id)===i.getAttribute("data-tool-call-id")});y&&(Ea(i,y,r,p+1),Fn(i))};Vn.addEventListener("click",i=>{var E,_,N,D,se,oe,Z,ve,Ne,Fe,$e,ze,ut,st;let f=i.target.closest("[data-ask-user-action]");if(!f)return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;let C=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),C==="dismiss"){let He=(E=y.getAttribute("data-tool-call-id"))!=null?E:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),ms(Vn,He);let Ie=(_=St.current)==null?void 0:_.getMessages().find(qe=>{var Ge;return((Ge=qe.toolCall)==null?void 0:Ge.id)===He});(N=Ie==null?void 0:Ie.agentMetadata)!=null&&N.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Ie),(se=St.current)==null||se.resolveAskUserQuestion(Ie,"(dismissed)"));return}if(C==="pick"){let He=f.getAttribute("data-option-label");if(!He)return;let Ie=y.getAttribute("data-multi-select")==="true",qe=ho(y);if(qe&&Ie){let Ge=$o(y)[er(y)],bt=new Set(Array.isArray(Ge)?Ge:[]);bt.has(He)?bt.delete(He):bt.add(He),yo(y,Array.from(bt)),Fn(y);return}if(qe){yo(y,He),Fn(y),xe(y);return}if(Ie){let Ge=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Ge?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Ge);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Bi(y).length===0);return}Kn(y,He,{source:"pick",values:[He]});return}if(C==="submit-multi"){let He=Bi(y);if(He.length===0)return;Kn(y,He.join(", "),{source:"multi",values:He});return}if(C==="open-free-text"){let He=y.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let Ie=He.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus()}return}if(C==="focus-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(C==="submit-free-text"){let He=y.querySelector('[data-ask-free-text-input="true"]'),Ie=(oe=He==null?void 0:He.value)!=null?oe:"";if(!Ie.trim())return;if(ho(y)){yo(y,Ie.trim()),Fn(y),xe(y);return}Kn(y,Ie,{source:"free-text"});return}if(C==="next"||C==="back"){if(!St.current)return;let He=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",Ie=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(Ne=(ve=qe==null?void 0:qe.value)==null?void 0:ve.trim())!=null?Ne:"";if(Ge){let Be=$o(y)[er(y)];(typeof Be!="string"||Be!==Ge)&&yo(y,Ge)}let bt=C==="next"?1:-1,L=er(y)+bt;Ea(y,Ie,r,L),Fn(y);return}if(C==="submit-all"){if(!St.current)return;let He=(Fe=y.getAttribute("data-tool-call-id"))!=null?Fe:"",Ie=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===He});if(!Ie)return;let qe=y.querySelector('[data-ask-free-text-input="true"]'),Ge=(ze=($e=qe==null?void 0:qe.value)==null?void 0:$e.trim())!=null?ze:"";Ge&&yo(y,Ge);let bt=Ta(y,Ie);St.current.persistAskUserQuestionProgress(Ie,{answers:bt,currentIndex:er(y)});let L=no(bt);Kn(y,L||"(submitted)",{source:"submit-all",structured:bt});return}if(C==="skip"){if(!St.current)return;let He=(ut=y.getAttribute("data-tool-call-id"))!=null?ut:"",Ie=St.current.getMessages().find(We=>{var Xe;return((Xe=We.toolCall)==null?void 0:Xe.id)===He});if(!Ie)return;let qe=ho(y),Ge=er(y),bt=us(y),L=Ge>=bt-1;if(!qe){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),ms(Vn,He),(st=Ie.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Ie),St.current.resolveAskUserQuestion(Ie,"(dismissed)"));return}yo(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),L){let We=Ta(y,Ie),Xe=no(We);Kn(y,Xe||"(skipped)",{source:"submit-all",structured:We});return}Ea(y,Ie,r,Ge+1),Fn(y);return}}),Vn.addEventListener("keydown",i=>{var E;if(i.key!=="Enter")return;let f=i.target;if(!((E=f.matches)!=null&&E.call(f,'[data-ask-free-text-input="true"]')))return;let y=f.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let C=f.value;if(C.trim()){if(ho(y)){yo(y,C.trim()),Fn(y),xe(y);return}Kn(y,C,{source:"free-text"})}});let Dr=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let p=i.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let f=Vn.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),E=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",Dr);let Gn=null,Ot=null,Qn=null,Nr=null,Ms=()=>{};function Xo(){Nr==null||Nr(),Nr=null}let Es=()=>{var _;if(!Gn||!Ot)return;let i=n.classList.contains("persona-artifact-appearance-seamless"),f=((_=n.ownerDocument.defaultView)!=null?_:window).innerWidth<=640;if(!i||n.classList.contains("persona-artifact-narrow-host")||f){Ot.style.removeProperty("position"),Ot.style.removeProperty("left"),Ot.style.removeProperty("top"),Ot.style.removeProperty("bottom"),Ot.style.removeProperty("width"),Ot.style.removeProperty("z-index");return}let y=Gn.firstElementChild;if(!y||y===Ot)return;let C=10;Ot.style.position="absolute",Ot.style.top="0",Ot.style.bottom="0",Ot.style.width=`${C}px`,Ot.style.zIndex="5";let E=y.offsetWidth-C/2;Ot.style.left=`${Math.max(0,E)}px`},Mo=()=>{},xr=()=>{var f,y,C,E,_;if(!wt||!tr(r))return;li(n,r),ci(n,r),Mo();let i=(E=(C=(y=(f=r.features)==null?void 0:f.artifacts)==null?void 0:y.layout)==null?void 0:C.narrowHostMaxWidth)!=null?E:520,p=Q.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=i),wt.update(Nn),An?(wt.setMobileOpen(!1),wt.element.classList.add("persona-hidden"),(_=wt.backdrop)==null||_.classList.add("persona-hidden")):Nn.artifacts.length>0&&(wt.element.classList.remove("persona-hidden"),wt.setMobileOpen(!0)),Ms()};if(tr(r)){Q.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Te),wt=Zm(r,{onSelect:f=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(f)},onDismiss:()=>{An=!0,xr()}}),wt.element.classList.add("persona-hidden"),Gn=p,p.appendChild(i),p.appendChild(wt.element),wt.backdrop&&Q.appendChild(wt.backdrop),Q.appendChild(p),Ms=()=>{var y,C,E,_;if(!Gn||!wt)return;if(!(((E=(C=(y=r.features)==null?void 0:y.artifacts)==null?void 0:C.layout)==null?void 0:E.resizable)===!0)){Qn==null||Qn(),Qn=null,Xo(),Ot&&(Ot.remove(),Ot=null),wt.element.style.removeProperty("width"),wt.element.style.removeProperty("maxWidth");return}if(!Ot){let N=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");N.setAttribute("role","separator"),N.setAttribute("aria-orientation","vertical"),N.setAttribute("aria-label","Resize artifacts panel"),N.tabIndex=0;let D=n.ownerDocument,se=(_=D.defaultView)!=null?_:window,oe=Z=>{var ut,st;if(!wt||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Xo();let ve=Z.clientX,Ne=wt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,$e=He=>{let Ie=Gn.getBoundingClientRect().width,qe=n.classList.contains("persona-artifact-appearance-seamless"),Ge=qe?0:rg(Gn,se),bt=qe?0:N.getBoundingClientRect().width||6,L=Ne-(He.clientX-ve),Be=og(L,Ie,Ge,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);wt.element.style.width=`${Be}px`,wt.element.style.maxWidth="none",Es()},ze=()=>{D.removeEventListener("pointermove",$e),D.removeEventListener("pointerup",ze),D.removeEventListener("pointercancel",ze),Nr=null;try{N.releasePointerCapture(Z.pointerId)}catch{}};Nr=ze,D.addEventListener("pointermove",$e),D.addEventListener("pointerup",ze),D.addEventListener("pointercancel",ze);try{N.setPointerCapture(Z.pointerId)}catch{}};N.addEventListener("pointerdown",oe),Ot=N,Gn.insertBefore(N,wt.element),Qn=()=>{N.removeEventListener("pointerdown",oe)}}if(Ot){let N=Nn.artifacts.length>0&&!An;Ot.classList.toggle("persona-hidden",!N),Es()}},Mo=()=>{var se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie,qe,Ge;if(!I||!wt||((oe=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?oe:!1)||fn(r)&&ur(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,C=(Ne=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Ne:!0,E=($e=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?$e:640;if(C&&y.innerWidth<=E||!ng(r,I))return;let _=(st=(ut=(ze=r.launcher)==null?void 0:ze.width)!=null?ut:r.launcherWidth)!=null?st:Gr,N=(Ge=(qe=(Ie=(He=r.features)==null?void 0:He.artifacts)==null?void 0:Ie.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ge:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!An?(Q.style.width=N,Q.style.maxWidth=N):(Q.style.width=_,Q.style.maxWidth=_)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{xr()}),Dn.observe(Q))}else Q.appendChild(Te),k()&&it&&(je.peekBanner&&it.appendChild(je.peekBanner),it.appendChild(Re));n.appendChild(ue),it&&n.appendChild(it);let ro=()=>{var Be,We,Xe,Pt,Oe,Kt,xt,sn,Wn,Bt,mn,_n,Ve,It,$n,Io,Wo,Ro,Ho,as,is,Gt,Bo,uo,mo,qr,Do,Ze;if(k()){Q.style.width="100%",Q.style.maxWidth="100%";let Nt=(We=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?We:{},Dt=ue.dataset.state==="expanded",Vt=(Xe=Nt.expandedSize)!=null?Xe:"anchored";if(!(Dt&&Vt!=="fullscreen")){Te.style.background="",Te.style.border="",Te.style.borderRadius="",Te.style.overflow="",Te.style.boxShadow="";return}let mt=(Oe=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:Oe.panel,Ut=Oa(r),gn=(pn,Zn)=>{var go;return pn==null||pn===""?Zn:(go=ys(Ut,pn))!=null?go:pn},Un="1px solid var(--persona-border)",Lr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Te.style.background="var(--persona-surface, #ffffff)",Te.style.border=gn(mt==null?void 0:mt.border,Un),Te.style.borderRadius=gn(mt==null?void 0:mt.borderRadius,dn),Te.style.boxShadow=gn(mt==null?void 0:mt.shadow,Lr),Te.style.overflow="hidden";return}let i=fn(r),p=(xt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?xt:!1,f=i||p||((Wn=(sn=r.launcher)==null?void 0:sn.fullHeight)!=null?Wn:!1),y=((Bt=r.launcher)==null?void 0:Bt.enabled)===!1,C=(_n=(mn=r.theme)==null?void 0:mn.components)==null?void 0:_n.panel,E=Oa(r),_=(Nt,Dt)=>{var Vt;return Nt==null||Nt===""?Dt:(Vt=ys(E,Nt))!=null?Vt:Nt},N=(Ve=n.ownerDocument.defaultView)!=null?Ve:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,se=(Wo=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Wo:640,oe=N.innerWidth<=se,Z=D&&oe&&I,ve=(Ho=(Ro=r.launcher)==null?void 0:Ro.position)!=null?Ho:"bottom-left",Ne=ve==="bottom-left"||ve==="top-left",Fe=(is=(as=r.launcher)==null?void 0:as.zIndex)!=null?is:wn,$e=p||Z?"none":"1px solid var(--persona-border)",ze=Z?"none":p?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";i&&!Z&&(ze="none",$e="none");let ut=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=_(C==null?void 0:C.border,$e),He=_(C==null?void 0:C.shadow,ze),Ie=_(C==null?void 0:C.borderRadius,ut),qe=we.scrollTop;n.style.cssText="",ue.style.cssText="",Q.style.cssText="",Te.style.cssText="",we.style.cssText="",Re.style.cssText="",J&&(we.style.display="none");let Ge=()=>{var Dt;if(qe<=0)return;((Dt=we.ownerDocument.defaultView)!=null?Dt:window).requestAnimationFrame(()=>{if(we.scrollTop===qe)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(qe,Vt))})};if(Z){ue.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ue.style.cssText=`
|
|
46
|
+
`,x.addEventListener("click",()=>{u=N,H.forEach((U,V)=>{let J=V<N;U.classList.toggle("selected",J),U.setAttribute("aria-checked",V===N-1?"true":"false")})}),H.push(x),P.appendChild(x)}w.appendChild(P);let M=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),N.appendChild(M),w.appendChild(N)}let T=document.createElement("div");T.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=l,I.addEventListener("click",()=>{n?.(),c.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=a,z.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let N=M?.value.trim()||void 0;await e(u,N),c.remove()}catch(N){z.disabled=!1,z.textContent=a,console.error("[CSAT Feedback] Failed to submit:",N)}}),T.appendChild(I),T.appendChild(z),w.appendChild(T),c.appendChild(w),c}function fu(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=r,b.appendChild(P),f.appendChild(b);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=c,M.appendChild(T),M.appendChild(I);let z=document.createElement("div");z.className="persona-feedback-numbers";let N=[];for(let D=0;D<=10;D++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${D} out of 10`),$.textContent=String(D),$.dataset.rating=String(D),D<=6?$.classList.add("persona-feedback-detractor"):D<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{w=D,N.forEach((fe,he)=>{fe.classList.toggle("selected",he===D),fe.setAttribute("aria-checked",he===D?"true":"false")})}),N.push($),z.appendChild($)}H.appendChild(M),H.appendChild(z),f.appendChild(H);let x=null;if(p){let D=document.createElement("div");D.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"),D.appendChild(x),f.appendChild(D)}let U=document.createElement("div");U.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),u.remove()});let J=document.createElement("button");return J.type="button",J.className="persona-feedback-btn persona-feedback-btn-submit",J.textContent=a,J.addEventListener("click",async()=>{if(w===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}J.disabled=!0,J.textContent="Submitting...";try{let D=x?.value.trim()||void 0;await e(w,D),u.remove()}catch(D){J.disabled=!1,J.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),U.appendChild(V),U.appendChild(J),f.appendChild(U),u.appendChild(f),u}var hr="persona-chat-history",ly=30*1e3,cy=641,dy={"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 py(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=dy[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Ka(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function uy(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function fy(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Ml=t=>!t||typeof t!="object"?{}:{...t},gu=t=>t.map(e=>({...e,streaming:!1})),mu=(t,e,n)=>{let o=t?.markdown?Js(t.markdown):null,r=Ys(t?.sanitize);return t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(e){let c=e.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Hn()!==null,d;if(t?.postprocessMessage){let c=t.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Yc(a):a,u=o(c);d=r&&p?r(u):u}else d=Zn(a);return d}};function hu(t){let e=m("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=oe(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=m("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var gy=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},my=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:gy(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),yu=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=qd(e),r=xl.getForInstance(o.plugins),{plugin:s,teardown:a}=Kp();o.components&&_n.registerAll(o.components);let l=au(),d=o.persistState===!1?null:o.storageAdapter??lu(),c={},u=null,w=!1,f=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:y}=g;return y&&(w=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(g=>f(g??{messages:[],metadata:{}}));else{let h=f(i??{messages:[],metadata:{}});h.metadata&&(c=Ml(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let b=()=>c,C=i=>{c=i({...c})??{},pi()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Al],H=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Cs.message,Cs.messageAndClick],M=Sl({parsers:P,handlers:H,getSessionMetadata:b,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let T=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,N=I,x=T,U=o.layout?.header?.layout,V=!1,J=()=>gs(o),D=()=>T||J(),$=J()?!1:T?I:!0,fe=!1,he=null,Ee=()=>{fe=!0,he&&clearTimeout(he),he=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},xe=mu(o,M,Ee),te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,le=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},ve=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ue=Y?new bs(ve):null,Te=o.features?.eventStream?.maxEvents??2e3,Ce=Y?new ys(Te,ue):null,je=Y?new vs:null,Fe=null,Pe=!1,Be=null,at=0;ue?.open().then(()=>Ce?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let _e={onCopy:i=>{l.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Xe=o.statusIndicator??{},an=i=>i==="idle"?Xe.idleText??Rt.idle:i==="connecting"?Xe.connectingText??Rt.connecting:i==="connected"?Xe.connectedText??Rt.connected:i==="error"?Xe.errorText??Rt.error:i==="paused"?Xe.pausedText??Rt.paused:i==="resuming"?Xe.resumingText??Rt.resuming:Rt[i];function Et(i,g,h,y){if(y==="idle"&&h.idleLink){i.textContent="";let A=document.createElement("a");A.href=h.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 ft=Hp({config:o,showClose:D()}),{wrapper:ke,panel:me,pillRoot:it}=ft.shell,Ie=ft.panelElements,{container:pe,body:ie,messagesWrapper:ye,suggestions:bt,textarea:F,sendButton:ne,sendButtonWrapper:De,composerForm:Se,statusText:E,introTitle:Q,introSubtitle:v,closeButton:S,iconHolder:k,headerTitle:W,headerSubtitle:G,header:B,footer:j,actionsRow:ae,rightActions:tt}=Ie,Me=Ie.leftActions,lt=Ie.setSendButtonMode,q=Ie.micButton,ze=Ie.micButtonWrapper,Re=Ie.attachmentButton,We=Ie.attachmentButtonWrapper,Le=Ie.attachmentInput,Je=Ie.attachmentPreviewsContainer;pe.classList.add("persona-relative"),ie.classList.add("persona-relative");let co=12,po=()=>le.label??"",Qa=()=>le.iconName??"arrow-down",Ss=()=>le.enabled!==!1,Xt=()=>Z.mode??"anchor-top",$n=()=>Xt()==="follow"||Xt()==="anchor-top"&&Mr,Wl=()=>Z.anchorTopOffset??16,Lu=()=>Z.restorePosition??"bottom",Bl=()=>Z.pauseOnInteraction===!0,Hl=()=>Z.showActivityWhilePinned!==!1,Dl=()=>Z.announce===!0,Pt=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let br=m("span","persona-flex persona-items-center"),Xa=m("span",""),uo=m("span","");uo.setAttribute("data-persona-scroll-to-bottom-count",""),uo.style.display="none",Pt.append(br,Xa,uo),pe.appendChild(Pt);let zn=m("div","persona-stream-anchor-spacer");zn.setAttribute("aria-hidden","true"),zn.setAttribute("data-persona-anchor-spacer",""),zn.style.flexShrink="0",zn.style.pointerEvents="none",zn.style.height="0px",ie.appendChild(zn);let fo=m("div","persona-sr-only");fo.setAttribute("aria-live","polite"),fo.setAttribute("aria-atomic","true"),fo.setAttribute("role","status"),fo.setAttribute("data-persona-live-region",""),Object.assign(fo.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"}),pe.appendChild(fo);let vr=null,Ts=null,Nl=i=>{!Dl()||!i||(Ts=i,vr===null&&(vr=setTimeout(()=>{vr=null,Ts&&Dl()&&(fo.textContent=Ts),Ts=null},400)))},Oo=()=>{let g=j.style.display==="none"?0:j.offsetHeight;Pt.style.bottom=`${g+co}px`};Oo();let Fl=()=>{let i=!!po();Pt.setAttribute("aria-label",po()||"Jump to latest"),Pt.title=po(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),br.innerHTML="";let g=oe(Qa(),"14px","currentColor",2);g?(br.appendChild(g),br.style.display=""):br.style.display="none",Xa.textContent=po(),Xa.style.display=i?"":"none"};Fl();let Tt=null,Zt=null,Ol=null,_l=r.find(i=>i.renderHeader);if(_l?.renderHeader){let i=_l.renderHeader({config:o,defaultRenderer:()=>{let g=Ho({config:o,showClose:D()});return ms(pe,g,o),g.header},onClose:()=>mt(!1,"user")});if(i){let g=pe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),B=i,ft.header.element=i)}}let Ja=()=>{if(!Ce)return;if(Pe=!0,!Fe&&Ce&&(Fe=Yp({buffer:Ce,getFullHistory:()=>Ce.getAllFromStore(),onClose:()=>wr(),config:o,plugins:r,getThroughput:()=>je?.getMetric()??{status:"idle"}})),Fe&&(ie.style.display="none",j.parentNode?.insertBefore(Fe.element,j),Fe.update()),rt){rt.style.boxShadow=`inset 0 0 0 1.5px ${Gt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&rt.classList.add(h))}let i=()=>{if(!Pe)return;let g=Date.now();g-at>=200&&(Fe?.update(),at=g),Be=requestAnimationFrame(i)};at=0,Be=requestAnimationFrame(i),tn(),l.emit("eventStream:opened",{timestamp:Date.now()})},wr=()=>{if(Pe){if(Pe=!1,Fe&&Fe.element.remove(),ie.style.display="",rt){rt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&rt.classList.remove(g))}Be!==null&&(cancelAnimationFrame(Be),Be=null),tn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},rt=null;if(Y){let i=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");rt=m("button",g),rt.style.width="28px",rt.style.height="28px",rt.style.color=Gt.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let h=oe("activity","18px","currentColor",1.5);h&&rt.appendChild(h);let y=Ie.clearChatButtonWrapper,A=Ie.closeButtonWrapper,L=y||A;L&&L.parentNode===B?B.insertBefore(rt,L):B.appendChild(rt),rt.addEventListener("click",()=>{Pe?wr():Ja()})}let Pu=i=>{let g=o.attachments;if(!g?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let A=i.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(g.allowedTypes??Fn).join(","),A.multiple=(g.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(A)}},$l=r.find(i=>i.renderComposer);if($l?.renderComposer){let i=o.composer,g=$l.renderComposer({config:o,defaultRenderer:()=>Ua({config:o}).footer,onSubmit:h=>{if(!_||_.isStreaming())return;let y=h.trim(),A=Tt?.hasAttachments()??!1;if(!y&&!A)return;hc();let L;A&&(L=[],L.push(...Tt.getContentParts()),y&&L.push(rr(y))),_.sendMessage(y,{contentParts:L}),A&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Le?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Ol?.()}:void 0});g&&(ft.replaceComposer(g),j=ft.composer.footer)}let Iu=i=>{let g=(...ce)=>{for(let se of ce){let we=i.querySelector(se);if(we)return we}return null},h=i.querySelector("[data-persona-composer-form]"),y=i.querySelector("[data-persona-composer-input]"),A=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),X=i.querySelector("[data-persona-composer-status]");h&&(Se=h),y&&(F=y),A&&(ne=A),L&&(q=L,ze=L.parentElement),X&&(E=X);let O=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(bt=O);let K=g("[data-persona-composer-attachment-button]",".persona-attachment-button");K&&(Re=K,We=K.parentElement),Le=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Je=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(ae=re),Me=g(".persona-widget-composer__left-actions")};Pu(j),Iu(j);let Un=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Un&&(ye.style.maxWidth=Un,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%"),Un&&Se&&!J()&&(Se.style.maxWidth=Un,Se.style.marginLeft="auto",Se.style.marginRight="auto"),Un&&bt&&!J()&&(bt.style.maxWidth=Un,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Un&&Je&&!J()&&(Je.style.maxWidth=Un,Je.style.marginLeft="auto",Je.style.marginRight="auto"),o.attachments?.enabled&&Le&&Je){Tt=ts.fromConfig(o.attachments),Tt.setPreviewsContainer(Je),Le.addEventListener("change",h=>{let y=h.target;Tt?.handleFileSelect(y.files),y.value=""});let i=o.attachments.dropOverlay,g=hu(i);pe.appendChild(g)}let Ru=()=>Zt?.prefetch();if(o.contextMentions?.enabled&&F&&(Zt=zd({config:o,textarea:F,anchor:Se??F,getMessages:()=>_.getMessages(),liveRegionHost:pe}),Zt)){let i=F;i.parentElement?.insertBefore(Zt.contextRow,i);let g=Zt.affordanceButtons;for(let h=g.length-1;h>=0;h--){let y=g[h];Me?Me.insertBefore(y,Me.firstChild):Se?.appendChild(y)}}(()=>{let i=o.layout?.slots??{},g=y=>{switch(y){case"body-top":return pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ye;case"footer-top":return bt;case"composer":return Se;case"footer-bottom":return E;default:return null}},h=(y,A)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")B.insertBefore(A,B.firstChild);else if(y==="header-right")B.appendChild(A);else{let L=B.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(A,L.nextSibling):B.appendChild(A)}break;case"body-top":{let L=ie.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(A):ie.insertBefore(A,ie.firstChild);break}case"body-bottom":ie.appendChild(A);break;case"footer-top":bt.replaceWith(A);break;case"footer-bottom":E.replaceWith(A);break;default:break}};for(let[y,A]of Object.entries(i))if(A)try{let L=A({config:o,defaultContent:()=>g(y)});L&&h(y,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,L)}})();let zl=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let L=h.getAttribute("data-bubble-type");if(L==="reasoning")fr.has(A)?fr.delete(A):fr.add(A),_p(A,y);else if(L==="tool")gr.has(A)?gr.delete(A):gr.add(A),$p(A,y,o);else if(L==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",K=Do.get(A)??O;Do.set(A,!K),Vp(A,y,o)}yo.delete(A)};ye.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),zl(i))}),ye.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),zl(i))}),ye.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let h=ye.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let A=y.toString(),L=yp(A);!L||L===A||(g.setData("text/plain",L),i.preventDefault())});let Ya=new Map,Ul=null,jl="idle",Wu={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Bu=(i,g)=>{let{icon:h,label:y}=Wu[g];i.setAttribute("aria-label",y),i.title=y,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=oe(h,14,"currentColor",2);A&&(i.innerHTML="",i.appendChild(A))},Vl=()=>{ye.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let y=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Bu(g,y&&y===Ul?jl:"idle")})};ye.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let A=y.getAttribute("data-actions-for");if(!A)return;let L=h.getAttribute("data-action");if(L==="copy"){let O=_.getMessages().find(K=>K.id===A);if(O&&_e.onCopy){let K=O.content||"";navigator.clipboard.writeText(K).then(()=>{h.classList.add("persona-message-action-success");let re=oe("check",14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ce=oe("copy",14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),_e.onCopy(O)}}else if(L==="read-aloud")_.toggleReadAloud(A);else if(L==="upvote"||L==="downvote"){let O=(Ya.get(A)??null)===L,K=L==="upvote"?"thumbs-up":"thumbs-down";if(O){Ya.delete(A),h.classList.remove("persona-message-action-active");let re=oe(K,14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re))}else{let re=L==="upvote"?"downvote":"upvote",ce=y.querySelector(`[data-action="${re}"]`);if(ce){ce.classList.remove("persona-message-action-active");let st=oe(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);st&&(ce.innerHTML="",ce.appendChild(st))}Ya.set(A,L),h.classList.add("persona-message-action-active");let se=oe(K,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(se)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ke=_.getMessages().find(ht=>ht.id===A);Ke&&_e.onFeedback&&_e.onFeedback({type:L,messageId:Ke.id,message:Ke})}}}),ye.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let A=y.getAttribute("data-message-id");if(!A)return;let L=h.getAttribute("data-approval-action");if(!L)return;let X=L==="approve"?"approved":"denied",K=_.getMessages().find(ce=>ce.id===A);if(!K?.approval)return;let re=y.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),K.approval.toolType==="webmcp"?_.resolveWebMcpApproval(A,X):_.resolveApproval(K.approval,X)});let Ye=null,xr=null,Cr=()=>{},Ar="none",Ms=null,gn={artifacts:[],selectedId:null},kn=!1,mn=!1,Sr=!1,_o=!1,ql=()=>_o||gn.artifacts.some(i=>ko(o.features?.artifacts,i.artifactType)==="panel"),Es=()=>gn.artifacts.length>0&&!kn&&ql(),gt={current:null},Za=(i,g)=>{let h=_.getArtifactById(g),y=h?.markdown,A=h?.title||"artifact",L=h?.file,X=h?.artifactType??"markdown";if(!y){let re=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let se=_.getMessages().find(we=>we.id===re);if(se?.rawContent)try{let we=JSON.parse(se.rawContent);y=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(L=we.props.file),!h&&typeof we?.props?.artifactType=="string"&&(X=we.props.artifactType)}catch{}}}return{markdown:y,title:A,file:L,artifactType:X}};ye.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:L,title:X,file:O}=Za(h,y);if(!L)return;let{filename:K,mime:re,content:ce}=Zd({title:X,markdown:L,file:O}),se=new Blob([ce],{type:re}),we=URL.createObjectURL(se),Ke=document.createElement("a");Ke.href=we,Ke.download=K,Ke.click(),URL.revokeObjectURL(we)}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.getAttribute("data-artifact-custom-action");if(!y)return;let A=h.closest("[data-artifact-inline]"),L=A?null:h.closest("[data-open-artifact]"),X=A?A.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,K=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===y);if(!K)return;let{markdown:re,title:ce,file:se,artifactType:we}=Za(h,X??""),Ke={artifactId:X,title:ce,artifactType:we,markdown:re,file:se};try{Promise.resolve(K.onClick(Ke)).catch(()=>{})}catch{}}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.getAttribute("data-copy-artifact");if(!y)return;let A=_.getArtifactById(y),L="";if(A)L=ls(A);else{let{markdown:X,file:O,artifactType:K}=Za(h,y);K==="markdown"&&(L=ls({id:y,artifactType:"markdown",status:"complete",markdown:X??"",...O?{file:O}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let X=oe("check",16,"currentColor",2);X&&(h.replaceChildren(X),setTimeout(()=>{let O=oe("copy",16,"currentColor",2);O&&h.replaceChildren(O)},1500))}).catch(()=>{})}),ye.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let y=h.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(kn=!1,_o=!0,mn=!0,Sr=!0,_.selectArtifact(y),Ln())}),ye.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),kn=!1,_o=!0,_.selectArtifact(y),Ln())}),ye.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let $o=Ie.composerOverlay,zo=(i,g,h)=>{let y=g.trim();if(!y||!gt.current)return;let A=i.getAttribute("data-tool-call-id")??"",L=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:y,answers:h.structured,values:h.values??(h.source==="multi"?y.split(", "):[y]),isFreeText:L,source:h.source},bubbles:!0,composed:!0})),nr($o,A);let X=gt.current.getMessages().find(O=>O.toolCall?.id===A);X?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(X,h.structured??y):gt.current.sendMessage(y)},go=i=>{let g=gt.current;if(!g)return;let h=i.getAttribute("data-tool-call-id")??"",y=g.getMessages().find(A=>A.toolCall?.id===h);y&&g.persistAskUserQuestionProgress(y,{answers:na(i,y),currentIndex:un(i)})},Kl=i=>Object.entries(i).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ei=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=un(i),h=tr(i);if(g>=h-1)return;let y=gt.current?.getMessages().find(A=>A.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&(ra(i,y,o,g+1),go(i))};$o.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let A=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),A==="dismiss"){let L=y.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),nr($o,L);let X=gt.current?.getMessages().find(O=>O.toolCall?.id===L);X?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(X),gt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(A==="pick"){let L=h.getAttribute("data-option-label");if(!L)return;let X=y.getAttribute("data-multi-select")==="true",O=eo(y);if(O&&X){let K=Po(y)[un(y)],re=new Set(Array.isArray(K)?K:[]);re.has(L)?re.delete(L):re.add(L),to(y,Array.from(re)),go(y);return}if(O){to(y,L),go(y),ei(y);return}if(X){let K=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",K?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!K);let re=y.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=Ni(y).length===0);return}zo(y,L,{source:"pick",values:[L]});return}if(A==="submit-multi"){let L=Ni(y);if(L.length===0)return;zo(y,L.join(", "),{source:"multi",values:L});return}if(A==="open-free-text"){let L=y.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let X=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(eo(y)){to(y,X.trim()),go(y),ei(y);return}zo(y,X,{source:"free-text"});return}if(A==="next"||A==="back"){if(!gt.current)return;let L=y.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(se=>se.toolCall?.id===L);if(!X)return;let K=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(K){let se=Po(y)[un(y)];(typeof se!="string"||se!==K)&&to(y,K)}let re=A==="next"?1:-1,ce=un(y)+re;ra(y,X,o,ce),go(y);return}if(A==="submit-all"){if(!gt.current)return;let L=y.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(se=>se.toolCall?.id===L);if(!X)return;let K=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";K&&to(y,K);let re=na(y,X);gt.current.persistAskUserQuestionProgress(X,{answers:re,currentIndex:un(y)});let ce=Kl(re);zo(y,ce||"(submitted)",{source:"submit-all",structured:re});return}if(A==="skip"){if(!gt.current)return;let L=y.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(we=>we.toolCall?.id===L);if(!X)return;let O=eo(y),K=un(y),re=tr(y),ce=K>=re-1;if(!O){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),nr($o,L),X.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(X),gt.current.resolveAskUserQuestion(X,"(dismissed)"));return}to(y,"");let se=y.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),ce){let we=na(y,X),Ke=Kl(we);zo(y,Ke||"(skipped)",{source:"submit-all",structured:we});return}ra(y,X,o,K+1),go(y);return}}),$o.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let A=h.value;if(A.trim()){if(eo(y)){to(y,A.trim()),go(y),ei(y);return}zo(y,A,{source:"free-text"})}});let Gl=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let h=$o.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),L=h.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];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",Gl);let jn=null,vt=null,Tr=null,ks=null,ti=()=>{},Ql=!1,Ls="",Ps="";function ni(){ks?.(),ks=null}let Xl=()=>{if(!jn||!vt)return;let i=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||h){vt.style.removeProperty("position"),vt.style.removeProperty("left"),vt.style.removeProperty("top"),vt.style.removeProperty("bottom"),vt.style.removeProperty("width"),vt.style.removeProperty("z-index");return}let y=jn.firstElementChild;if(!y||y===vt)return;let A=10;vt.style.position="absolute",vt.style.top="0",vt.style.bottom="0",vt.style.width=`${A}px`,vt.style.zIndex="5";let L=bl(jn,g),X=y.offsetWidth+L/2-A/2;vt.style.left=`${Math.max(0,X)}px`},Is=()=>{},Hu=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>h?!1:T||Ft(o)},Rs=()=>!Qt(o)||!Es()||t.classList.contains("persona-artifact-narrow-host")||Hu()||(t.ownerDocument.defaultView??window).innerWidth<cy?"none":yl(o)?"detached":"welded",Ln=()=>{if(!Ye||!Qt(o))return;ws(t,o),xs(t,o),Is();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=me.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let h=Es();Ye.setVisible(h),Ye.update(gn),kn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),mn=!1,Sr=!1):gn.artifacts.length>0&&ql()?(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,Sr=!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&&!Sr&&(mn=!1),mn!==Ql){let L=Ye.element;mn?(Ls=L.style.width,Ps=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Ls&&(L.style.width=Ls),Ps&&(L.style.maxWidth=Ps),Ls="",Ps=""),Ql=mn}t.classList.toggle("persona-artifact-expanded",mn),Ye.setExpanded(mn);let A=Rs();A!==Ar&&(Ar=A,Cr()),ti()};if(Qt(o)){me.style.position="relative";let i=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(pe),Ye=eu(o,{onSelect:h=>gt.current?.selectArtifact(h),onDismiss:()=>{kn=!0,Ln()},onToggleExpand:()=>{let h=!mn,y=gn.selectedId??gn.artifacts[gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:y,expanded:h})!==!0&&(mn=h,h||(Sr=!1),Ln())}}),Ye.element.classList.add("persona-hidden"),jn=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&me.appendChild(Ye.backdrop),me.appendChild(g),ti=()=>{if(!jn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Tr?.(),Tr=null,ni(),vt&&(vt.remove(),vt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!vt){let y=m("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 A=t.ownerDocument,L=A.defaultView??window,X=O=>{if(!Ye||O.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;O.preventDefault(),ni();let K=O.clientX,re=Ye.element.getBoundingClientRect().width,ce=o.features?.artifacts?.layout,se=Ke=>{let ht=jn.getBoundingClientRect().width,st=t.classList.contains("persona-artifact-welded-split"),jt=bl(jn,L),Bt=st?0:y.getBoundingClientRect().width||6,R=re-(Ke.clientX-K),Oe=ru(R,ht,jt,Bt,ce?.resizableMinWidth,ce?.resizableMaxWidth);Ye.element.style.width=`${Oe}px`,Ye.element.style.maxWidth="none",Xl()},we=()=>{A.removeEventListener("pointermove",se),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),ks=null;try{y.releasePointerCapture(O.pointerId)}catch{}};ks=we,A.addEventListener("pointermove",se),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{y.setPointerCapture(O.pointerId)}catch{}};y.addEventListener("pointerdown",X),vt=y,jn.insertBefore(y,Ye.element),Tr=()=>{y.removeEventListener("pointerdown",X)}}if(vt){let y=Es();vt.classList.toggle("persona-hidden",!y),Xl()}},Is=()=>{if(!T||!Ye||(o.launcher?.sidebarMode??!1)||Ft(o)&&fn(o).reveal==="emerge")return;let y=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(A&&y.innerWidth<=L||!ou(o,T))return;let X=o.launcher?.width??o.launcherWidth??On,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Es()?(me.style.width=O,me.style.maxWidth=O):(me.style.width=X,me.style.maxWidth=X)},typeof ResizeObserver<"u"&&(xr=new ResizeObserver(()=>{Ln()}),xr.observe(me))}else me.appendChild(pe);J()&&it&&(Ie.peekBanner&&it.appendChild(Ie.peekBanner),it.appendChild(j)),t.appendChild(ke),it&&t.appendChild(it);let Ws=()=>{if(J()){me.style.width="100%",me.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},Jt=ke.dataset.state==="expanded",qs=Lt.expandedSize??"anchored";if(!(Jt&&qs!=="fullscreen")){pe.style.background="",pe.style.border="",pe.style.borderRadius="",pe.style.overflow="",pe.style.boxShadow="";return}let Or=o.theme?.components?.panel,Ks=ir(o),Xo=(Wn,To)=>Wn==null||Wn===""?To:Kt(Ks,Wn)??Wn,_r="1px solid var(--persona-border)",Ei="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",So="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";pe.style.background="var(--persona-surface, #ffffff)",pe.style.border=Xo(Or?.border,_r),pe.style.borderRadius=Xo(Or?.borderRadius,So),pe.style.boxShadow=Xo(Or?.shadow,Ei),pe.style.overflow="hidden";return}let i=Ft(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,X=ir(o),O=(Lt,Jt)=>Lt==null||Lt===""?Jt:Kt(X,Lt)??Lt,K=t.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,ce=o.launcher?.mobileBreakpoint??640,se=K.innerWidth<=ce,we=re&&se&&T,Ke=i&&re&&se,ht=o.launcher?.position??"bottom-left",st=ht==="bottom-left"||ht==="top-left",jt=o.launcher?.zIndex??zt,Bt="var(--persona-panel-border, 1px solid var(--persona-border))",R="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Oe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ae=A&&!we&&!Ke;Ae?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let $e=Ae?Bt:g||we?"none":Bt,St=Ae?R:we?"none":g?st?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":y?"none":R;i&&!we&&!Ae&&(St="none",$e="none");let pt=Ae?Oe:g||we?"0":Oe,xt=O(L?.border,$e),yt=O(L?.shadow,St),_t=O(L?.borderRadius,pt),Co=Rs(),ut=Co==="detached",de=Co==="welded";t.classList.toggle("persona-artifact-detached-split",ut),t.classList.toggle("persona-artifact-welded-split",de);let Ct="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",ot=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&yl(o)&&y&&!i;t.classList.toggle("persona-artifact-chat-flush",ot);let Ve=ut||ot?"none":yt,Ze=ut?Bt:de?"none":xt,kt=ut?Oe:_t;ot&&(Ze="none",kt="0");let He=L?.borderRadius!=null&&L.borderRadius!=="",et=ot&&!He?"0":_t,nn=ie.scrollTop;t.style.cssText="",ke.style.cssText="",me.style.cssText="",pe.style.cssText="",ie.style.cssText="",j.style.cssText="",Pe&&(ie.style.display="none");let Ao=()=>{if(nn<=0)return;(ie.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ie.scrollTop===nn)return;let Jt=ie.scrollHeight-ie.clientHeight;Jt<=0||(ie.scrollTop=Math.min(nn,Jt))})};if(we){ke.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"),ke.style.cssText=`
|
|
35
47
|
position: fixed !important;
|
|
36
48
|
inset: 0 !important;
|
|
37
49
|
width: 100% !important;
|
|
@@ -41,9 +53,9 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
41
53
|
padding: 0 !important;
|
|
42
54
|
display: flex !important;
|
|
43
55
|
flex-direction: column !important;
|
|
44
|
-
z-index: ${
|
|
56
|
+
z-index: ${jt} !important;
|
|
45
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
46
|
-
`,
|
|
58
|
+
`,me.style.cssText=`
|
|
47
59
|
position: relative !important;
|
|
48
60
|
display: flex !important;
|
|
49
61
|
flex-direction: column !important;
|
|
@@ -56,7 +68,7 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
56
68
|
padding: 0 !important;
|
|
57
69
|
box-shadow: none !important;
|
|
58
70
|
border-radius: 0 !important;
|
|
59
|
-
`,
|
|
71
|
+
`,pe.style.cssText=`
|
|
60
72
|
display: flex !important;
|
|
61
73
|
flex-direction: column !important;
|
|
62
74
|
flex: 1 1 0% !important;
|
|
@@ -67,20 +79,33 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
67
79
|
overflow: hidden !important;
|
|
68
80
|
border-radius: 0 !important;
|
|
69
81
|
border: none !important;
|
|
70
|
-
`,
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
`,ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0",V=!0,Ao();return}let Vs=o?.launcher?.width??o?.launcherWidth??On;if(!g&&!i)y&&h?(me.style.width="100%",me.style.maxWidth="100%"):(me.style.width=Vs,me.style.maxWidth=Vs);else if(i)if(fn(o).reveal==="emerge"&&!A){let Jt=fn(o).width;me.style.width=Jt,me.style.maxWidth=Jt}else me.style.width="100%",me.style.maxWidth="100%";if(Is(),me.style.boxShadow=Ve,me.style.borderRadius=et,ut?me.style.border="none":de&&(me.style.border=xt),pe.style.border=Ze,pe.style.borderRadius=kt,pe.style.boxShadow=ut&&!ot?Ct:"",ot&&(pe.style.background="transparent",ie.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),de){let Lt=o.features?.artifacts?.layout;Ms=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||_t}else Ms=null;if(i&&!we&&!Ae&&!ut&&!de&&L?.border===void 0&&(pe.style.border="none",fn(o).side==="right"?pe.style.borderLeft="1px solid var(--persona-border)":pe.style.borderRight="1px solid var(--persona-border)"),i&&!we&&de&&L?.border===void 0&&(fn(o).side==="right"?me.style.borderLeft="1px solid var(--persona-border)":me.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",y&&(t.style.width="100%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",y&&(ke.style.overflow="hidden"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",ut||(me.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.overflow="hidden",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.overflowY="auto",j.style.flexShrink="0"),y&&(Ae||ut||ot)&&!i&&(ot||(ke.style.padding="var(--persona-panel-inset)"),ke.style.background="var(--persona-panel-canvas-bg)"),ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!y&&!i&&(xn[ht]??xn["bottom-right"]).split(" ").forEach(Jt=>ke.classList.add(Jt)),g){let Lt=o.launcher?.sidebarWidth??"420px";A?ke.style.cssText=`
|
|
83
|
+
position: fixed !important;
|
|
84
|
+
top: var(--persona-panel-inset) !important;
|
|
85
|
+
bottom: var(--persona-panel-inset) !important;
|
|
86
|
+
width: ${Lt} !important;
|
|
87
|
+
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
|
+
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
89
|
+
margin: 0 !important;
|
|
90
|
+
padding: 0 !important;
|
|
91
|
+
display: flex !important;
|
|
92
|
+
flex-direction: column !important;
|
|
93
|
+
z-index: ${jt} !important;
|
|
94
|
+
${st?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
+
`:ke.style.cssText=`
|
|
96
|
+
position: fixed !important;
|
|
97
|
+
top: 0 !important;
|
|
98
|
+
bottom: 0 !important;
|
|
99
|
+
width: ${Lt} !important;
|
|
100
|
+
height: 100vh !important;
|
|
101
|
+
max-height: 100vh !important;
|
|
102
|
+
margin: 0 !important;
|
|
103
|
+
padding: 0 !important;
|
|
104
|
+
display: flex !important;
|
|
105
|
+
flex-direction: column !important;
|
|
106
|
+
z-index: ${jt} !important;
|
|
107
|
+
${st?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
|
+
`,me.style.cssText=`
|
|
84
109
|
position: relative !important;
|
|
85
110
|
display: flex !important;
|
|
86
111
|
flex-direction: column !important;
|
|
@@ -91,9 +116,10 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
91
116
|
min-height: 0 !important;
|
|
92
117
|
margin: 0 !important;
|
|
93
118
|
padding: 0 !important;
|
|
94
|
-
box-shadow: ${
|
|
95
|
-
border-radius: ${
|
|
96
|
-
|
|
119
|
+
box-shadow: ${Ve} !important;
|
|
120
|
+
border-radius: ${et} !important;
|
|
121
|
+
${ut?"border: none !important;":de?`border: ${xt} !important;`:""}
|
|
122
|
+
`,me.style.setProperty("width","100%","important"),me.style.setProperty("max-width","100%","important"),pe.style.cssText=`
|
|
97
123
|
display: flex !important;
|
|
98
124
|
flex-direction: column !important;
|
|
99
125
|
flex: 1 1 0% !important;
|
|
@@ -102,15 +128,18 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
102
128
|
min-height: 0 !important;
|
|
103
129
|
max-height: 100% !important;
|
|
104
130
|
overflow: hidden !important;
|
|
105
|
-
border-radius: ${
|
|
106
|
-
border: ${
|
|
107
|
-
|
|
131
|
+
border-radius: ${kt} !important;
|
|
132
|
+
border: ${Ze} !important;
|
|
133
|
+
${ut&&!ot?`box-shadow: ${Ct} !important;`:""}
|
|
134
|
+
${ot?"background: transparent !important;":""}
|
|
135
|
+
`,j.style.cssText=`
|
|
108
136
|
flex-shrink: 0 !important;
|
|
109
137
|
border-top: none !important;
|
|
110
138
|
padding: 8px 16px 12px 16px !important;
|
|
111
|
-
`}if(!y&&!i){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Dt=p?"":"padding-top: 1.25em !important;",Vt=p?"":`z-index: ${(Ze=(Do=r.launcher)==null?void 0:Do.zIndex)!=null?Ze:wn} !important;`;ue.style.cssText+=Nt+Dt+Vt}Ge()};ro(),bs(n,r),li(n,r),ci(n,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",Dr)}),lt.push(()=>{sr!==null&&clearTimeout(sr)});let tn=null,nn=null;lt.push(()=>{tn==null||tn(),tn=null,nn==null||nn(),nn=null}),Dn&<.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Qn==null||Qn(),Qn=null,Xo(),Ot&&(Ot.remove(),Ot=null),wt==null||wt.element.style.removeProperty("width"),wt==null||wt.element.style.removeProperty("maxWidth")}),ae&<.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),Ae==null||Ae.destroy(),Ae=null,V==null||V.destroy(),V=null,Ce=null});let Cr=null,ks=()=>{Cr&&(Cr(),Cr=null),r.colorScheme==="auto"&&(Cr=mm(()=>{bs(n,r)}))};ks(),lt.push(()=>{Cr&&(Cr(),Cr=null)}),lt.push(a);let Fr=(Vc=r.features)==null?void 0:Vc.streamAnimation;if(Fr!=null&&Fr.type&&Fr.type!=="none"){let i=vs(Fr.type,Fr.plugins);i&&(Ga(i,n),lt.push(()=>Mm(n)))}let Eo=Vm(qt),Ar=null,O,Jo=i=>{var y,C;if(!O)return;let p=i!=null?i:O.getMessages(),f=((C=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:C.enabled)!==!1?Fu(p):null;f?Eo.render(f,O,ye,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(E=>E.role==="user")?Eo.render([],O,ye,p):Eo.render(r.suggestionChips,O,ye,p,r.suggestionChipsConfig)},Xn=!1,Sr=ym(),Or=new Map,Tr=new Map,ir=new Map,Yo=0,ga=Oo()!==null,yn=Ua(),Sn=0,lr=null,Tn=!1,ko=!1,cr=0,bn=null,Mr=null,Zo=!1,Lo=!1,es=null,oo=!0,so=!1,ot=null,x=4,j=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},De=(Gc=(Kc=r.voiceRecognition)==null?void 0:Kc.autoResume)!=null?Gc:!1,nt=i=>{l.emit("voice:state",{active:K.active,source:i,timestamp:Date.now()})},ct=()=>{w(i=>({...i,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},ui=()=>{var y,C;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let i=hl(u.voiceState),p=!!i.active,f=Number((C=i.timestamp)!=null?C:0);K.manuallyDeactivated=!!i.manuallyDeactivated,p&&Date.now()-f<lw&&setTimeout(()=>{var E,_;K.active||(K.manuallyDeactivated=!1,((_=(E=r.voiceRecognition)==null?void 0:E.provider)==null?void 0:_.type)==="runtype"?O.toggleVoice().then(()=>{K.active=O.isVoiceActive(),nt("restore"),O.isVoiceActive()&&os()}):ya("restore"))},1e3)},ao=()=>O?gg(O.getMessages()).filter(i=>!i.__skipPersist):[],Mn=null,cn=(i,p)=>{typeof console!="undefined"&&console.error(i,p)},_r=(i,p)=>{let f=()=>{try{let _=i();return!_||typeof _.then!="function"?null:Promise.resolve(_).catch(N=>{cn(p,N)})}catch(_){return cn(p,_),null}},y=Mn,C=y?y.then(()=>{var _;return(_=f())!=null?_:void 0}):f();if(!C)return;let E=C.finally(()=>{Mn===E&&(Mn=null)});Mn=E};function Er(i){if(!(c!=null&&c.save))return;let f={messages:i?gg(i):O?ao():[],metadata:u,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};_r(()=>c.save(f),"[AgentWidget] Failed to persist state:")}let rn=null,En=()=>ue.querySelector("#persona-scroll-container")||we,un=()=>{rn!==null&&(cancelAnimationFrame(rn),rn=null),Tn=!1},Al=()=>{lr!==null&&(cancelAnimationFrame(lr),lr=null),ko=!1,un()},kg=()=>Xn&&gi()&&(Ft()!=="anchor-top"||rr()),mi=()=>{let i=vt()||"Jump to latest",p=kg();jt.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),cr>0?(Hn.textContent=String(cr),Hn.style.display="",jt.setAttribute("aria-label",`${i} (${cr} new)`)):(Hn.textContent="",Hn.style.display="none",jt.setAttribute("aria-label",p?`${i} (response streaming below)`:i))},Sl=()=>{cr!==0&&(cr=0,mi())},gi=()=>Yt()?!yn.isFollowing():!vo(we,j),On=()=>{if(!Qt()||J){jt.parentNode&&jt.remove(),jt.style.display="none";return}jt.parentNode!==Te&&Te.appendChild(jt),jn();let p=Ir(we)>0&&gi();p?mi():Sl(),jt.style.display=p?"":"none"},Ls=()=>{yn.pause()&&(Al(),On())},io=()=>{yn.resume(),Sl(),On()},lo=(i=!1)=>{Yt()&&yn.isFollowing()&&(!i&&!Xn||(lr!==null&&(cancelAnimationFrame(lr),lr=null),ko=!0,lr=requestAnimationFrame(()=>{lr=null,ko=!1,yn.isFollowing()&&Lg(En(),i?220:140)})))},Tl=(i,p,f,y=()=>!0)=>{let C=i.scrollTop,E=p(),_=E-C;if(un(),Math.abs(_)<1){Tn=!0,i.scrollTop=E,Sn=i.scrollTop,Tn=!1;return}let N=performance.now();Tn=!0;let D=oe=>1-Math.pow(1-oe,3),se=oe=>{if(!y()){un();return}let Z=p();Z!==E&&(E=Z,_=E-C);let ve=oe-N,Ne=Math.min(ve/f,1),Fe=D(Ne),$e=C+_*Fe;i.scrollTop=$e,Sn=i.scrollTop,Ne<1?rn=requestAnimationFrame(se):(i.scrollTop=E,Sn=i.scrollTop,rn=null,Tn=!1)};rn=requestAnimationFrame(se)},Lg=(i,p=500)=>{let f=Ir(i)-i.scrollTop;if(Math.abs(f)<1){Sn=i.scrollTop;return}if(Math.abs(f)>=q){un(),Tn=!0,i.scrollTop=Ir(i),Sn=i.scrollTop,Tn=!1;return}Tl(i,()=>Ir(i),p,()=>yn.isFollowing())},Ml=()=>{let i=En();Tn=!0,i.scrollTop=Ir(i),Sn=i.scrollTop,Tn=!1,On()},El=i=>{let p=0,f=i;for(;f&&f!==we;)p+=f.offsetTop,f=f.offsetParent;return p},kl=()=>{var E;if(Wr()!=="last-user-turn")return!1;let i=(E=O==null?void 0:O.getMessages())!=null?E:[];if(i.length<2)return!1;let p=[...i].reverse().find(_=>_.role==="user");if(!p)return!1;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=we.querySelector(`[data-message-id="${f}"]`);if(!y)return!1;let C=Math.min(Math.max(0,El(y)-hr()),Ir(we));return Tn=!0,we.scrollTop=C,Sn=we.scrollTop,Tn=!1,Ft()==="follow"&&!vo(we,j)&&yn.pause(),On(),!0},Ll=i=>{Pn.style.height=`${Math.max(0,Math.round(i))}px`,bn&&(bn.spacerHeight=Math.max(0,i))},Ps=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),un(),bn=null,Pn.style.height="0px"},Pg=i=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var D;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=we.querySelector(`[data-message-id="${p}"]`);if(!f)return;let y=El(f),C=(D=bn==null?void 0:bn.spacerHeight)!=null?D:0,E=we.scrollHeight-C,{targetScrollTop:_,spacerHeight:N}=Cm({anchorOffsetTop:y,topOffset:hr(),viewportHeight:we.clientHeight,contentHeight:E});bn={initialSpacerHeight:N,contentHeightAtAnchor:E,spacerHeight:N},Ll(N),Tl(we,()=>_,220)})},Ig=()=>{if(Yt()){if(!yn.isFollowing()||vo(we,1))return;lo(!Xn);return}if(bn&&bn.initialSpacerHeight>0){let i=we.scrollHeight-bn.spacerHeight,p=Am({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:i});p!==bn.spacerHeight&&Ll(p)}On()},Wg=i=>{let p=Ft();p==="follow"?(io(),lo(!0)):p==="anchor-top"&&(oo=!1,so=!0,Pg(i))},Rg=()=>{if(Ft()==="anchor-top"){if(so){oo=!1;return}oo=!0,Ps(),io(),lo(!0)}},Hg=i=>{let p=new Map;i.forEach(f=>{let y=G.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!y&&f.role==="assistant"&&(l.emit("assistant:message",f),!Lo&&(Ft()!=="anchor-top"||rr())&&gi()&&(cr+=1,mi(),On(),Xr(cr===1?"1 new message below.":`${cr} new messages below.`))),f.role==="assistant"&&(y!=null&&y.streaming)&&f.streaming===!1&&l.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(y?f.approval.status!=="pending"&&l.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):l.emit("approval:requested",{approval:f.approval,message:f}))}),G.clear(),p.forEach((f,y)=>{G.set(y,f)})},Bg=(i,p,f)=>{var st,He,Ie,qe,Ge,bt;let y=document.createElement("div"),E=(()=>{var Be;let L=o.find(We=>We.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),_=(L,Be)=>Be==null?!1:typeof Be=="string"?(L.textContent=Be,!0):(L.appendChild(Be),!0),N=new Set,D=new Set,se=o.some(L=>L.renderAskUserQuestion),oe=[],Z=[],ve=r.enableComponentStreaming!==!1,Ne=r.approval!==!1,Fe=[];if(p.forEach(L=>{var mn,_n,Ve,It,$n,Io,Wo,Ro,Ho,as,is,Gt,Bo,uo,mo,qr,Do;N.add(L.id);let Be=se&&_o(L),We=Ne&&L.variant==="approval"&&!!L.approval,Xe=!Be&&L.role==="assistant"&&!L.variant&&ve&&fl(L);if(!We&&ir.has(L.id)){let Ze=i.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),ir.delete(L.id)}if(!Xe&&Tr.has(L.id)){let Ze=i.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Tr.delete(L.id)}let Pt=_o(L)?`:${(mn=L.agentMetadata)!=null&&mn.askUserQuestionAnswered?"a":"u"}:${(_n=L.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Oe=hm(L,Yo)+Pt,Kt=Be||We||Xe?null:bm(Sr,L.id,Oe);if(Kt){y.appendChild(Kt.cloneNode(!0)),_o(L)&&((Ve=L.toolCall)!=null&&Ve.id)&&((It=L.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=L.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(L.toolCall.id),Ma(L,r,je.composerOverlay));return}let xt=null,sn=o.find(Ze=>!!(L.variant==="reasoning"&&Ze.renderReasoning||L.variant==="tool"&&Ze.renderToolCall||!L.variant&&Ze.renderMessage)),Wn=(Io=r.layout)==null?void 0:Io.messages;if(_o(L)&&((Wo=L.agentMetadata)==null?void 0:Wo.askUserQuestionAnswered)===!0){Or.delete(L.id);let Ze=i.querySelector(`#wrapper-${L.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Ni(L)&&((Ho=(Ro=r.features)==null?void 0:Ro.suggestReplies)==null?void 0:Ho.enabled)!==!1)return;if(_o(L)&&((is=(as=r.features)==null?void 0:as.askUserQuestion)==null?void 0:is.enabled)!==!1){let Ze=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(Ze&&St.current){let Nt=Or.get(L.id),Dt=Nt!==Oe,Vt=null;if(Dt){let{payload:Ut,complete:gn}=ps(L),Un=L.id,Lr=()=>{var dn;return(dn=St.current)==null?void 0:dn.getMessages().find(pn=>pn.id===Un)};Vt=Ze.renderAskUserQuestion({message:L,payload:Ut,complete:gn,resolve:dn=>{var Zn;let pn=Lr();pn&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(pn,dn))},dismiss:()=>{var pn,Zn,go;let dn=Lr();(pn=dn==null?void 0:dn.agentMetadata)!=null&&pn.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(dn),(go=St.current)==null||go.resolveAskUserQuestion(dn,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Dt&&Vt===null&&!$t){((Gt=L.agentMetadata)==null?void 0:Gt.awaitingLocalTool)===!0&&!((Bo=L.agentMetadata)!=null&&Bo.askUserQuestionAnswered)&&(D.add(L.toolCall.id),Ma(L,r,je.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${L.id}`,mt.setAttribute("data-wrapper-id",L.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),y.appendChild(mt),oe.push({messageId:L.id,fingerprint:Oe,bubble:Vt});return}else{((uo=L.agentMetadata)==null?void 0:uo.awaitingLocalTool)===!0&&!((mo=L.agentMetadata)!=null&&mo.askUserQuestionAnswered)&&(D.add(L.toolCall.id),Ma(L,r,je.composerOverlay));return}}else if(We){let Ze=(qr=o.find($t=>typeof $t.renderApproval=="function"))!=null?qr:s,Dt=ir.get(L.id)!==Oe,Vt=null;if(Dt&&(Ze!=null&&Ze.renderApproval)){let $t=L.id,mt=(Ut,gn)=>{var Lr,dn,pn;let Un=(Lr=St.current)==null?void 0:Lr.getMessages().find(Zn=>Zn.id===$t);Un!=null&&Un.approval&&(Un.approval.toolType==="webmcp"?(dn=St.current)==null||dn.resolveWebMcpApproval(Un.id,Ut):(pn=St.current)==null||pn.resolveApproval(Un.approval,Ut,gn))};Vt=Ze.renderApproval({message:L,defaultRenderer:()=>ai(L,r),config:r,approve:Ut=>mt("approved",Ut),deny:Ut=>mt("denied",Ut)})}if(Dt&&Vt===null){let $t=i.querySelector(`#wrapper-${L.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),ir.delete(L.id),xt=ai(L,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${L.id}`,$t.setAttribute("data-wrapper-id",L.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),y.appendChild($t),Fe.push({messageId:L.id,fingerprint:Oe,bubble:Vt});return}}else if(sn)if(L.variant==="reasoning"&&L.reasoning&&sn.renderReasoning){if(!Le)return;xt=sn.renderReasoning({message:L,defaultRenderer:()=>nl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&sn.renderToolCall){if(!Pe)return;xt=sn.renderToolCall({message:L,defaultRenderer:()=>ol(L,r),config:r})}else sn.renderMessage&&(xt=sn.renderMessage({message:L,defaultRenderer:()=>{let Ze=tl(L,f,Wn,r.messageActions,Je,{loadingIndicatorRenderer:E,widgetConfig:r});return L.role!=="user"&&cl(Ze,L,r,O),Ze},config:r}));if(!xt&&Xe){let Ze=pg(L);if(Ze){let Nt=Tr.get(L.id),Dt=Nt!==Oe,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Dt){let mt=cg(Ze,{config:r,message:L,transform:f});if(mt)if(Vt){let Ut=document.createElement("div");if(Ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=f({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(gn)}Ut.appendChild(mt),$t=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${L.id}`,Ut.setAttribute("data-message-id",L.id),Ut.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=f({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Ut.appendChild(gn)}Ut.appendChild(mt),$t=Ut}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${L.id}`,mt.setAttribute("data-wrapper-id",L.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),y.appendChild(mt),Z.push({messageId:L.id,fingerprint:Oe,bubble:$t});return}}}if(!xt)if(L.variant==="reasoning"&&L.reasoning){if(!Le)return;xt=nl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!Pe)return;xt=ol(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;xt=ai(L,r)}else{let Ze=(Do=r.layout)==null?void 0:Do.messages;Ze!=null&&Ze.renderUserMessage&&L.role==="user"?xt=Ze.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):Ze!=null&&Ze.renderAssistantMessage&&L.role==="assistant"?xt=Ze.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):xt=tl(L,f,Ze,r.messageActions,Je,{loadingIndicatorRenderer:E,widgetConfig:r}),L.role!=="user"&&xt&&cl(xt,L,r,O)}let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-${L.id}`,Bt.setAttribute("data-wrapper-id",L.id),L.role==="user"&&Bt.classList.add("persona-justify-end"),(xt==null?void 0:xt.getAttribute("data-persona-component-directive"))==="true"&&Bt.classList.add("persona-w-full"),Bt.appendChild(xt),vm(Sr,L.id,Oe,Bt),y.appendChild(Bt)}),je.composerOverlay&&je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let We=Be.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&ms(je.composerOverlay,We)}),(He=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&He.grouped){let L=[],Be=[];p.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){Be.push(We);return}Be.length>1&&L.push(Be),Be=[]}),Be.length>1&&L.push(Be),L.forEach((We,Xe)=>{var mn,_n;let Pt=We.map(Ve=>Array.from(y.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ve.id)).filter(Ve=>!!Ve);if(Pt.length<2)return;let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id=`wrapper-tool-group-${Xe}-${We[0].id}`,Oe.setAttribute("data-wrapper-id",`tool-group-${Xe}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${We.length} tools`,Wn=(_n=(mn=r.toolCall)==null?void 0:mn.renderGroupedSummary)==null?void 0:_n.call(mn,{messages:We,toolCalls:We.map(Ve=>Ve.toolCall).filter(Ve=>!!Ve),defaultSummary:sn,config:r});_(xt,Wn)||(xt.textContent=sn);let Bt=document.createElement("div");Bt.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(xt,Bt),Oe.appendChild(Kt),Pt[0].before(Oe),Pt.forEach((Ve,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ve),Bt.appendChild($n)})})}wm(Sr,N);let $e=p.some(L=>L.role==="assistant"&&L.streaming),ze=p[p.length-1],ut=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Xn&&p.some(L=>L.role==="user")&&!$e&&!ut){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:la},Be=o.find(Xe=>Xe.renderLoadingIndicator),We=null;if(Be!=null&&Be.renderLoadingIndicator&&(We=Be.renderLoadingIndicator(L)),We===null&&((Ie=r.loadingIndicator)!=null&&Ie.render)&&(We=r.loadingIndicator.render(L)),We===null&&(We=la()),We){let Xe=document.createElement("div"),Pt=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;Xe.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Xe.setAttribute("data-typing-indicator","true"),Xe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Xe.appendChild(We);let Oe=document.createElement("div");Oe.className="persona-flex",Oe.id="wrapper-typing-indicator",Oe.setAttribute("data-wrapper-id","typing-indicator"),Oe.appendChild(Xe),y.appendChild(Oe)}}if(!Xn&&p.length>0){let L=p[p.length-1],Be={config:r,lastMessage:L,messageCount:p.length},We=o.find(Pt=>Pt.renderIdleIndicator),Xe=null;if(We!=null&&We.renderIdleIndicator&&(Xe=We.renderIdleIndicator(Be)),Xe===null&&((Ge=r.loadingIndicator)!=null&&Ge.renderIdle)&&(Xe=r.loadingIndicator.renderIdle(Be)),Xe){let Pt=document.createElement("div"),Oe=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.className=Oe?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Xe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),y.appendChild(Kt)}}if(_a(i,y),oe.length>0)for(let{messageId:L,fingerprint:Be,bubble:We}of oe){let Xe=i.querySelector(`#wrapper-${L}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),Or.set(L,Be))}if(Or.size>0)for(let L of Or.keys())N.has(L)||Or.delete(L);if(Z.length>0)for(let{messageId:L,fingerprint:Be,bubble:We}of Z){let Xe=i.querySelector(`#wrapper-${L}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),Tr.set(L,Be))}if(Tr.size>0)for(let L of Tr.keys())N.has(L)||Tr.delete(L);if(Fe.length>0)for(let{messageId:L,fingerprint:Be,bubble:We}of Fe){let Xe=i.querySelector(`#wrapper-${L}`);Xe&&We!==null&&(Xe.replaceChildren(We),Xe.setAttribute("data-bubble-fp",Be),ir.set(L,Be))}if(ir.size>0)for(let L of ir.keys())N.has(L)||ir.delete(L)},Is=(i,p,f)=>{Bg(i,p,f),to()},Ws=null,Dg=()=>{var f;if(Ws)return;let i=y=>{let C=y.composedPath();C.includes(ue)||it&&C.includes(it)||_t(!1,"user")};Ws=i,((f=n.ownerDocument)!=null?f:document).addEventListener("pointerdown",i,!0)},Pl=()=>{var p;if(!Ws)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",Ws,!0),Ws=null};lt.push(()=>Pl());let Rs=null,Ng=()=>{var f;if(Rs)return;let i=y=>{y.key==="Escape"&&(y.isComposing||_t(!1,"user"))};Rs=i,((f=n.ownerDocument)!=null?f:document).addEventListener("keydown",i,!0)},Il=()=>{var p;if(!Rs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",Rs,!0),Rs=null};lt.push(()=>Il());let Hs=!1,Wl=new Set,Fg=()=>{var p,f,y,C;let i=(y=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.peek)==null?void 0:y.streamAnimation;return i||((C=r.features)==null?void 0:C.streamAnimation)},ts=()=>{var ut,st,He,Ie;if(!k())return;let i=je.peekBanner,p=je.peekTextNode;if(!i||!p)return;if(F){i.classList.remove("persona-pill-peek--visible");return}let f=(ut=O==null?void 0:O.getMessages())!=null?ut:[],y;for(let qe=f.length-1;qe>=0;qe--){let Ge=f[qe];if(Ge.role==="assistant"&&Ge.content){y=Ge;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let C=y.content,E=!!y.streaming,_=Fg(),N=ja(_),D=N.type!=="none"?vs(N.type,_==null?void 0:_.plugins):null,se=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,y))===!0,oe=D!==null&&(E||se);oe&&D&&!Wl.has(D.name)&&(Ga(D,n),Wl.add(D.name));let Z=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(He=p.dataset.personaPeekStreamClass)!=null?He:null;ve&&ve!==Z&&(p.classList.remove(ve),delete p.dataset.personaPeekStreamClass),Z&&ve!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),oe?(p.style.setProperty("--persona-stream-step",`${N.speed}ms`),p.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=oe?Va(C,N.buffer,D,y,E):C;if(oe&&N.placeholder==="skeleton"&&E&&(!Ne||!Ne.trim())){let qe=document.createElement("div"),Ge=ra();Ge.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ge),_a(p,qe)}else{let qe=Math.max(0,Ne.length-100),Ge=Ne.length>100?Ne.slice(-100):Ne,bt=fo(Ge);if(!oe||!D){let L=Ne.length>100?`\u2026${Ge}`:Ge;p.textContent!==L&&(p.textContent=L)}else{let L=bt;(D.wrap==="char"||D.wrap==="word")&&(L=na(bt,D.wrap,`peek-${y.id}`,{skipTags:D.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=L,D.useCaret&&Ge.length>0){let We=Ka(),Xe=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Xe[Xe.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):Be.appendChild(We)}_a(p,Be),(Ie=D.onAfterRender)==null||Ie.call(D,{container:p,bubble:i,messageId:y.id,message:y,speed:N.speed,duration:N.duration})}}let ze=Xn||Hs;i.classList.toggle("persona-pill-peek--visible",ze)};if(k()){let i=je.peekBanner;if(i){let y=C=>{C.preventDefault(),C.stopPropagation(),_t(!0,"user")};i.addEventListener("pointerdown",y),lt.push(()=>{i.removeEventListener("pointerdown",y)})}let p=()=>{Hs||(Hs=!0,ts())},f=()=>{Hs&&(Hs=!1,ts())};Q.addEventListener("pointerenter",p),Q.addEventListener("pointerleave",f),lt.push(()=>{Q.removeEventListener("pointerenter",p),Q.removeEventListener("pointerleave",f)}),it&&(it.addEventListener("pointerenter",p),it.addEventListener("pointerleave",f),lt.push(()=>{it.removeEventListener("pointerenter",p),it.removeEventListener("pointerleave",f)}))}let Og=i=>{var ve,Ne,Fe,$e,ze,ut,st,He;let p=(Ne=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Ne:{},f=(Fe=p.expandedSize)!=null?Fe:"anchored",y=($e=p.bottomOffset)!=null?$e:"16px",C=p.collapsedMaxWidth,E=(ze=p.expandedMaxWidth)!=null?ze:"880px",_=(ut=p.expandedTopOffset)!=null?ut:"5vh",N=(st=p.modalMaxWidth)!=null?st:"880px",D=(He=p.modalMaxHeight)!=null?He:"min(90vh, 800px)",se="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Z=ue.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",it){let Ie=it.style;Ie.bottom=y,Ie.width=C!=null?C:""}if(i&&f!=="fullscreen"){if(f==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=N,Z.maxWidth=se,Z.maxHeight=D,Z.height=D;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${oe})`,Z.top=_,Z.width=E,Z.maxWidth=se}},Bs=()=>{var D,se,oe,Z,ve,Ne,Fe,$e;if(!U())return;if(k()){let ut=(oe=((se=(D=r.launcher)==null?void 0:D.composerBar)!=null?se:{}).expandedSize)!=null?oe:"anchored",st=F?"expanded":"collapsed";ue.dataset.state=st,ue.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ue.style.removeProperty("display"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Og(F),Te.style.display=F?"flex":"none",ro(),F?(Dg(),Ng()):(Pl(),Il()),ts();return}let i=fn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,f=(Ne=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Ne:640,y=($e=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?$e:!0,C=p.innerWidth<=f,E=y&&C&&I,_=ur(r).reveal;F?(ue.style.removeProperty("display"),ue.style.display=i?"flex":"",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),Jt?Jt.element.style.display="none":on&&(on.style.display="none")):(i?i&&(_==="overlay"||_==="push")&&!E?(ue.style.removeProperty("display"),ue.style.display="flex",ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.setProperty("display","none","important"),ue.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ue.style.display="",ue.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),Jt?Jt.element.style.display=i?"none":"":on&&(on.style.display=i?"none":""))},_t=(i,p="user")=>{var E,_;if(!U()||F===i)return;let f=F;F=i,Bs();let y=(()=>{var Fe,$e,ze,ut,st,He,Ie,qe,Ge,bt;let N=($e=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?$e:!1,D=(ze=n.ownerDocument.defaultView)!=null?ze:window,se=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Ie=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?Ie:640,Z=D.innerWidth<=oe,ve=fn(r)&&se&&Z,Ne=k()&&((bt=(Ge=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ge.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return N||se&&Z&&I||ve||Ne})();if(F&&y){if(!tn){let N=n.getRootNode(),D=N instanceof ShadowRoot?N.host:n.closest(".persona-host");D&&(tn=Gi(D,(_=(E=r.launcher)==null?void 0:E.zIndex)!=null?_:wn))}nn||(nn=Qi(n.ownerDocument))}else F||(tn==null||tn(),tn=null,nn==null||nn(),nn=null);F&&(Ds(),kl()||(Ft()==="follow"?lo(!0):Ml()));let C={open:F,source:p,timestamp:Date.now()};F&&!f?l.emit("widget:opened",C):!F&&f&&l.emit("widget:closed",C),l.emit("widget:state",{open:F,launcherEnabled:I,voiceActive:K.active,streaming:O.isStreaming()})},fi=i=>{ge(i?"stop":"send"),H&&(H.disabled=i),Eo.buttons.forEach(p=>{p.disabled=i}),Re.dataset.personaComposerStreaming=i?"true":"false",Re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=i)})},hi=()=>{K.active||ye&&ye.focus()};l.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>hi(),200)});let Rl=()=>{var f,y,C,E,_,N,D,se,oe,Z,ve;gr.textContent=(y=(f=r.copy)==null?void 0:f.welcomeTitle)!=null?y:"Hello \u{1F44B}",fr.textContent=(E=(C=r.copy)==null?void 0:C.welcomeSubtitle)!=null?E:"Ask anything about your account or products.",ye.placeholder=(N=(_=r.copy)==null?void 0:_.inputPlaceholder)!=null?N:"How can I help...";let i=we.querySelector("[data-persona-intro-card]");if(i){let Ne=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;i.style.display=Ne?"":"none",Ne?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&oe)&&!(O!=null&&O.isStreaming())&&(pe.textContent=(ve=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?ve:"Send"),ye.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ye.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{w(p=>({...p,sessionId:i}))}});let Po=null,_g=()=>{Po==null&&(Po=setInterval(()=>{let i=Ye.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Po),Po=null;return}let p=Date.now();i.forEach(f=>{let y=Number(f.getAttribute("data-tool-elapsed"));y&&(f.textContent=La(p-y))})},100))},yi=(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((_,N)=>yi(_,p[N]));let f=i,y=p,C=Object.keys(f),E=Object.keys(y);return C.length===E.length&&C.every(_=>Object.prototype.hasOwnProperty.call(y,_)&&yi(f[_],y[_]))},Hl=i=>{let{content:p,rawContent:f,llmContent:y,...C}=i;return C},bi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!fl(i),$g=(i,p,f)=>{if(i.length!==p.length)return!1;let y=i[f.index],C=p[f.index];return!y||!C||y.id!==f.id||C.id!==f.id?!1:(!Object.is(y.content,C.content)||!Object.is(y.rawContent,C.rawContent)||!Object.is(y.llmContent,C.llmContent))&&bi(y)&&bi(C)&&yi(Hl(y),Hl(C))},Bl=null,ns=null,$r=null,Ur=null,fa=i=>{var C,E;Bl=i;let p,f;ns=null;for(let _=i.length-1;_>=0;_-=1){let N=i[_];if(!p&&N.role==="user"&&(p=N),!f&&N.role==="assistant"&&(f=N),!ns&&bi(N)&&(ns={index:_,id:N.id}),p&&f&&ns)break}Is(Ye,i,Y),_g(),Jo(i),lo(!Xn),Hg(i),i.length===0&&(Ps(),oo=!0,so=!1),!Zo||Lo?(Zo=!0,es=(C=p==null?void 0:p.id)!=null?C:null,ot=(E=f==null?void 0:f.id)!=null?E:null):p&&p.id!==es?(es=p.id,Wg(p.id)):f&&f.id!==ot&&Rg(),f&&(ot=f.id);let y=K.lastUserMessageId;p&&p.id!==y&&(K.lastUserMessageId=p.id,l.emit("user:message",p)),K.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Er(i),ts()},vi=()=>{Ur!==null&&(cancelAnimationFrame(Ur),Ur=null);let i=$r;$r=null,i&&fa(i)},Dl=()=>{Ur!==null&&cancelAnimationFrame(Ur),Ur=null,$r=null},Ug=i=>{let p=$r!=null?$r:Bl;if(Xn&&p&&ns&&$g(p,i,ns)){$r=i,Ur===null&&(Ur=requestAnimationFrame(()=>{Ur=null;let f=$r;$r=null,f&&fa(f)}));return}if(i.length===0){Dl(),fa(i);return}vi(),fa(i)};O=new Na(r,{onMessagesChanged(i){Ug(i)},onStatusChanged(i){var y;let p=(y=r.statusIndicator)!=null?y:{};ft(hn,(C=>{var E,_,N,D,se,oe;return C==="idle"?(E=p.idleText)!=null?E:en.idle:C==="connecting"?(_=p.connectingText)!=null?_:en.connecting:C==="connected"?(N=p.connectedText)!=null?N:en.connected:C==="error"?(D=p.errorText)!=null?D:en.error:C==="paused"?(se=p.pausedText)!=null?se:en.paused:C==="resuming"?(oe=p.resumingText)!=null?oe:en.resuming:en[C]})(i),p,i)},onStreamingChanged(i){i||((O==null?void 0:O.getMessages().length)===0?Dl():vi()),Xn=i,fi(i),O&&Is(Ye,O.getMessages(),Y),i||lo(!0),On(),Xr(i?"Responding\u2026":"Response complete."),ts()},onVoiceStatusChanged(i){var p,f;if(l.emit("voice:status",{status:i,timestamp:Date.now()}),((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype")switch(i){case"listening":zr(),os();break;case"processing":zr(),Kg();break;case"speaking":zr(),Gg();break;default:i==="idle"&&O.isBargeInActive()?(zr(),os(),H==null||H.setAttribute("aria-label","End voice session")):(K.active=!1,zr(),nt("system"),ct());break}},onArtifactsState(i){Nn=i,xr(),Er()},onReconnect(i){var y;let{executionId:p,lastEventId:f}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:p,after:f}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:p,after:f,attempt:(y=i.attempt)!=null?y:1}):l.emit("stream:resumed",{executionId:p,after:f})}}),St.current=O,lt.push(()=>O.cancel());let wi=null;if(O.onReadAloudChange((i,p)=>{var C;Zr=i,eo=p,to();let f=i!=null?i:wi;i&&(wi=i);let y=f&&(C=O.getMessages().find(E=>E.id===f))!=null?C:null;l.emit("message:read-aloud",{messageId:f,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(wi=null)}),Zo=!0,((Xc=(Qc=r.voiceRecognition)==null?void 0:Qc.provider)==null?void 0:Xc.type)==="runtype")try{O.setupVoice()}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}r.clientToken&&O.initClientSession().catch(i=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(V||r.onSSEEvent)&&O.setSSEEventCallback((i,p)=>{var f;(f=r.onSSEEvent)==null||f.call(r,i,p),X==null||X.processEvent(i,p),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(p)})});let Nl=()=>{r.resume&&typeof r.reconnectStream=="function"&&O.resumeFromHandle(r.resume)};g?g.then(i=>{var p,f,y;if(i){if(i.metadata&&(u=hl(i.metadata),T.syncFromMetadata()),(p=i.messages)!=null&&p.length){Lo=!0;try{O.hydrateMessages(i.messages)}finally{Lo=!1}}(f=i.artifacts)!=null&&f.length&&O.hydrateArtifacts(i.artifacts,(y=i.selectedArtifactId)!=null?y:null)}}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Nl()):Nl();let Fl=()=>{var p,f,y;!k()||F||!((y=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.expandOnSubmit)==null||y)||_t(!0,"auto")},Ol=i=>{var C;if(i.preventDefault(),O.isStreaming()){O.cancel(),X==null||X.reset(),Ae==null||Ae.update();return}let p=ye.value.trim(),f=(C=At==null?void 0:At.hasAttachments())!=null?C:!1;if(!p&&!f)return;Fl();let y;f&&(y=[],y.push(...At.getContentParts()),p&&y.push(_i(p))),ye.value="",ye.style.height="auto",ha(),O.sendMessage(p,{contentParts:y}),f&&At.clearAttachments()},zg=()=>{var i;return((i=r.features)==null?void 0:i.composerHistory)!==!1},xi={...$a},Ci=!1,ha=()=>{xi={...$a}},qg=()=>O.getMessages().filter(i=>i.role==="user").map(i=>{var p;return(p=i.content)!=null?p:""}).filter(i=>i.length>0),jg=i=>{if(!ye)return;Ci=!0,ye.value=i,ye.dispatchEvent(new Event("input",{bubbles:!0})),Ci=!1;let p=ye.value.length;ye.setSelectionRange(p,p)},_l=()=>{Ci||ha()},$l=i=>{if(ye){if(zg()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let p=ye.selectionStart===0&&ye.selectionEnd===0,f=fm({direction:i.key==="ArrowUp"?"up":"down",history:qg(),currentValue:ye.value,atStart:p,state:xi});if(xi=f.state,f.handled){i.preventDefault(),f.value!==void 0&&jg(f.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(O.isStreaming()){i.preventDefault();return}ha(),i.preventDefault(),pe.click()}}},Ul=i=>{i.key!=="Escape"||i.isComposing||O.isStreaming()&&i.composedPath().includes(Te)&&(O.cancel(),X==null||X.reset(),Ae==null||Ae.update(),ha(),i.preventDefault(),i.stopImmediatePropagation())},zl=async i=>{var f;if(((f=r.attachments)==null?void 0:f.enabled)!==!0||!At)return;let p=dw(i.clipboardData);p.length!==0&&(i.preventDefault(),await At.handleFiles(p))},Jn=null,kr=!1,rs=null,pt=null,ql=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ya=(i="user")=>{var E,_,N,D,se,oe,Z;if(kr||O.isStreaming())return;let p=ql();if(!p)return;Jn=new p;let y=(_=((E=r.voiceRecognition)!=null?E:{}).pauseDuration)!=null?_:2e3;Jn.continuous=!0,Jn.interimResults=!0,Jn.lang="en-US";let C=ye.value;Jn.onresult=ve=>{let Ne="",Fe="";for(let ze=0;ze<ve.results.length;ze++){let ut=ve.results[ze],st=ut[0].transcript;ut.isFinal?Ne+=st+" ":Fe=st}let $e=C+Ne+Fe;ye.value=$e,rs&&clearTimeout(rs),(Ne||Fe)&&(rs=window.setTimeout(()=>{let ze=ye.value.trim();ze&&Jn&&kr&&(co(),ye.value="",ye.style.height="auto",O.sendMessage(ze,{viaVoice:!0}))},y))},Jn.onerror=ve=>{ve.error!=="no-speech"&&co()},Jn.onend=()=>{if(kr){let ve=ye.value.trim();ve&&ve!==C.trim()&&(ye.value="",ye.style.height="auto",O.sendMessage(ve,{viaVoice:!0})),co()}};try{if(Jn.start(),kr=!0,K.active=!0,i!=="system"&&(K.manuallyDeactivated=!1),nt(i),ct(),H){let ve=(N=r.voiceRecognition)!=null?N:{};pt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Z=(oe=ve.iconSize)!=null?oe:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Ne=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,$e=ve.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let ze=H.querySelector("svg");ze&&ze.setAttribute("stroke",Fe)}$e&&(H.style.borderColor=$e),H.setAttribute("aria-label","Stop voice recognition")}}catch{co("system")}},co=(i="user")=>{if(kr){if(kr=!1,rs&&(clearTimeout(rs),rs=null),Jn){try{Jn.stop()}catch{}Jn=null}if(K.active=!1,nt(i),ct(),H){if(H.classList.remove("persona-voice-recording"),pt){H.style.backgroundColor=pt.backgroundColor,H.style.color=pt.color,H.style.borderColor=pt.borderColor;let p=H.querySelector("svg");p&&p.setAttribute("stroke",pt.color||"currentColor"),pt=null}H.setAttribute("aria-label","Start voice recognition")}}},Vg=(i,p)=>{var st,He,Ie,qe,Ge,bt,L,Be,We;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((st=i==null?void 0:i.provider)==null?void 0:st.type)==="runtype",C=((He=i==null?void 0:i.provider)==null?void 0:He.type)==="custom";if(!(f||y||C))return null;let _=v("div","persona-send-button-wrapper"),N=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let D=(Ie=i==null?void 0:i.iconName)!=null?Ie:"mic",se=(qe=p==null?void 0:p.size)!=null?qe:"40px",oe=(Ge=i==null?void 0:i.iconSize)!=null?Ge:se,Z=parseFloat(oe)||24,ve=(bt=i==null?void 0:i.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,Ne=(L=i==null?void 0:i.iconColor)!=null?L:p==null?void 0:p.textColor;N.style.width=oe,N.style.height=oe,N.style.minWidth=oe,N.style.minHeight=oe,N.style.fontSize="18px",N.style.lineHeight="1",Ne?N.style.color=Ne:N.style.color="var(--persona-text, #111827)";let $e=he(D,Z,Ne||"currentColor",1.5);$e?N.appendChild($e):N.textContent="\u{1F3A4}",ve?N.style.backgroundColor=ve:N.style.backgroundColor="",i!=null&&i.borderWidth&&(N.style.borderWidth=i.borderWidth,N.style.borderStyle="solid"),i!=null&&i.borderColor&&(N.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(N.style.paddingLeft=i.paddingX,N.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(N.style.paddingTop=i.paddingY,N.style.paddingBottom=i.paddingY),_.appendChild(N);let ze=(Be=i==null?void 0:i.tooltipText)!=null?Be:"Start voice recognition";if(((We=i==null?void 0:i.showTooltip)!=null?We:!1)&&ze){let Xe=v("div","persona-send-button-tooltip");Xe.textContent=ze,_.appendChild(Xe)}return{micButton:N,micButtonWrapper:_}},Ai=()=>{var p,f,y,C,E;if(!H||pt)return;let i=(p=r.voiceRecognition)!=null?p:{};pt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(f=i.iconName)!=null?f:"mic",iconSize:parseFloat((E=(C=i.iconSize)!=null?C:(y=r.sendButton)==null?void 0:y.size)!=null?E:"40")||24}},Si=(i,p)=>{var E,_,N,D,se;if(!H)return;let f=H.querySelector("svg");f&&f.remove();let y=(se=pt==null?void 0:pt.iconSize)!=null?se:parseFloat((D=(N=(E=r.voiceRecognition)==null?void 0:E.iconSize)!=null?N:(_=r.sendButton)==null?void 0:_.size)!=null?D:"40")||24,C=he(i,y,p,1.5);C&&H.appendChild(C)},ba=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},os=()=>{var C;if(!H)return;Ai();let i=(C=r.voiceRecognition)!=null?C:{},p=i.recordingBackgroundColor,f=i.recordingIconColor,y=i.recordingBorderColor;if(ba(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=f!=null?f:"var(--persona-voice-recording-indicator, #ffffff)",f){let E=H.querySelector("svg");E&&E.setAttribute("stroke",f)}y&&(H.style.borderColor=y),H.setAttribute("aria-label","Stop voice recognition")},Kg=()=>{var N,D,se,oe,Z,ve,Ne,Fe;if(!H)return;Ai();let i=(N=r.voiceRecognition)!=null?N:{},p=O.getVoiceInterruptionMode(),f=(D=i.processingIconName)!=null?D:"loader",y=(oe=(se=i.processingIconColor)!=null?se:pt==null?void 0:pt.color)!=null?oe:"",C=(ve=(Z=i.processingBackgroundColor)!=null?Z:pt==null?void 0:pt.backgroundColor)!=null?ve:"",E=(Fe=(Ne=i.processingBorderColor)!=null?Ne:pt==null?void 0:pt.borderColor)!=null?Fe:"";ba(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=C,H.style.borderColor=E;let _=y||"currentColor";H.style.color=_,Si(f,_),H.setAttribute("aria-label","Processing voice input"),p==="none"&&(H.style.cursor="default")},Gg=()=>{var se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie;if(!H)return;Ai();let i=(se=r.voiceRecognition)!=null?se:{},p=O.getVoiceInterruptionMode(),f=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(oe=i.speakingIconName)!=null?oe:f,C=(Fe=i.speakingIconColor)!=null?Fe:p==="barge-in"?(ve=(Z=i.recordingIconColor)!=null?Z:pt==null?void 0:pt.color)!=null?ve:"":(Ne=pt==null?void 0:pt.color)!=null?Ne:"",E=(ut=i.speakingBackgroundColor)!=null?ut:p==="barge-in"?($e=i.recordingBackgroundColor)!=null?$e:"var(--persona-voice-recording-bg, #ef4444)":(ze=pt==null?void 0:pt.backgroundColor)!=null?ze:"",_=(Ie=i.speakingBorderColor)!=null?Ie:p==="barge-in"?(st=i.recordingBorderColor)!=null?st:"":(He=pt==null?void 0:pt.borderColor)!=null?He:"";ba(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=E,H.style.borderColor=_;let N=C||"currentColor";H.style.color=N,Si(y,N);let D=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",D),p==="none"&&(H.style.cursor="default"),p==="barge-in"&&H.classList.add("persona-voice-recording")},zr=()=>{var i,p,f;H&&(ba(),pt&&(H.style.backgroundColor=(i=pt.backgroundColor)!=null?i:"",H.style.color=(p=pt.color)!=null?p:"",H.style.borderColor=(f=pt.borderColor)!=null?f:"",Si(pt.iconName,pt.color||"currentColor"),pt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},va=()=>{var i,p;if(((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"){let f=O.getVoiceStatus(),y=O.getVoiceInterruptionMode();if(y==="none"&&(f==="processing"||f==="speaking"))return;if(y==="cancel"&&(f==="processing"||f==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),nt("user"),zr()});return}O.toggleVoice().then(()=>{K.active=O.isVoiceActive(),K.manuallyDeactivated=!O.isVoiceActive(),ct(),nt("user"),O.isVoiceActive()?os():zr()});return}if(kr){let f=ye.value.trim();K.manuallyDeactivated=!0,ct(),co("user"),f&&(ye.value="",ye.style.height="auto",O.sendMessage(f))}else K.manuallyDeactivated=!1,ct(),ya("user")};br=va,H&&(H.addEventListener("click",va),lt.push(()=>{var i,p;((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),zr()):co("system"),H&&H.removeEventListener("click",va)}));let Qg=l.on("assistant:complete",()=>{De&&(K.active||K.manuallyDeactivated||De==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var i,p;!K.active&&!K.manuallyDeactivated&&(((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?O.toggleVoice().then(()=>{K.active=O.isVoiceActive(),nt("auto"),O.isVoiceActive()&&os()}):ya("auto"))},600))});lt.push(Qg);let Xg=l.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});lt.push(Xg);let jl=()=>{_t(!F,"user")},Jt=null,on=null;if(I&&!k()){let{instance:i,element:p}=Yi({config:r,plugins:o,onToggle:jl});Jt=i,i||(on=p)}Jt?n.appendChild(Jt.element):on&&n.appendChild(on),Bs(),Jo(),Rl(),fi(O.isStreaming()),kl()||(Ft()==="follow"?lo(!0):Ml()),ui(),P&&(!I||k()?setTimeout(()=>hi(),0):F&&setTimeout(()=>hi(),200));let Ds=()=>{var D,se,oe,Z,ve,Ne,Fe,$e,ze,ut,st,He,Ie,qe,Ge,bt,L,Be,We,Xe,Pt,Oe;if(k()){jn(),Bs();return}let i=fn(r),p=(se=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?se:!1,f=i||p||((Z=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Z:!1),y=(ve=n.ownerDocument.defaultView)!=null?ve:window,C=(Fe=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Fe:!0,E=(ze=($e=r.launcher)==null?void 0:$e.mobileBreakpoint)!=null?ze:640,_=y.innerWidth<=E,N=C&&_&&I;try{if(N){ro(),bs(n,r);return}if($&&($=!1,ro(),bs(n,r)),!I&&!i){Q.style.height="",Q.style.width="";return}if(!p&&!i){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,xt=Kt!=null?Kt:Gr;Q.style.width=xt,Q.style.maxWidth=xt}if(Mo(),!f){let Kt=y.innerHeight,xt=64,sn=(Ie=(He=r.launcher)==null?void 0:He.heightOffset)!=null?Ie:0,Wn=Math.max(200,Kt-xt),Bt=Math.min(640,Wn),mn=Math.max(200,Bt-sn);Q.style.height=`${mn}px`}}finally{if(jn(),Bs(),F&&I){let xt=((qe=n.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((bt=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?bt:640),sn=(Be=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?Be:!1,Wn=(Xe=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Xe:!0,Bt=fn(r)&&Wn&&xt,mn=sn||Wn&&xt&&I||Bt;if(mn&&!nn){let _n=n.getRootNode(),Ve=_n instanceof ShadowRoot?_n.host:n.closest(".persona-host");Ve&&!tn&&(tn=Gi(Ve,(Oe=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?Oe:wn)),nn=Qi(n.ownerDocument)}else mn||(tn==null||tn(),tn=null,nn==null||nn(),nn=null)}}};Ds();let Vl=(Jc=n.ownerDocument.defaultView)!=null?Jc:window;if(Vl.addEventListener("resize",Ds),lt.push(()=>Vl.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let i=new ResizeObserver(()=>{jn()});i.observe(Re),lt.push(()=>i.disconnect())}Sn=we.scrollTop;let Kl=Ir(we),Jg=()=>{let i=we.getRootNode(),p=typeof i.getSelection=="function"?i.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},Ti=()=>xm(Jg(),we),Gl=()=>{let i=we.scrollTop,p=Ir(we),f=p<Kl;if(Kl=p,!Yt()){Sn=i,On();return}let{action:y,nextLastScrollTop:C}=za({following:yn.isFollowing(),currentScrollTop:i,lastScrollTop:Sn,nearBottom:vo(we,j),userScrollThreshold:x,isAutoScrolling:Tn||ko||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Sn=C,y==="resume"){Ti()||io();return}y==="pause"&&Ls()};if(we.addEventListener("scroll",Gl,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Gl)),typeof ResizeObserver!="undefined"){let i=new ResizeObserver(()=>{Ig()});i.observe(Ye),i.observe(we),lt.push(()=>i.disconnect())}let Ql=()=>{Yt()&&yn.isFollowing()&&Ti()&&Ls()},Xl=we.ownerDocument;Xl.addEventListener("selectionchange",Ql),lt.push(()=>{Xl.removeEventListener("selectionchange",Ql)});let Yg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Jl=i=>{nr()&&Yt()&&yn.isFollowing()&&Yg.has(i.key)&&Ls()},Yl=i=>{if(!nr()||!Yt()||!yn.isFollowing())return;let p=i.target;p&&p.closest("a, button, [tabindex], input, textarea, select")&&Ls()};we.addEventListener("keydown",Jl),we.addEventListener("focusin",Yl),lt.push(()=>{we.removeEventListener("keydown",Jl),we.removeEventListener("focusin",Yl)});let Zl=i=>{if(!Yt())return;let p=qa({following:yn.isFollowing(),deltaY:i.deltaY,nearBottom:vo(we,j),resumeWhenNearBottom:!0});p==="pause"?Ls():p==="resume"&&!Ti()&&io()};we.addEventListener("wheel",Zl,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",Zl)),jt.addEventListener("click",()=>{Ps(),we.scrollTop=we.scrollHeight,Sn=we.scrollTop,io(),lo(!0),On()}),lt.push(()=>jt.remove()),lt.push(()=>{Al(),Ps()});let ec=()=>{Ue&&(Ar&&(Ue.removeEventListener("click",Ar),Ar=null),U()?(Ue.style.display="",Ar=()=>{_t(!1,"user")},Ue.addEventListener("click",Ar)):Ue.style.display="none")};ec(),(()=>{let{clearChatButton:i}=je;i&&i.addEventListener("click",()=>{O.clearMessages(),Sr.clear(),io(),ms(je.composerOverlay);try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(p),c!=null&&c.clear&&_r(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),Ae==null||Ae.update()})})(),Ct&&Ct.addEventListener("submit",Ol),ye==null||ye.addEventListener("keydown",$l),ye==null||ye.addEventListener("input",_l),ye==null||ye.addEventListener("paste",zl);let tc=(Yc=n.ownerDocument)!=null?Yc:document;tc.addEventListener("keydown",Ul,!0);let nc="persona-attachment-drop-active",Ns=0,Mi=()=>{Ns=0,Te.classList.remove(nc)},ss=()=>{var i;return((i=r.attachments)==null?void 0:i.enabled)===!0&&At!==null},rc=i=>{!di(i.dataTransfer)||!ss()||(Ns++,Ns===1&&Te.classList.add(nc))},oc=i=>{!di(i.dataTransfer)||!ss()||(Ns--,Ns<=0&&Mi())},sc=i=>{!di(i.dataTransfer)||!ss()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},ac=i=>{var f;if(!di(i.dataTransfer)||!ss())return;i.preventDefault(),i.stopPropagation(),Mi();let p=Array.from((f=i.dataTransfer.files)!=null?f:[]);p.length!==0&&At.handleFiles(p)},po=!0;Te.addEventListener("dragenter",rc,po),Te.addEventListener("dragleave",oc,po),n.addEventListener("dragover",sc,po),n.addEventListener("drop",ac,po);let wa=n.ownerDocument,ic=i=>{ss()&&i.preventDefault()},lc=i=>{ss()&&i.preventDefault()};wa.addEventListener("dragover",ic),wa.addEventListener("drop",lc),lt.push(()=>{Ct&&Ct.removeEventListener("submit",Ol),ye==null||ye.removeEventListener("keydown",$l),ye==null||ye.removeEventListener("input",_l),ye==null||ye.removeEventListener("paste",zl),tc.removeEventListener("keydown",Ul,!0)}),lt.push(()=>{Te.removeEventListener("dragenter",rc,po),Te.removeEventListener("dragleave",oc,po),n.removeEventListener("dragover",sc,po),n.removeEventListener("drop",ac,po),wa.removeEventListener("dragover",ic),wa.removeEventListener("drop",lc),Mi()}),lt.push(()=>{O.cancel()}),Jt?lt.push(()=>{Jt==null||Jt.destroy()}):on&<.push(()=>{on==null||on.remove()});let Zt={update(i){var Un,Lr,dn,pn,Zn,go,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,wd,xd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,zd,qd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,wp,xp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,Up,zp,qp,jp,Vp,Kp,Gp,Qp,Xp,Jp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu;let p=r.toolCall,f=r.messageActions,y=(Un=r.layout)==null?void 0:Un.messages,C=r.colorScheme,E=r.loadingIndicator,_=r.iterationDisplay,N=(Lr=r.features)==null?void 0:Lr.showReasoning,D=(dn=r.features)==null?void 0:dn.showToolCalls,se=(pn=r.features)==null?void 0:pn.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Z=(sd=(go=r.features)==null?void 0:go.streamAnimation)==null?void 0:sd.type;r={...r,...i},ro(),bs(n,r),li(n,r),ci(n,r),xr(),r.colorScheme!==C&&ks();let ve=pl.getForInstance(r.plugins);o.length=0,o.push(...ve),I=(id=(ad=r.launcher)==null?void 0:ad.enabled)!=null?id:!0,R=(cd=(ld=r.launcher)==null?void 0:ld.autoExpand)!=null?cd:!1,Le=(pd=(dd=r.features)==null?void 0:dd.showReasoning)!=null?pd:!0,Pe=(md=(ud=r.features)==null?void 0:ud.showToolCalls)!=null?md:!0,fe=(fd=(gd=r.features)==null?void 0:gd.scrollToBottom)!=null?fd:{};let Ne=Ft();ne=(yd=(hd=r.features)==null?void 0:hd.scrollBehavior)!=null?yd:{},Ne!==Ft()&&(Ps(),io()),Jr(),On();let Fe=ae;if(ae=(vd=(bd=r.features)==null?void 0:bd.showEventStreamToggle)!=null?vd:!1,ae&&!Fe){if(V||(Ce=new da(ce),V=new ca(_e,Ce),X=X!=null?X:new pa,Ce.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),O.setSSEEventCallback((ee,Tt)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ee,Tt),X==null||X.processEvent(ee,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let ee=(xd=(wd=r.features)==null?void 0:wd.eventStream)==null?void 0:xd.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=v("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ln.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let zt=he("activity","18px","currentColor",1.5);zt&&yt.appendChild(zt);let at=je.clearChatButtonWrapper,kt=je.closeButtonWrapper,an=at||kt;an&&an.parentNode===ke?ke.insertBefore(yt,an):ke.appendChild(yt),yt.addEventListener("click",()=>{J?ar():Hr()})}}else!ae&&Fe&&(ar(),yt&&(yt.remove(),yt=null),V==null||V.clear(),Ce==null||Ce.destroy(),V=null,Ce=null,X==null||X.reset(),X=null);if(((Cd=r.launcher)==null?void 0:Cd.enabled)===!1&&Jt&&(Jt.destroy(),Jt=null),((Ad=r.launcher)==null?void 0:Ad.enabled)===!1&&on&&(on.remove(),on=null),((Sd=r.launcher)==null?void 0:Sd.enabled)!==!1&&!Jt&&!on){let{instance:ee,element:Tt}=Yi({config:r,plugins:o,onToggle:jl});Jt=ee,ee||(on=Tt),n.appendChild(Tt)}Jt&&Jt.update(r),me&&((Td=r.launcher)==null?void 0:Td.title)!==void 0&&(me.textContent=r.launcher.title),Me&&((Md=r.launcher)==null?void 0:Md.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let $e=(Ed=r.layout)==null?void 0:Ed.header;if(($e==null?void 0:$e.layout)!==z&&ke){let ee=$e?Ja(r,$e,{showClose:U(),onClose:()=>_t(!1,"user")}):qo({config:r,showClose:U(),onClose:()=>_t(!1,"user")});rt.replaceHeader(ee),ke=rt.header.element,M=rt.header.iconHolder,me=rt.header.headerTitle,Me=rt.header.headerSubtitle,Ue=rt.header.closeButton,z=$e==null?void 0:$e.layout}else if($e&&(M&&(M.style.display=$e.showIcon===!1?"none":""),me&&(me.style.display=$e.showTitle===!1?"none":""),Me&&(Me.style.display=$e.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=$e.showCloseButton===!1?"none":""),je.clearChatButtonWrapper)){let ee=$e.showClearChat;if(ee!==void 0){je.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=je;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((kd=r.layout)==null?void 0:kd.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((Ld=r.layout)==null?void 0:Ld.showFooter)!==!1;Re&&(Re.style.display=st?"":"none"),jn(),On(),I!==W?I?_t(R,"auto"):(F=!0,Bs()):R!==A&&_t(R,"auto"),A=R,W=I,Ds(),ec();let qe=JSON.stringify(i.toolCall)!==JSON.stringify(p),Ge=JSON.stringify(r.messageActions)!==JSON.stringify(f),bt=JSON.stringify((Pd=r.layout)==null?void 0:Pd.messages)!==JSON.stringify(y),L=((Id=r.loadingIndicator)==null?void 0:Id.render)!==(E==null?void 0:E.render)||((Wd=r.loadingIndicator)==null?void 0:Wd.renderIdle)!==(E==null?void 0:E.renderIdle)||((Rd=r.loadingIndicator)==null?void 0:Rd.showBubble)!==(E==null?void 0:E.showBubble),Be=r.iterationDisplay!==_,We=((Bd=(Hd=r.features)==null?void 0:Hd.showReasoning)!=null?Bd:!0)!==(N!=null?N:!0)||((Nd=(Dd=r.features)==null?void 0:Dd.showToolCalls)!=null?Nd:!0)!==(D!=null?D:!0)||JSON.stringify((Fd=r.features)==null?void 0:Fd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((Od=r.features)==null?void 0:Od.reasoningDisplay)!==JSON.stringify(oe);(qe||Ge||bt||L||Be||We)&&O&&(Yo++,Is(Ye,O.getMessages(),Y));let Pt=($d=(_d=r.features)==null?void 0:_d.streamAnimation)==null?void 0:$d.type;if(Pt!==Z&&Pt&&Pt!=="none"){let ee=vs(Pt,(zd=(Ud=r.features)==null?void 0:Ud.streamAnimation)==null?void 0:zd.plugins);ee&&Ga(ee,n)}let Oe=(qd=r.launcher)!=null?qd:{},Kt=(jd=Oe.headerIconHidden)!=null?jd:!1,xt=(Kd=(Vd=r.layout)==null?void 0:Vd.header)==null?void 0:Kd.showIcon,sn=Kt||xt===!1,Wn=Oe.headerIconName,Bt=(Gd=Oe.headerIconSize)!=null?Gd:"48px";if(M){let ee=Te.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(sn)M.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(M.style.display="",M.style.height=Bt,M.style.width=Bt,ee&&Tt&&(ee.contains(M)?M.nextSibling!==Tt&&(M.remove(),ee.insertBefore(M,Tt)):ee.insertBefore(M,Tt)),Wn){let at=parseFloat(Bt)||24,kt=he(Wn,at*.6,"currentColor",1);kt?M.replaceChildren(kt):M.textContent=(Qd=Oe.agentIconText)!=null?Qd:"\u{1F4AC}"}else if(Oe.iconUrl){let at=M.querySelector("img");if(at)at.src=Oe.iconUrl,at.style.height=Bt,at.style.width=Bt;else{let kt=document.createElement("img");kt.src=Oe.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Bt,kt.style.width=Bt,M.replaceChildren(kt)}}else{let at=M.querySelector("svg"),kt=M.querySelector("img");(at||kt)&&M.replaceChildren(),M.textContent=(Xd=Oe.agentIconText)!=null?Xd:"\u{1F4AC}"}let zt=M.querySelector("img");zt&&(zt.style.height=Bt,zt.style.width=Bt)}}let mn=(Yd=(Jd=r.layout)==null?void 0:Jd.header)==null?void 0:Yd.showTitle,_n=(ep=(Zd=r.layout)==null?void 0:Zd.header)==null?void 0:ep.showSubtitle;if(me&&(me.style.display=mn===!1?"none":""),Me&&(Me.style.display=_n===!1?"none":""),Ue){((np=(tp=r.layout)==null?void 0:tp.header)==null?void 0:np.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(rp=Oe.closeButtonSize)!=null?rp:"32px",zt=(op=Oe.closeButtonPlacement)!=null?op:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=je,kt=zt==="top-right",an=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==an)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Te.style.position="relative",Te.appendChild(at);else{let dt=(ap=(sp=Oe.clearChat)==null?void 0:sp.placement)!=null?ap:"inline",ln=(lp=(ip=Oe.clearChat)==null?void 0:ip.enabled)!=null?lp:!0;at.className=ln&&dt==="inline"?"":"persona-ml-auto";let Rn=Te.querySelector(".persona-border-b-persona-divider");Rn&&Rn.appendChild(at)}if(Ue.style.color=Oe.closeButtonColor||Ln.actionIconColor,Oe.closeButtonBackgroundColor?(Ue.style.backgroundColor=Oe.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),Oe.closeButtonBorderWidth||Oe.closeButtonBorderColor){let dt=Oe.closeButtonBorderWidth||"0px",ln=Oe.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${ln}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");Oe.closeButtonBorderRadius?(Ue.style.borderRadius=Oe.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),Oe.closeButtonPaddingX?(Ue.style.paddingLeft=Oe.closeButtonPaddingX,Ue.style.paddingRight=Oe.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Oe.closeButtonPaddingY?(Ue.style.paddingTop=Oe.closeButtonPaddingY,Ue.style.paddingBottom=Oe.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let vn=(cp=Oe.closeButtonIconName)!=null?cp:"x",dr=(dp=Oe.closeButtonIconText)!=null?dp:"\xD7";Ue.innerHTML="";let kn=he(vn,"28px","currentColor",1);kn?Ue.appendChild(kn):Ue.textContent=dr;let Xt=(pp=Oe.closeButtonTooltipText)!=null?pp:"Close chat",zn=(up=Oe.closeButtonShowTooltip)!=null?up:!0;if(Ue.setAttribute("aria-label",Xt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),zn&&Xt)){let dt=null,ln=()=>{if(dt||!Ue)return;let No=Ue.ownerDocument,Fs=No.body;if(!Fs)return;dt=Pr(No,"div","persona-clear-chat-tooltip"),dt.textContent=Xt;let Os=Pr(No,"div");Os.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Os);let Fo=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(wo),dt.style.left=`${Fo.left+Fo.width/2}px`,dt.style.top=`${Fo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Fs.appendChild(dt)},Rn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",ln),at.addEventListener("mouseleave",Rn),Ue.addEventListener("focus",ln),Ue.addEventListener("blur",Rn),at._cleanupTooltip=()=>{Rn(),at&&(at.removeEventListener("mouseenter",ln),at.removeEventListener("mouseleave",Rn)),Ue&&(Ue.removeEventListener("focus",ln),Ue.removeEventListener("blur",Rn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:It}=je;if(Ve){let ee=(mp=Oe.clearChat)!=null?mp:{},Tt=(gp=ee.enabled)!=null?gp:!0,zt=(hp=(fp=r.layout)==null?void 0:fp.header)==null?void 0:hp.showClearChat,at=zt!==void 0?zt:Tt,kt=(yp=ee.placement)!=null?yp:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:an}=je;!k()&&an&&!an.classList.contains("persona-absolute")&&(at?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let vn=kt==="top-right",dr=It.classList.contains("persona-absolute");if(!k()&&vn!==dr&&at){if(It.remove(),vn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Te.style.position="relative",Te.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Xt=Te.querySelector(".persona-border-b-persona-divider"),zn=je.closeButtonWrapper;Xt&&zn&&zn.parentElement===Xt?Xt.insertBefore(It,zn):Xt&&Xt.appendChild(It)}let kn=je.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(vn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(at){if(!k()){let dt=(bp=ee.size)!=null?bp:"32px";Ve.style.height=dt,Ve.style.width=dt}let an=(vp=ee.iconName)!=null?vp:"refresh-cw",vn=(wp=ee.iconColor)!=null?wp:"";Ve.style.color=vn||Ln.actionIconColor,Ve.innerHTML="";let dr=k()?"14px":"20px",kn=he(an,dr,"currentColor",2);if(kn&&Ve.appendChild(kn),ee.backgroundColor?(Ve.style.backgroundColor=ee.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let dt=ee.borderWidth||"0px",ln=ee.borderColor||"transparent";Ve.style.border=`${dt} solid ${ln}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ee.borderRadius?(Ve.style.borderRadius=ee.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ee.paddingX?(Ve.style.paddingLeft=ee.paddingX,Ve.style.paddingRight=ee.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ee.paddingY?(Ve.style.paddingTop=ee.paddingY,Ve.style.paddingBottom=ee.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Xt=(xp=ee.tooltipText)!=null?xp:"Clear chat",zn=(Cp=ee.showTooltip)!=null?Cp:!0;if(Ve.setAttribute("aria-label",Xt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),zn&&Xt)){let dt=null,ln=()=>{if(dt||!Ve)return;let No=Ve.ownerDocument,Fs=No.body;if(!Fs)return;dt=Pr(No,"div","persona-clear-chat-tooltip"),dt.textContent=Xt;let Os=Pr(No,"div");Os.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Os);let Fo=Ve.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(wo),dt.style.left=`${Fo.left+Fo.width/2}px`,dt.style.top=`${Fo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Fs.appendChild(dt)},Rn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",ln),It.addEventListener("mouseleave",Rn),Ve.addEventListener("focus",ln),Ve.addEventListener("blur",Rn),It._cleanupTooltip=()=>{Rn(),It&&(It.removeEventListener("mouseenter",ln),It.removeEventListener("mouseleave",Rn)),Ve&&(Ve.removeEventListener("focus",ln),Ve.removeEventListener("blur",Rn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[ml],Io=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ua.message,ua.messageAndClick];T=gl({parsers:$n,handlers:Io,getSessionMetadata:b,updateSessionMetadata:w,emit:l.emit,documentRef:typeof document!="undefined"?document:null}),Y=fg(r,T,de),O.updateConfig(r),Is(Ye,O.getMessages(),Y),Jo(),Rl(),fi(O.isStreaming());let Wo=((Ap=r.voiceRecognition)==null?void 0:Ap.enabled)===!0,Ro=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ho=((Tp=(Sp=r.voiceRecognition)==null?void 0:Sp.provider)==null?void 0:Tp.type)==="runtype";if(Wo&&(Ro||Ho))if(!H||!be){let ee=Vg(r.voiceRecognition,r.sendButton);ee&&(H=ee.micButton,be=ee.micButtonWrapper,ht.insertBefore(be,Cn),H.addEventListener("click",va),H.disabled=O.isStreaming())}else{let ee=(Mp=r.voiceRecognition)!=null?Mp:{},Tt=(Ep=r.sendButton)!=null?Ep:{},zt=(kp=ee.iconName)!=null?kp:"mic",at=(Lp=Tt.size)!=null?Lp:"40px",kt=(Pp=ee.iconSize)!=null?Pp:at,an=parseFloat(kt)||24;H.style.width=kt,H.style.height=kt,H.style.minWidth=kt,H.style.minHeight=kt;let vn=(Wp=(Ip=ee.iconColor)!=null?Ip:Tt.textColor)!=null?Wp:"currentColor";H.innerHTML="";let dr=he(zt,an,vn,2);dr?H.appendChild(dr):H.textContent="\u{1F3A4}";let kn=(Rp=ee.backgroundColor)!=null?Rp:Tt.backgroundColor;kn?H.style.backgroundColor=kn:H.style.backgroundColor="",vn?H.style.color=vn:H.style.color="var(--persona-text, #111827)",ee.borderWidth?(H.style.borderWidth=ee.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),ee.borderColor?H.style.borderColor=ee.borderColor:H.style.borderColor="",ee.paddingX?(H.style.paddingLeft=ee.paddingX,H.style.paddingRight=ee.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),ee.paddingY?(H.style.paddingTop=ee.paddingY,H.style.paddingBottom=ee.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Xt=be==null?void 0:be.querySelector(".persona-send-button-tooltip"),zn=(Hp=ee.tooltipText)!=null?Hp:"Start voice recognition";if(((Bp=ee.showTooltip)!=null?Bp:!1)&&zn)if(Xt)Xt.textContent=zn,Xt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=zn,be==null||be.insertBefore(ln,H)}else Xt&&(Xt.style.display="none");be.style.display="",H.disabled=O.isStreaming()}else H&&be&&(be.style.display="none",((Np=(Dp=r.voiceRecognition)==null?void 0:Dp.provider)==null?void 0:Np.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():kr&&co());if(((Fp=r.attachments)==null?void 0:Fp.enabled)===!0)if(!gt||!le){let ee=(Op=r.attachments)!=null?Op:{},zt=($p=((_p=r.sendButton)!=null?_p:{}).size)!=null?$p:"40px";Lt||(Lt=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,ye)),Ke||(Ke=document.createElement("input"),Ke.type="file",Ke.accept=((Up=ee.allowedTypes)!=null?Up:Kr).join(","),Ke.multiple=((zp=ee.maxFiles)!=null?zp:4)>1,Ke.style.display="none",Ke.setAttribute("aria-label","Attach files"),Ct.insertBefore(Ke,ye)),gt=v("div","persona-send-button-wrapper"),le=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(qp=ee.buttonTooltipText)!=null?qp:"Attach file");let at=(jp=ee.buttonIconName)!=null?jp:"paperclip",kt=zt,an=parseFloat(kt)||40,vn=Math.round(an*.6);le.style.width=kt,le.style.height=kt,le.style.minWidth=kt,le.style.minHeight=kt,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let dr=he(at,vn,"currentColor",1.5);dr?le.appendChild(dr):le.textContent="\u{1F4CE}",le.addEventListener("click",zn=>{zn.preventDefault(),Ke==null||Ke.click()}),gt.appendChild(le);let kn=(Vp=ee.buttonTooltipText)!=null?Vp:"Attach file",Xt=v("div","persona-send-button-tooltip");Xt.textContent=kn,gt.appendChild(Xt),Qe.append(gt),!At&&Ke&&Lt&&(At=Zs.fromConfig(ee),At.setPreviewsContainer(Lt),Ke.addEventListener("change",async()=>{At&&(Ke!=null&&Ke.files)&&(await At.handleFileSelect(Ke.files),Ke.value="")})),Te.querySelector(".persona-attachment-drop-overlay")||Te.appendChild(hg(ee.dropOverlay))}else{gt.style.display="";let ee=(Kp=r.attachments)!=null?Kp:{};Ke&&(Ke.accept=((Gp=ee.allowedTypes)!=null?Gp:Kr).join(","),Ke.multiple=((Qp=ee.maxFiles)!=null?Qp:4)>1),At&&At.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else gt&&(gt.style.display="none"),At&&At.clearAttachments(),(Xp=Te.querySelector(".persona-attachment-drop-overlay"))==null||Xp.remove();let Gt=(Jp=r.sendButton)!=null?Jp:{},Bo=(Yp=Gt.useIcon)!=null?Yp:!1,uo=(Zp=Gt.iconText)!=null?Zp:"\u2191",mo=Gt.iconName,qr=(eu=Gt.tooltipText)!=null?eu:"Send message",Do=(tu=Gt.showTooltip)!=null?tu:!1,Ze=(nu=Gt.size)!=null?nu:"40px",Nt=Gt.backgroundColor,Dt=Gt.textColor;if(Bo){if(pe.style.width=Ze,pe.style.height=Ze,pe.style.minWidth=Ze,pe.style.minHeight=Ze,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Dt?pe.style.color=Dt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",mo){let ee=parseFloat(Ze)||24,Tt=(Dt==null?void 0:Dt.trim())||"currentColor",zt=he(mo,ee,Tt,2);zt?pe.appendChild(zt):pe.textContent=uo}else pe.textContent=uo;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(ou=(ru=r.copy)==null?void 0:ru.sendButtonLabel)!=null?ou:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Dt?pe.style.color=Dt:pe.classList.add("persona-text-white");Gt.borderWidth?(pe.style.borderWidth=Gt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Gt.borderColor?pe.style.borderColor=Gt.borderColor:pe.style.borderColor="",Gt.paddingX?(pe.style.paddingLeft=Gt.paddingX,pe.style.paddingRight=Gt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Gt.paddingY?(pe.style.paddingTop=Gt.paddingY,pe.style.paddingBottom=Gt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=Cn==null?void 0:Cn.querySelector(".persona-send-button-tooltip");if(Do&&qr)if(Vt)Vt.textContent=qr,Vt.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=qr,Cn==null||Cn.insertBefore(ee,pe)}else Vt&&(Vt.style.display="none");let $t=(cu=(su=r.layout)==null?void 0:su.contentMaxWidth)!=null?cu:k()?(lu=(iu=(au=r.launcher)==null?void 0:au.composerBar)==null?void 0:iu.contentMaxWidth)!=null?lu:"720px":void 0;$t?(Ye.style.maxWidth=$t,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(du=r.statusIndicator)!=null?du:{},Ut=(pu=mt.visible)!=null?pu:!0;if(hn.style.display=Ut?"":"none",O){let ee=O.getStatus();ft(hn,(zt=>{var at,kt,an,vn;return zt==="idle"?(at=mt.idleText)!=null?at:en.idle:zt==="connecting"?(kt=mt.connectingText)!=null?kt:en.connecting:zt==="connected"?(an=mt.connectedText)!=null?an:en.connected:zt==="error"?(vn=mt.errorText)!=null?vn:en.error:en[zt]})(ee),mt,ee)}hn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";hn.classList.add(gn)},open(){U()&&_t(!0,"api")},close(){U()&&_t(!1,"api")},toggle(){U()&&_t(!F,"api")},reconnect(){O.reconnectNow()},clearChat(){An=!1,O.clearMessages(),Sr.clear(),io();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c!=null&&c.clear&&_r(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),Ae==null||Ae.update()},setMessage(i){return!ye||O.isStreaming()?!1:(!F&&U()&&_t(!0,"system"),ye.value=i,ye.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(O.isStreaming())return!1;let p=(i==null?void 0:i.trim())||ye.value.trim();return p?(!F&&U()&&_t(!0,"system"),ye.value="",ye.style.height="auto",O.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return O.isStreaming()?!1:((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?(O.isVoiceActive()||(!F&&U()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),O.toggleVoice().then(()=>{K.active=O.isVoiceActive(),nt("user"),O.isVoiceActive()&&os()})),!0):kr?!0:ql()?(!F&&U()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),ya("user"),!0):!1},stopVoiceRecognition(){var i,p;return((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),nt("user"),zr()}),!0):!1:kr?(K.manuallyDeactivated=!0,ct(),co("user"),!0):!1},injectMessage(i){return!F&&U()&&_t(!0,"system"),O.injectMessage(i)},injectAssistantMessage(i){!F&&U()&&_t(!0,"system");let p=O.injectAssistantMessage(i);return te&&(te=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),p},injectUserMessage(i){return!F&&U()&&_t(!0,"system"),O.injectUserMessage(i)},injectSystemMessage(i){return!F&&U()&&_t(!0,"system"),O.injectSystemMessage(i)},injectMessageBatch(i){return!F&&U()&&_t(!0,"system"),O.injectMessageBatch(i)},injectComponentDirective(i){return!F&&U()&&_t(!0,"system"),O.injectComponentDirective(i)},injectTestMessage(i){!F&&U()&&_t(!0,"system"),O.injectTestEvent(i)},async connectStream(i,p){return O.connectStream(i,p)},__pushEventStreamEvent(i){V&&(X==null||X.processEvent(i.type,i.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ae||!V||Hr()},hideEventStream(){J&&ar()},isEventStreamVisible(){return J},showArtifacts(){tr(r)&&(An=!1,xr(),wt==null||wt.setMobileOpen(!0))},hideArtifacts(){tr(r)&&(An=!0,xr())},upsertArtifact(i){return tr(r)?(An=!1,O.upsertArtifact(i)):null},selectArtifact(i){tr(r)&&O.selectArtifact(i)},clearArtifacts(){tr(r)&&O.clearArtifacts()},getArtifacts(){var i;return(i=O==null?void 0:O.getArtifacts())!=null?i:[]},getSelectedArtifactId(){var i;return(i=O==null?void 0:O.getSelectedArtifactId())!=null?i:null},focusInput(){return I&&!F&&!k()||!ye?!1:(ye.focus(),!0)},async resolveApproval(i,p,f){let C=O.getMessages().find(E=>{var _;return E.variant==="approval"&&((_=E.approval)==null?void 0:_.id)===i});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${i}`);if(C.approval.toolType==="webmcp"){O.resolveWebMcpApproval(C.id,p);return}return O.resolveApproval(C.approval,p,f)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){w(i)},on(i,p){return l.on(i,p)},off(i,p){l.off(i,p)},isOpen(){return U()&&F},isVoiceActive(){return K.active},toggleReadAloud(i){O.toggleReadAloud(i)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(i){return O.getReadAloudState(i)},onReadAloudChange(i){return O.onReadAloudChange(i)},getState(){return{open:U()&&F,launcherEnabled:I,voiceActive:K.active,streaming:O.isStreaming()}},showCSATFeedback(i){!F&&U()&&_t(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let f=ug({onSubmit:async(y,C)=>{var E;O.isClientTokenMode()&&await O.submitCSATFeedback(y,C),(E=i==null?void 0:i.onSubmit)==null||E.call(i,y,C)},onDismiss:i==null?void 0:i.onDismiss,...i});Ye.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!F&&U()&&_t(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let f=mg({onSubmit:async(y,C)=>{var E;O.isClientTokenMode()&&await O.submitNPSFeedback(y,C),(E=i==null?void 0:i.onSubmit)==null||E.call(i,y,C)},onDismiss:i==null?void 0:i.onDismiss,...i});Ye.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,p){return O.submitCSATFeedback(i,p)},async submitNPSFeedback(i,p){return O.submitNPSFeedback(i,p)},destroy(){vi(),Po!=null&&(clearInterval(Po),Po=null),lt.forEach(i=>i()),ue.remove(),it==null||it.remove(),Jt==null||Jt.destroy(),on==null||on.remove(),Ar&&Ue.removeEventListener("click",Ar)}};if((((Zc=t==null?void 0:t.debugTools)!=null?Zc:!1)||!!r.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,p={controller:Zt,getMessages:Zt.getMessages,getStatus:Zt.getStatus,getMetadata:Zt.getPersistentMetadata,updateMetadata:Zt.updatePersistentMetadata,clearHistory:()=>Zt.clearChat(),setVoiceActive:f=>f?Zt.startVoiceRecognition():Zt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,lt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=i)})}if(typeof window!="undefined"){let i=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===i)&&Zt.focusInput()};if(window.addEventListener("persona:focusInput",p),lt.push(()=>{window.removeEventListener("persona:focusInput",p)}),ae){let N=se=>{let oe=se.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===i)&&Zt.showEventStream()},D=se=>{let oe=se.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===i)&&Zt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",D)})}let f=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===i)&&Zt.showArtifacts()},y=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===i)&&Zt.hideArtifacts()},C=N=>{let D=N.detail;D!=null&&D.instanceId&&D.instanceId!==i||D!=null&&D.artifact&&Zt.upsertArtifact(D.artifact)},E=N=>{let D=N.detail;D!=null&&D.instanceId&&D.instanceId!==i||typeof(D==null?void 0:D.id)=="string"&&Zt.selectArtifact(D.id)},_=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===i)&&Zt.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",C),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",_),lt.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",C),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",_)})}let Yn=pw(r.persistState);if(Yn&&U()){let i=uw(Yn.storage),p=`${Yn.keyPrefix}widget-open`,f=`${Yn.keyPrefix}widget-voice`,y=`${Yn.keyPrefix}widget-voice-mode`;if(i){let C=((ed=Yn.persist)==null?void 0:ed.openState)&&i.getItem(p)==="true",E=((td=Yn.persist)==null?void 0:td.voiceState)&&i.getItem(f)==="true",_=((nd=Yn.persist)==null?void 0:nd.voiceState)&&i.getItem(y)==="true";if(C&&setTimeout(()=>{Zt.open(),setTimeout(()=>{var N;if(E||_)Zt.startVoiceRecognition();else if((N=Yn.persist)!=null&&N.focusInput){let D=n.querySelector("textarea");D&&D.focus()}},100)},0),(rd=Yn.persist)!=null&&rd.openState&&(l.on("widget:opened",()=>{i.setItem(p,"true")}),l.on("widget:closed",()=>{i.setItem(p,"false")})),(od=Yn.persist)!=null&&od.voiceState&&(l.on("voice:state",N=>{i.setItem(f,N.active?"true":"false")}),l.on("user:message",N=>{i.setItem(y,N.viaVoice?"true":"false")})),Yn.clearOnChatClear){let N=()=>{i.removeItem(p),i.removeItem(f),i.removeItem(y)},D=()=>N();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return h&&U()&&setTimeout(()=>{Zt.open()},0),ts(),ga||gu().then(()=>{O&&(Yo++,Sr.clear(),Is(Ye,O.getMessages(),Y))}).catch(()=>{}),Zt};var mw=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},gw=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},fw=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},hw=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},bg=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},wl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},vg=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",wl(n)},yl=n=>{n.style.transition=""},bl=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},vl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},pi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},yw=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},bw=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},wg=(n,e,t,r,o,s,a)=>{var b,w,S,B,T,I;let l=ur(s),d=l.reveal==="push";yw(n,e,t,r,d),bw(n,e,t,r,l.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=l.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,u=(w=(b=s==null?void 0:s.launcher)==null?void 0:b.mobileFullscreen)!=null?w:!0,g=(B=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?B:640,h=c!=null?c.innerWidth<=g:!1;if(u&&h&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),bl(e),yl(r),vg(r),vl(t),pi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((I=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?I:wn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),vg(r),gw(r,l.maxHeight),l.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",bl(e),yl(r),vl(t),pi(o,r);let R=l.animate?"transform 180ms ease":"none",P=l.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=l.width,r.style.maxWidth=l.width,r.style.minWidth=l.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=R,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",l.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(l.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",yl(r),wl(r),pi(o,r);let R=mw(l.width,n.clientWidth),P=Math.max(0,n.clientWidth),A=l.animate?"margin-left 180ms ease":"none",W=l.side==="right"?a?-R:0:a?0:-R;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${P+R}px`,e.style.transition=A,e.style.marginLeft=`${W}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${P}px`,t.style.maxWidth=`${P}px`,t.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=l.width,r.style.minWidth=l.width,r.style.maxWidth=l.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",bl(e),wl(r),vl(t),pi(o,r);let R=l.reveal==="emerge";R?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let P=a?l.width:"0px",A=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",fw(r,l.maxHeight),r.style.overflow=R||W?"hidden":"visible",r.style.transition=A,R&&(r.style.alignItems=l.side==="right"?"flex-start":"flex-end",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.boxSizing="border-box")}},vw=(n,e)=>{let t=n.ownerDocument.createElement("div");return bg(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){bg(t,r)},destroy(){t.remove()}}},ww=(n,e)=>{var I,R,P,A;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),l=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),g=(R=(I=e==null?void 0:e.launcher)==null?void 0:I.enabled)==null||R?(A=(P=e==null?void 0:e.launcher)==null?void 0:P.autoExpand)!=null?A:!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,n),d.appendChild(n);let h=null,m=()=>{h==null||h.disconnect(),h=null},b=()=>{m(),ur(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{wg(a,l,d,c,u,e,g)}),h.observe(a))},w=!1,S=()=>{wg(a,l,d,c,u,e,g),b(),g&&!w&&a.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,hw(a,ur(e)))},B=a.ownerDocument.defaultView,T=()=>{S()};return B==null||B.addEventListener("resize",T),ur(e).reveal==="push"?(l.appendChild(d),l.appendChild(c),a.appendChild(l)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:u,shell:a,syncWidgetState(W){let z=W.launcherEnabled?W.open:!0;g!==z&&(g=z,S())},updateConfig(W){var z,$;e=W,(($=(z=e==null?void 0:e.launcher)==null?void 0:z.enabled)!=null?$:!0)===!1&&(g=!0),S()},destroy(){B==null||B.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},xg=(n,e)=>fn(e)?ww(n,e):vw(n,e);var ma={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Cg=.15,Ag=1.5,xl="persona-preview-shell-theme",xw={load:()=>null,save:()=>{},clear:()=>{}},Cw=["How do I get started?","Pricing & plans","Talk to support"];function Cl(n){return n.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Aw(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Sg(n){let e=Aw(n);return`* { box-sizing: border-box; }
|
|
139
|
+
${ot?"background: transparent !important;":""}
|
|
140
|
+
`}if(!y&&!i){let Lt="max-height: -moz-available !important; max-height: stretch !important;",Jt=g?"":"padding-top: 1.25em !important;",qs=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;ke.style.cssText+=Lt+Jt+qs}Ao()};Ws(),rs(t,o),ws(t,o),xs(t,o),Cr=()=>{Ws(),rs(t,o),ws(t,o),xs(t,o),Ms?t.style.setProperty("--persona-artifact-welded-outer-radius",Ms):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",Gl)}),qe.push(()=>{vr!==null&&clearTimeout(vr)});let Cn=null,An=null;qe.push(()=>{Cn?.(),Cn=null,An?.(),An=null}),xr&&qe.push(()=>{xr?.disconnect(),xr=null}),qe.push(()=>{Tr?.(),Tr=null,ni(),vt&&(vt.remove(),vt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Y&&qe.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),Fe?.destroy(),Fe=null,Ce?.destroy(),Ce=null,ue=null});let mo=null,Jl=()=>{mo&&(mo(),mo=null),o.colorScheme==="auto"&&(mo=ba(()=>{rs(t,o)}))};Jl(),qe.push(()=>{mo&&(mo(),mo=null)}),qe.push(a);let Bs=o.features?.streamAnimation;if(Bs?.type&&Bs.type!=="none"){let i=ur(Bs.type,Bs.plugins);i&&(Wa(i,t),qe.push(()=>Lp(t)))}let Hs=Gp(bt),ho=null,_,oi=i=>{if(!_)return;let g=i??_.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?bd(g):null;h?Hs.render(h,_,F,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(y=>y.role==="user")?Hs.render([],_,F,g):Hs.render(o.suggestionChips,_,F,g,o.suggestionChipsConfig)},hn=!1,yo=wp(),Uo=new Map,bo=new Map,Vn=new Map,ri=0,Du=Hn()!==null,en=Ea(),ln=0,qn=null,cn=!1,Ds=!1,Kn=0,yn=null,vo=null,si=!1,Ns=!1,ai=null,Mr=!0,ii=!1,li=null,Nu=4,Fs=24,Fu=80,ci=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Yl=o.voiceRecognition?.autoResume??!1,Pn=i=>{l.emit("voice:state",{active:Qe.active,source:i,timestamp:Date.now()})},bn=()=>{C(i=>({...i,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Ou=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Ml(c.voiceState),g=!!i.active,h=Number(i.timestamp??0);Qe.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-h<ly&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Pn("restore"),_.isVoiceActive()&&Go()}):$s("restore"))},1e3)},_u=()=>_?gu(_.getMessages()).filter(i=>!i.__skipPersist):[],Os=null,Zl=(i,g)=>{typeof console<"u"&&console.error(i,g)},di=(i,g)=>{let h=()=>{try{let X=i();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(O=>{Zl(g,O)})}catch(X){return Zl(g,X),null}},y=Os,A=y?y.then(()=>h()??void 0):h();if(!A)return;let L=A.finally(()=>{Os===L&&(Os=null)});Os=L};function pi(i){if(!d?.save)return;let h={messages:i?gu(i):_?_u():[],metadata:c,artifacts:gn.artifacts,selectedArtifactId:gn.selectedId};di(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let jo=null,ec=()=>ke.querySelector("#persona-scroll-container")||ie,Er=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),cn=!1},tc=()=>{qn!==null&&(cancelAnimationFrame(qn),qn=null),Ds=!1,Er()},$u=()=>hn&&fi()&&(Xt()!=="anchor-top"||Hl()),ui=()=>{let i=po()||"Jump to latest",g=$u();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Kn>0?(uo.textContent=String(Kn),uo.style.display="",Pt.setAttribute("aria-label",`${i} (${Kn} new)`)):(uo.textContent="",uo.style.display="none",Pt.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},nc=()=>{Kn!==0&&(Kn=0,ui())},fi=()=>$n()?!en.isFollowing():!io(ie,Fs),tn=()=>{if(!Ss()||Pe){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==pe&&pe.appendChild(Pt),Oo();let g=En(ie)>0&&fi();g?ui():nc(),Pt.style.display=g?"":"none"},kr=()=>{en.pause()&&(tc(),tn())},Gn=()=>{en.resume(),nc(),tn()},Qn=(i=!1)=>{$n()&&en.isFollowing()&&(!i&&!hn||(qn!==null&&(cancelAnimationFrame(qn),qn=null),Ds=!0,qn=requestAnimationFrame(()=>{qn=null,Ds=!1,en.isFollowing()&&zu(ec(),i?220:140)})))},oc=(i,g,h,y=()=>!0)=>{let A=i.scrollTop,L=g(),X=L-A;if(Er(),Math.abs(X)<1){cn=!0,i.scrollTop=L,ln=i.scrollTop,cn=!1;return}let O=performance.now();cn=!0;let K=ce=>1-Math.pow(1-ce,3),re=ce=>{if(!y()){Er();return}let se=g();se!==L&&(L=se,X=L-A);let we=ce-O,Ke=Math.min(we/h,1),ht=K(Ke),st=A+X*ht;i.scrollTop=st,ln=i.scrollTop,Ke<1?jo=requestAnimationFrame(re):(i.scrollTop=L,ln=i.scrollTop,jo=null,cn=!1)};jo=requestAnimationFrame(re)},zu=(i,g=500)=>{let h=En(i)-i.scrollTop;if(Math.abs(h)<1){ln=i.scrollTop;return}if(Math.abs(h)>=Fu){Er(),cn=!0,i.scrollTop=En(i),ln=i.scrollTop,cn=!1;return}oc(i,()=>En(i),g,()=>en.isFollowing())},rc=()=>{let i=ec();cn=!0,i.scrollTop=En(i),ln=i.scrollTop,cn=!1,tn()},sc=i=>{let g=0,h=i;for(;h&&h!==ie;)g+=h.offsetTop,h=h.offsetParent;return g},ac=()=>{if(Lu()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(L=>L.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ie.querySelector(`[data-message-id="${h}"]`);if(!y)return!1;let A=Math.min(Math.max(0,sc(y)-Wl()),En(ie));return cn=!0,ie.scrollTop=A,ln=ie.scrollTop,cn=!1,Xt()==="follow"&&!io(ie,Fs)&&en.pause(),tn(),!0},ic=i=>{zn.style.height=`${Math.max(0,Math.round(i))}px`,yn&&(yn.spacerHeight=Math.max(0,i))},Lr=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Er(),yn=null,zn.style.height="0px"},Uu=i=>{vo!==null&&cancelAnimationFrame(vo),vo=requestAnimationFrame(()=>{vo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ie.querySelector(`[data-message-id="${g}"]`);if(!h)return;let y=sc(h),A=yn?.spacerHeight??0,L=ie.scrollHeight-A,{targetScrollTop:X,spacerHeight:O}=Tp({anchorOffsetTop:y,topOffset:Wl(),viewportHeight:ie.clientHeight,contentHeight:L});yn={initialSpacerHeight:O,contentHeightAtAnchor:L,spacerHeight:O},ic(O),oc(ie,()=>X,220)})},ju=()=>{if($n()){if(!en.isFollowing()||io(ie,1))return;Qn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let i=ie.scrollHeight-yn.spacerHeight,g=Mp({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:i});g!==yn.spacerHeight&&ic(g)}tn()},Vu=i=>{let g=Xt();g==="follow"?(Gn(),Qn(!0)):g==="anchor-top"&&(Mr=!1,ii=!0,Uu(i))},qu=()=>{if(Xt()==="anchor-top"){if(ii){Mr=!1;return}Mr=!0,Lr(),Gn(),Qn(!0)}},Ku=i=>{let g=new Map;i.forEach(h=>{let y=ci.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(l.emit("assistant:message",h),!Ns&&(Xt()!=="anchor-top"||Hl())&&fi()&&(Kn+=1,ui(),tn(),Nl(Kn===1?"1 new message below.":`${Kn} new messages below.`))),h.role==="assistant"&&y?.streaming&&h.streaming===!1&&l.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&l.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):l.emit("approval:requested",{approval:h.approval,message:h}))}),ci.clear(),g.forEach((h,y)=>{ci.set(y,h)})},Gu=(i,g,h)=>{let y=document.createElement("div"),L=(()=>{let R=r.find(Oe=>Oe.renderLoadingIndicator);if(R?.renderLoadingIndicator)return R.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(R,Oe)=>Oe==null?!1:typeof Oe=="string"?(R.textContent=Oe,!0):(R.appendChild(Oe),!0),O=new Set,K=new Set,re=r.some(R=>R.renderAskUserQuestion),ce=[],se=[],we=o.enableComponentStreaming!==!1,Ke=o.approval!==!1,ht=[];if(g.forEach(R=>{O.add(R.id);let Oe=re&&Lo(R),Ae=Ke&&R.variant==="approval"&&!!R.approval,$e=!Oe&&R.role==="assistant"&&!R.variant&&we&&Tl(R);!Ae&&Vn.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Vn.delete(R.id)),!$e&&bo.has(R.id)&&(i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(R.id));let St=Lo(R)?`:${R.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${R.agentMetadata?.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=vp(R,ri)+St,xt=Oe||Ae||$e?null:xp(yo,R.id,pt);if(xt){y.appendChild(xt.cloneNode(!0)),Lo(R)&&R.toolCall?.id&&R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(K.add(R.toolCall.id),oa(R,o,Ie.composerOverlay));return}let yt=null,_t=r.find(de=>!!(R.variant==="reasoning"&&de.renderReasoning||R.variant==="tool"&&de.renderToolCall||!R.variant&&de.renderMessage)),Co=o.layout?.messages;if(Lo(R)&&R.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(R.id),i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime");return}if(Oi(R)&&o.features?.suggestReplies?.enabled!==!1)return;if(Lo(R)&&o.features?.askUserQuestion?.enabled!==!1){let de=r.find(Ct=>typeof Ct.renderAskUserQuestion=="function");if(de&>.current){let Ct=Uo.get(R.id),Vt=Ct!==pt,Ht=null;if(Vt){let{payload:Ze,complete:kt}=er(R),He=R.id,et=()=>gt.current?.getMessages().find(nn=>nn.id===He);Ht=de.renderAskUserQuestion({message:R,payload:Ze,complete:kt,resolve:nn=>{let Ao=et();Ao&>.current?.resolveAskUserQuestion(Ao,nn)},dismiss:()=>{let nn=et();nn?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(nn),gt.current?.resolveAskUserQuestion(nn,"(dismissed)"))},config:o})}let ot=Ct!=null;if(Vt&&Ht===null&&!ot){R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(K.add(R.toolCall.id),oa(R,o,Ie.composerOverlay));return}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${R.id}`,Ve.setAttribute("data-wrapper-id",R.id),Ve.setAttribute("data-ask-plugin-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),y.appendChild(Ve),ce.push({messageId:R.id,fingerprint:pt,bubble:Ht});return}else{R.agentMetadata?.awaitingLocalTool===!0&&!R.agentMetadata?.askUserQuestionAnswered&&(K.add(R.toolCall.id),oa(R,o,Ie.composerOverlay));return}}else if(Ae){let de=r.find(ot=>typeof ot.renderApproval=="function")??s,Vt=Vn.get(R.id)!==pt,Ht=null;if(Vt&&de?.renderApproval){let ot=R.id,Ve=(Ze,kt)=>{let He=gt.current?.getMessages().find(et=>et.id===ot);He?.approval&&(He.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(He.id,Ze):gt.current?.resolveApproval(He.approval,Ze,kt))};Ht=de.renderApproval({message:R,defaultRenderer:()=>Va(R,o),config:o,approve:Ze=>Ve("approved",Ze),deny:Ze=>Ve("denied",Ze)})}if(Vt&&Ht===null)i.querySelector(`#wrapper-${R.id}`)?.removeAttribute("data-preserve-runtime"),Vn.delete(R.id),yt=Va(R,o);else{let ot=document.createElement("div");ot.className="persona-flex",ot.id=`wrapper-${R.id}`,ot.setAttribute("data-wrapper-id",R.id),ot.setAttribute("data-approval-plugin-stub","true"),ot.setAttribute("data-preserve-runtime","true"),y.appendChild(ot),ht.push({messageId:R.id,fingerprint:pt,bubble:Ht});return}}else if(_t)if(R.variant==="reasoning"&&R.reasoning&&_t.renderReasoning){if(!te)return;yt=_t.renderReasoning({message:R,defaultRenderer:()=>dl(R,o),config:o})}else if(R.variant==="tool"&&R.toolCall&&_t.renderToolCall){if(!ge)return;yt=_t.renderToolCall({message:R,defaultRenderer:()=>ul(R,o),config:o})}else _t.renderMessage&&(yt=_t.renderMessage({message:R,defaultRenderer:()=>{let de=cl(R,h,Co,o.messageActions,_e,{loadingIndicatorRenderer:L,widgetConfig:o});return R.role!=="user"&&vl(de,R,o,_),de},config:o}));if(!yt&&$e){let de=pu(R);if(de){let Ct=bo.get(R.id),Vt=Ct!==pt,Ht=o.wrapComponentDirectiveInBubble!==!1&&_n.getOptions(de.component)?.bubbleChrome!==!1,ot=null;if(Vt){let Ve=cu(de,{config:o,message:R,transform:h});if(Ve&&de.component==="PersonaArtifactInline"){let Ze=Ve.hasAttribute("data-artifact-inline")?Ve:Ve.querySelector("[data-artifact-inline]"),kt=Ze?.getAttribute("data-artifact-inline")??"",He=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(kt):kt,et=kt?i.querySelector(`#wrapper-${R.id}`)?.querySelector(`[data-artifact-inline="${He}"]`)??null:null;Ze&&et&&et!==Ze&&gp(et)&&(Ze===Ve?Ve=et:Ze.replaceWith(et))}if(Ve)if(Ht){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${R.id}`,Ze.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let kt=document.createElement("div");kt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",kt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ze.appendChild(kt)}Ze.appendChild(Ve),ot=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-${R.id}`,Ze.setAttribute("data-message-id",R.id),Ze.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let kt=document.createElement("div");kt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",kt.innerHTML=h({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Ze.appendChild(kt)}Ze.appendChild(Ve),ot=Ze}}if(ot||Ct!=null){let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${R.id}`,Ve.setAttribute("data-wrapper-id",R.id),Ve.setAttribute("data-component-directive-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),Ht||Ve.classList.add("persona-w-full"),y.appendChild(Ve),se.push({messageId:R.id,fingerprint:pt,bubble:ot});return}}}if(!yt)if(R.variant==="reasoning"&&R.reasoning){if(!te)return;yt=dl(R,o)}else if(R.variant==="tool"&&R.toolCall){if(!ge)return;yt=ul(R,o)}else if(R.variant==="approval"&&R.approval){if(o.approval===!1)return;yt=Va(R,o)}else{let de=o.layout?.messages;de?.renderUserMessage&&R.role==="user"?yt=de.renderUserMessage({message:R,config:o,streaming:!!R.streaming}):de?.renderAssistantMessage&&R.role==="assistant"?yt=de.renderAssistantMessage({message:R,config:o,streaming:!!R.streaming}):yt=cl(R,h,de,o.messageActions,_e,{loadingIndicatorRenderer:L,widgetConfig:o}),R.role!=="user"&&yt&&vl(yt,R,o,_)}let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${R.id}`,ut.setAttribute("data-wrapper-id",R.id),R.role==="user"&&ut.classList.add("persona-justify-end"),yt?.getAttribute("data-persona-component-directive")==="true"&&ut.classList.add("persona-w-full"),ut.appendChild(yt),Cp(yo,R.id,pt,ut),y.appendChild(ut)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Ae=Oe.getAttribute("data-persona-ask-sheet-for");Ae&&!K.has(Ae)&&nr(Ie.composerOverlay,Ae)}),o.features?.toolCallDisplay?.grouped){let R=[],Oe=[];g.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&ge){Oe.push(Ae);return}Ae.variant==="reasoning"&&!te||(Oe.length>1&&R.push(Oe),Oe=[])}),Oe.length>1&&R.push(Oe),R.forEach((Ae,$e)=>{let St=Ae.map(Ct=>Array.from(y.children).find(Vt=>Vt instanceof HTMLElement&&Vt.getAttribute("data-wrapper-id")===Ct.id)).filter(Ct=>!!Ct);if(St.length<2)return;let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-tool-group-${$e}-${Ae[0].id}`,pt.setAttribute("data-wrapper-id",`tool-group-${$e}-${Ae[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let _t=`Called ${Ae.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Ct=>Ct.toolCall).filter(Ct=>!!Ct),defaultSummary:_t,config:o});X(yt,Co)||(yt.textContent=_t);let ut=document.createElement("div");ut.className="persona-tool-group-stack persona-flex persona-flex-col";let de=o.features?.toolCallDisplay?.groupedMode==="summary";xt.appendChild(yt),de||xt.appendChild(ut),pt.appendChild(xt),St[0].before(pt),St.forEach((Ct,Vt)=>{if(de){Ct.remove();return}let Ht=document.createElement("div");Ht.className="persona-tool-group-item persona-relative",Ht.setAttribute("data-persona-tool-group-item","true"),Vt<St.length-1&&Ht.setAttribute("data-persona-tool-group-connector","true"),Ht.appendChild(Ct),ut.appendChild(Ht)})})}Ap(yo,O);let st=g.some(R=>R.role==="assistant"&&R.streaming),jt=g[g.length-1],Bt=jt?.role==="assistant"&&!jt.streaming&&jt.variant!=="approval";if(hn&&g.some(R=>R.role==="user")&&!st&&!Bt){let R={config:o,streaming:!0,location:"standalone",defaultRenderer:hs},Oe=r.find($e=>$e.renderLoadingIndicator),Ae=null;if(Oe?.renderLoadingIndicator&&(Ae=Oe.renderLoadingIndicator(R)),Ae===null&&o.loadingIndicator?.render&&(Ae=o.loadingIndicator.render(R)),Ae===null&&(Ae=hs()),Ae){let $e=document.createElement("div"),St=o.loadingIndicator?.showBubble!==!1;$e.className=St?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$e.setAttribute("data-typing-indicator","true"),$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",$e.appendChild(Ae);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-typing-indicator",pt.setAttribute("data-wrapper-id","typing-indicator"),pt.appendChild($e),y.appendChild(pt)}}if(!hn&&g.length>0){let R=g[g.length-1],Oe={config:o,lastMessage:R,messageCount:g.length},Ae=r.find(St=>St.renderIdleIndicator),$e=null;if(Ae?.renderIdleIndicator&&($e=Ae.renderIdleIndicator(Oe)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(Oe)),$e){let St=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;St.className=pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),St.setAttribute("data-idle-indicator","true"),St.appendChild($e);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(St),y.appendChild(xt)}}if(Ma(i,y),ce.length>0)for(let{messageId:R,fingerprint:Oe,bubble:Ae}of ce){let $e=i.querySelector(`#wrapper-${R}`);$e&&Ae!==null&&($e.replaceChildren(Ae),$e.setAttribute("data-bubble-fp",Oe),Uo.set(R,Oe))}if(Uo.size>0)for(let R of Uo.keys())O.has(R)||Uo.delete(R);if(se.length>0)for(let{messageId:R,fingerprint:Oe,bubble:Ae}of se){let $e=i.querySelector(`#wrapper-${R}`);$e&&Ae!==null&&($e.replaceChildren(Ae),$e.setAttribute("data-bubble-fp",Oe),bo.set(R,Oe))}if(bo.size>0)for(let R of bo.keys())O.has(R)||bo.delete(R);if(ht.length>0)for(let{messageId:R,fingerprint:Oe,bubble:Ae}of ht){let $e=i.querySelector(`#wrapper-${R}`);$e&&Ae!==null&&($e.replaceChildren(Ae),$e.setAttribute("data-bubble-fp",Oe),Vn.set(R,Oe))}if(Vn.size>0)for(let R of Vn.keys())O.has(R)||Vn.delete(R)},Pr=(i,g,h)=>{Gu(i,g,h),Vl()},Ir=null,Qu=()=>{if(Ir)return;let i=h=>{let y=h.composedPath();y.includes(ke)||it&&y.includes(it)||mt(!1,"user")};Ir=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},lc=()=>{if(!Ir)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ir,!0),Ir=null};qe.push(()=>lc());let Rr=null,Xu=()=>{if(Rr)return;let i=h=>{h.key==="Escape"&&(h.isComposing||mt(!1,"user"))};Rr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},cc=()=>{if(!Rr)return;(t.ownerDocument??document).removeEventListener("keydown",Rr,!0),Rr=null};qe.push(()=>cc());let Wr=!1,dc=new Set,Ju=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Vo=()=>{if(!J())return;let i=Ie.peekBanner,g=Ie.peekTextNode;if(!i||!g)return;if($){i.classList.remove("persona-pill-peek--visible");return}let h=_?.getMessages()??[],y;for(let Bt=h.length-1;Bt>=0;Bt--){let R=h[Bt];if(R.role==="assistant"&&R.content){y=R;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let A=y.content,L=!!y.streaming,X=Ju(),O=Pa(X),K=O.type!=="none"?ur(O.type,X?.plugins):null,re=K?.isAnimating?.(y)===!0,ce=K!==null&&(L||re);ce&&K&&!dc.has(K.name)&&(Wa(K,t),dc.add(K.name));let se=ce&&K?.containerClass?K.containerClass:null,we=g.dataset.personaPeekStreamClass??null;we&&we!==se&&(g.classList.remove(we),delete g.dataset.personaPeekStreamClass),se&&we!==se&&(g.classList.add(se),g.dataset.personaPeekStreamClass=se),ce?(g.style.setProperty("--persona-stream-step",`${O.speed}ms`),g.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ke=ce?Ia(A,O.buffer,K,y,L):A;if(ce&&O.placeholder==="skeleton"&&L&&(!Ke||!Ke.trim())){let Bt=document.createElement("div"),R=ps();R.classList.add("persona-pill-peek__skeleton"),Bt.appendChild(R),Ma(g,Bt)}else{let Bt=Math.max(0,Ke.length-100),R=Ke.length>100?Ke.slice(-100):Ke,Oe=Zn(R);if(!ce||!K){let Ae=Ke.length>100?`\u2026${R}`:R;g.textContent!==Ae&&(g.textContent=Ae)}else{let Ae=Oe;(K.wrap==="char"||K.wrap==="word")&&(Ae=ds(Oe,K.wrap,`peek-${y.id}`,{skipTags:K.skipTags,startIndex:Bt}));let $e=document.createElement("div");if($e.innerHTML=Ae,K.useCaret&&R.length>0){let St=Ra(),pt=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),xt=pt[pt.length-1];xt?.parentNode?xt.parentNode.insertBefore(St,xt.nextSibling):$e.appendChild(St)}Ma(g,$e),K.onAfterRender?.({container:g,bubble:i,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let jt=hn||Wr;i.classList.toggle("persona-pill-peek--visible",jt)};if(J()){let i=Ie.peekBanner;if(i){let y=A=>{A.preventDefault(),A.stopPropagation(),mt(!0,"user")};i.addEventListener("pointerdown",y),qe.push(()=>{i.removeEventListener("pointerdown",y)})}let g=()=>{Wr||(Wr=!0,Vo())},h=()=>{Wr&&(Wr=!1,Vo())};me.addEventListener("pointerenter",g),me.addEventListener("pointerleave",h),qe.push(()=>{me.removeEventListener("pointerenter",g),me.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",g),it.addEventListener("pointerleave",h),qe.push(()=>{it.removeEventListener("pointerenter",g),it.removeEventListener("pointerleave",h)}))}let Yu=i=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",y=g.bottomOffset??"16px",A=g.collapsedMaxWidth,L=g.expandedMaxWidth??"880px",X=g.expandedTopOffset??"5vh",O=g.modalMaxWidth??"880px",K=g.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",se=ke.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",it){let we=it.style;we.bottom=y,we.width=A??""}if(i&&h!=="fullscreen"){if(h==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=O,se.maxWidth=re,se.maxHeight=K,se.height=K;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${y} + ${ce})`,se.top=X,se.width=L,se.maxWidth=re}},Br=()=>{if(!D())return;if(J()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ce=$?"expanded":"collapsed";ke.dataset.state=ce,ke.dataset.expandedSize=re,it&&(it.dataset.state=ce,it.dataset.expandedSize=re),ke.style.removeProperty("display"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Yu($),pe.style.display=$?"flex":"none",Ws(),$?(Qu(),Xu()):(lc(),cc()),Vo();return}let i=Ft(o),g=t.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,A=g.innerWidth<=h,L=y&&A&&T,X=fn(o).reveal;$?(ke.style.removeProperty("display"),ke.style.display=i?"flex":"",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-95","persona-opacity-0"),me.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Ut&&(Ut.style.display="none")):(i?i&&(X==="overlay"||X==="push")&&!L?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),me.classList.remove("persona-scale-100","persona-opacity-100"),me.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":Ut&&(Ut.style.display=i?"none":""))},mt=(i,g="user")=>{if(!D()||$===i)return;let h=$;$=i,Br();let y=(()=>{let L=o.launcher?.sidebarMode??!1,X=t.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,K=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=K,ce=Ft(o)&&O&&re,se=J()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||O&&re&&T||ce||se})();if($&&y){if(!Cn){let L=t.getRootNode(),X=L instanceof ShadowRoot?L.host:t.closest(".persona-host");X&&(Cn=ol(X,o.launcher?.zIndex??zt))}An||(An=rl(t.ownerDocument))}else $||(Cn?.(),Cn=null,An?.(),An=null);$&&(Nr(),ac()||(Xt()==="follow"?Qn(!0):rc()));let A={open:$,source:g,timestamp:Date.now()};$&&!h?l.emit("widget:opened",A):!$&&h&&l.emit("widget:closed",A),l.emit("widget:state",{open:$,launcherEnabled:T,voiceActive:Qe.active,streaming:_.isStreaming()})},gi=i=>{lt(i?"stop":"send"),q&&(q.disabled=i),Hs.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)})},mi=()=>{Qe.active||F&&F.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>mi(),200)});let pc=()=>{Q.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",F.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ie.querySelector("[data-persona-intro-card]");if(i){let h=o.copy?.showWelcomeCard!==!1;i.style.display=h?"":"none",h?(ie.classList.remove("persona-gap-3"),ie.classList.add("persona-gap-6")):(ie.classList.remove("persona-gap-6"),ie.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(ne.textContent=o.copy?.sendButtonLabel??"Send"),F.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',F.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{C(g=>({...g,sessionId:i}))}});let wo=null,Zu=()=>{wo==null&&(wo=setInterval(()=>{let i=ye.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(wo),wo=null;return}let g=Date.now();i.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=aa(g-y))})},100))},hi=(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((X,O)=>hi(X,g[O]));let h=i,y=g,A=Object.keys(h),L=Object.keys(y);return A.length===L.length&&A.every(X=>Object.prototype.hasOwnProperty.call(y,X)&&hi(h[X],y[X]))},uc=i=>{let{content:g,rawContent:h,llmContent:y,...A}=i;return A},yi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Tl(i),ef=(i,g,h)=>{if(i.length!==g.length)return!1;let y=i[h.index],A=g[h.index];return!y||!A||y.id!==h.id||A.id!==h.id?!1:(!Object.is(y.content,A.content)||!Object.is(y.rawContent,A.rawContent)||!Object.is(y.llmContent,A.llmContent))&&yi(y)&&yi(A)&&hi(uc(y),uc(A))},fc=null,qo=null,xo=null,In=null,_s=i=>{fc=i;let g,h;qo=null;for(let A=i.length-1;A>=0;A-=1){let L=i[A];if(!g&&L.role==="user"&&(g=L),!h&&L.role==="assistant"&&(h=L),!qo&&yi(L)&&(qo={index:A,id:L.id}),g&&h&&qo)break}Pr(ye,i,xe),Ji(ye,gn.artifacts,{suppressTransition:hn}),Zu(),oi(i),Qn(!hn),Ku(i),i.length===0&&(Lr(),Mr=!0,ii=!1),!si||Ns?(si=!0,ai=g?.id??null,li=h?.id??null):g&&g.id!==ai?(ai=g.id,Vu(g.id)):h&&h.id!==li&&qu(),h&&(li=h.id);let y=Qe.lastUserMessageId;g&&g.id!==y&&(Qe.lastUserMessageId=g.id,l.emit("user:message",g)),Qe.lastUserMessageWasVoice=!!g?.viaVoice,pi(i),Vo()},bi=()=>{In!==null&&(cancelAnimationFrame(In),In=null);let i=xo;xo=null,i&&_s(i)},gc=()=>{In!==null&&cancelAnimationFrame(In),In=null,xo=null},tf=i=>{let g=xo??fc;if(hn&&g&&qo&&ef(g,i,qo)){xo=i,In===null&&(In=requestAnimationFrame(()=>{In=null;let h=xo;xo=null,h&&_s(h)}));return}if(i.length===0){gc(),_s(i);return}bi(),_s(i)};_=new ga(o,{onMessagesChanged(i){tf(i)},onStatusChanged(i){let g=o.statusIndicator??{};Et(E,(y=>y==="idle"?g.idleText??Rt.idle:y==="connecting"?g.connectingText??Rt.connecting:y==="connected"?g.connectedText??Rt.connected:y==="error"?g.errorText??Rt.error:y==="paused"?g.pausedText??Rt.paused:y==="resuming"?g.resumingText??Rt.resuming:Rt[y])(i),g,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?gc():bi()),hn=i,gi(i),_&&Pr(ye,_.getMessages(),xe),i||Qn(!0),tn(),Nl(i?"Responding\u2026":"Response complete."),Vo()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Rn(),Go();break;case"processing":Rn(),ff();break;case"speaking":Rn(),gf();break;default:i==="idle"&&_.isBargeInActive()?(Rn(),Go(),q?.setAttribute("aria-label","End voice session")):(Qe.active=!1,Rn(),Pn("system"),bn());break}},onArtifactsState(i){gn=i,i.artifacts.length===0&&(_o=!1),Ji(ye,i.artifacts,{suppressTransition:hn}),Ln(),pi()},onReconnect(i){let{executionId:g,lastEventId:h}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:g,after:h}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:h,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:g,after:h})}}),gt.current=_,qe.push(()=>_.cancel());let vi=null;if(_.onReadAloudChange((i,g)=>{Ul=i,jl=g,Vl();let h=i??vi;i&&(vi=i);let y=h?_.getMessages().find(A=>A.id===h)??null:null;l.emit("message:read-aloud",{messageId:h,message:y,state:g,timestamp:Date.now()}),g==="idle"&&(vi=null)}),si=!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)}),(Ce||o.onSSEEvent)&&_.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),je?.processEvent(i,g),Ce?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let mc=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=Ml(i.metadata),M.syncFromMetadata()),i.messages?.length){Ns=!0;try{_.hydrateMessages(i.messages)}finally{Ns=!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(()=>mc()):mc();let hc=()=>{!J()||$||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},nf=(i,g)=>i?g?{refs:[...i.refs,...g.refs],finalize:async()=>{let[h,y]=await Promise.allSettled([i.finalize(),g.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),y.status==="fulfilled"?A.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),my(A)}}:i:g,of=()=>{let g=F.getInlineMessageFields?.();return g&&g.contentSegments.some(y=>y.kind==="mention")?g.contentSegments:void 0},Hr=!1,rf=async i=>{let g=F.value.trim(),h=Tt?.hasAttachments()??!1,y=g?await(Zt?.takeInlineCommand(g)??Promise.resolve(null)):null;if(y?.kind==="action"){F.value="",F.style.height="auto",Dr(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,L=y?.kind==="server"?y.mentions:null,X=nf(A,L),O=y?.kind==="prompt"?y.sendText:g,K=!!A&&A.refs.length>0;if(!O&&!h&&!K&&!L)return;hc();let re;h&&(re=[],re.push(...Tt.getContentParts()),O&&re.push(rr(O)));let ce=y?.kind==="prompt"?void 0:of();F.value="",F.style.height="auto",Dr(),_.sendMessage(O,{contentParts:re,mentions:X??void 0,contentSegments:ce,viaVoice:i?.viaVoice}),h&&Tt.clearAttachments(),A&&Zt?.clear()},wi=async i=>{if(!Hr){Hr=!0;try{await rf(i)}finally{Hr=!1}}},yc=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),je?.reset(),Fe?.update();return}Hr||wi()},sf=()=>o.features?.composerHistory!==!1,xi={...el},Ci=!1,Dr=()=>{xi={...el}},af=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),lf=i=>{if(!F)return;Ci=!0,F.value=i,F.dispatchEvent(new Event("input",{bubbles:!0})),Ci=!1;let g=F.value.length;F.setSelectionRange(g,g)},cf=i=>{Ci||(i.isComposing||Zt?.handleInput(i.inputType??void 0),Dr())},df=i=>{if(F&&!(!i.isComposing&&Zt?.handleKeydown(i))){if(sf()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=F.selectionStart===0&&F.selectionEnd===0,h=bp({direction:i.key==="ArrowUp"?"up":"down",history:af(),currentValue:F.value,atStart:g,state:xi});if(xi=h.state,h.handled){i.preventDefault(),h.value!==void 0&&lf(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(Hr){i.preventDefault();return}Dr(),i.preventDefault(),ne.click()}}},bc=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(pe)&&(_.cancel(),je?.reset(),Fe?.update(),Dr(),i.preventDefault(),i.stopImmediatePropagation())},pf=async i=>{if(o.attachments?.enabled!==!0||!Tt)return;let g=py(i.clipboardData);g.length!==0&&(i.preventDefault(),await Tt.handleFiles(g))},dn=null,Sn=!1,Ko=null,wt=null,vc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$s=(i="user")=>{if(Sn||_.isStreaming())return;let g=vc();if(!g)return;dn=new g;let y=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let A=F.value;dn.onresult=L=>{let X="",O="";for(let re=0;re<L.results.length;re++){let ce=L.results[re],se=ce[0].transcript;ce.isFinal?X+=se+" ":O=se}let K=A+X+O;F.value=K,Ko&&clearTimeout(Ko),(X||O)&&(Ko=window.setTimeout(()=>{F.value.trim()&&dn&&Sn&&(Xn(),wi({viaVoice:!0}))},y))},dn.onerror=L=>{L.error!=="no-speech"&&Xn()},dn.onend=()=>{if(Sn){let L=F.value.trim();L&&L!==A.trim()&&wi({viaVoice:!0}),Xn()}};try{if(dn.start(),Sn=!0,Qe.active=!0,i!=="system"&&(Qe.manuallyDeactivated=!1),Pn(i),bn(),q){let L=o.voiceRecognition??{};wt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let X=L.recordingBackgroundColor,O=L.recordingIconColor,K=L.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let re=q.querySelector("svg");re&&re.setAttribute("stroke",O)}K&&(q.style.borderColor=K),q.setAttribute("aria-label","Stop voice recognition")}}catch{Xn("system")}},Xn=(i="user")=>{if(Sn){if(Sn=!1,Ko&&(clearTimeout(Ko),Ko=null),dn){try{dn.stop()}catch{}dn=null}if(Qe.active=!1,Pn(i),bn(),q){if(q.classList.remove("persona-voice-recording"),wt){q.style.backgroundColor=wt.backgroundColor,q.style.color=wt.color,q.style.borderColor=wt.borderColor;let g=q.querySelector("svg");g&&g.setAttribute("stroke",wt.color||"currentColor"),wt=null}q.setAttribute("aria-label","Start voice recognition")}}},uf=(i,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),y=i?.provider?.type==="runtype",A=i?.provider?.type==="custom";if(!(h||y||A))return null;let X=m("div","persona-send-button-wrapper"),O=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let K=i?.iconName??"mic",re=g?.size??"40px",ce=i?.iconSize??re,se=parseFloat(ce)||24,we=i?.backgroundColor??g?.backgroundColor,Ke=i?.iconColor??g?.textColor;O.style.width=ce,O.style.height=ce,O.style.minWidth=ce,O.style.minHeight=ce,O.style.fontSize="18px",O.style.lineHeight="1",Ke?O.style.color=Ke:O.style.color="var(--persona-text, #111827)";let st=oe(K,se,Ke||"currentColor",1.5);st?O.appendChild(st):O.textContent="\u{1F3A4}",we?O.style.backgroundColor=we:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),X.appendChild(O);let jt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&jt){let R=m("div","persona-send-button-tooltip");R.textContent=jt,X.appendChild(R)}return{micButton:O,micButtonWrapper:X}},Ai=()=>{if(!q||wt)return;let i=o.voiceRecognition??{};wt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Si=(i,g)=>{if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=oe(i,y,g,1.5);A&&q.appendChild(A)},zs=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Go=()=>{if(!q)return;Ai();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,h=i.recordingIconColor,y=i.recordingBorderColor;if(zs(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=q.querySelector("svg");A&&A.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},ff=()=>{if(!q)return;Ai();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),h=i.processingIconName??"loader",y=i.processingIconColor??wt?.color??"",A=i.processingBackgroundColor??wt?.backgroundColor??"",L=i.processingBorderColor??wt?.borderColor??"";zs(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=A,q.style.borderColor=L;let X=y||"currentColor";q.style.color=X,Si(h,X),q.setAttribute("aria-label","Processing voice input"),g==="none"&&(q.style.cursor="default")},gf=()=>{if(!q)return;Ai();let i=o.voiceRecognition??{},g=_.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",y=i.speakingIconName??h,A=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??wt?.color??"":wt?.color??""),L=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),X=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":wt?.borderColor??"");zs(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=L,q.style.borderColor=X;let O=A||"currentColor";q.style.color=O,Si(y,O);let K=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",K),g==="none"&&(q.style.cursor="default"),g==="barge-in"&&q.classList.add("persona-voice-recording")},Rn=()=>{q&&(zs(),wt&&(q.style.backgroundColor=wt.backgroundColor??"",q.style.color=wt.color??"",q.style.borderColor=wt.borderColor??"",Si(wt.iconName,wt.color||"currentColor"),wt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},Us=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),g=_.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()});return}_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Qe.manuallyDeactivated=!_.isVoiceActive(),bn(),Pn("user"),_.isVoiceActive()?Go():Rn()});return}if(Sn){let i=F.value.trim();Qe.manuallyDeactivated=!0,bn(),Xn("user"),i&&(F.value="",F.style.height="auto",_.sendMessage(i))}else Qe.manuallyDeactivated=!1,bn(),$s("user")};Ol=Us,q&&(q.addEventListener("click",Us),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Rn()):Xn("system"),q&&q.removeEventListener("click",Us)}));let mf=l.on("assistant:complete",()=>{Yl&&(Qe.active||Qe.manuallyDeactivated||Yl==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Pn("auto"),_.isVoiceActive()&&Go()}):$s("auto"))},600))});qe.push(mf);let hf=l.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});qe.push(hf);let wc=()=>{mt(!$,"user")},Ot=null,Ut=null;if(T&&!J()){let{instance:i,element:g}=al({config:o,plugins:r,onToggle:wc});Ot=i,i||(Ut=g)}Ot?t.appendChild(Ot.element):Ut&&t.appendChild(Ut),Br(),oi(),pc(),gi(_.isStreaming()),ac()||(Xt()==="follow"?Qn(!0):rc()),Ou(),z&&(!T||J()?setTimeout(()=>mi(),0):$&&setTimeout(()=>mi(),200));let Nr=()=>{if(J()){Oo(),Br();return}let i=Ft(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),y=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640,X=y.innerWidth<=L,O=A&&X&&T;try{if(O){Cr(),Ar=Rs();return}let K=!1;V&&(V=!1,Cr(),K=!0);let re=Rs();if(!K&&re!==Ar&&(Cr(),K=!0),Ar=re,K&&ti(),!T&&!i){me.style.height="",me.style.width="";return}if(!g&&!i){let se=o?.launcher?.width??o?.launcherWidth??On;me.style.width=se,me.style.maxWidth=se}if(Is(),!h){let ce=y.innerHeight,se=64,we=o.launcher?.heightOffset??0,Ke=Math.max(200,ce-se),ht=Math.min(640,Ke),st=Math.max(200,ht-we);me.style.height=`${st}px`}}finally{if(Oo(),Br(),$&&T){let re=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ce=o.launcher?.sidebarMode??!1,se=o.launcher?.mobileFullscreen??!0,we=Ft(o)&&se&&re,Ke=ce||se&&re&&T||we;if(Ke&&!An){let ht=t.getRootNode(),st=ht instanceof ShadowRoot?ht.host:t.closest(".persona-host");st&&!Cn&&(Cn=ol(st,o.launcher?.zIndex??zt)),An=rl(t.ownerDocument)}else Ke||(Cn?.(),Cn=null,An?.(),An=null)}}};Nr();let xc=t.ownerDocument.defaultView??window;if(xc.addEventListener("resize",Nr),qe.push(()=>xc.removeEventListener("resize",Nr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Oo()});i.observe(j),qe.push(()=>i.disconnect())}ln=ie.scrollTop;let Cc=En(ie),yf=()=>{let i=ie.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ie.ownerDocument.getSelection()},Ti=()=>Sp(yf(),ie),Ac=()=>{let i=ie.scrollTop,g=En(ie),h=g<Cc;if(Cc=g,!$n()){ln=i,tn();return}let{action:y,nextLastScrollTop:A}=ka({following:en.isFollowing(),currentScrollTop:i,lastScrollTop:ln,nearBottom:io(ie,Fs),userScrollThreshold:Nu,isAutoScrolling:cn||Ds||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=A,y==="resume"){Ti()||Gn();return}y==="pause"&&kr()};if(ie.addEventListener("scroll",Ac,{passive:!0}),qe.push(()=>ie.removeEventListener("scroll",Ac)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ju()});i.observe(ye),i.observe(ie),qe.push(()=>i.disconnect())}let Sc=()=>{$n()&&en.isFollowing()&&Ti()&&kr()},Tc=ie.ownerDocument;Tc.addEventListener("selectionchange",Sc),qe.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let bf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Mc=i=>{Bl()&&$n()&&en.isFollowing()&&bf.has(i.key)&&kr()},Ec=i=>{if(!Bl()||!$n()||!en.isFollowing())return;let g=i.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&kr()};ie.addEventListener("keydown",Mc),ie.addEventListener("focusin",Ec),qe.push(()=>{ie.removeEventListener("keydown",Mc),ie.removeEventListener("focusin",Ec)});let kc=i=>{if(!$n())return;let g=La({following:en.isFollowing(),deltaY:i.deltaY,nearBottom:io(ie,Fs),resumeWhenNearBottom:!0});g==="pause"?kr():g==="resume"&&!Ti()&&Gn()};ie.addEventListener("wheel",kc,{passive:!0}),qe.push(()=>ie.removeEventListener("wheel",kc)),Pt.addEventListener("click",()=>{Lr(),ie.scrollTop=ie.scrollHeight,ln=ie.scrollTop,Gn(),Qn(!0),tn()}),qe.push(()=>Pt.remove()),qe.push(()=>{tc(),Lr()});let Lc=()=>{S&&(ho&&(S.removeEventListener("click",ho),ho=null),D()?(S.style.display="",ho=()=>{mt(!1,"user")},S.addEventListener("click",ho)):S.style.display="none")};Lc(),(()=>{let{clearChatButton:i}=Ie;i&&i.addEventListener("click",()=>{_.clearMessages(),yo.clear(),Gn(),nr(Ie.composerOverlay);try{localStorage.removeItem(hr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&di(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Ce?.clear(),je?.reset(),Fe?.update()})})(),Se&&Se.addEventListener("submit",yc);let Pc=[["keydown",df],["input",cf],["paste",pf],["focus",Ru]],Ic=i=>{if(i)for(let[g,h]of Pc)i.addEventListener(g,h)},Rc=i=>{if(i)for(let[g,h]of Pc)i.removeEventListener(g,h)};Ic(F),Zt?.onComposerSwap((i,g)=>{Rc(g),F=i,Ic(i)});let Wc=t.ownerDocument??document;Wc.addEventListener("keydown",bc,!0);let Bc="persona-attachment-drop-active",Fr=0,Mi=()=>{Fr=0,pe.classList.remove(Bc)},Qo=()=>o.attachments?.enabled===!0&&Tt!==null,Hc=i=>{!Ka(i.dataTransfer)||!Qo()||(Fr++,Fr===1&&pe.classList.add(Bc))},Dc=i=>{!Ka(i.dataTransfer)||!Qo()||(Fr--,Fr<=0&&Mi())},Nc=i=>{!Ka(i.dataTransfer)||!Qo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Fc=i=>{if(!Ka(i.dataTransfer)||!Qo())return;i.preventDefault(),i.stopPropagation(),Mi();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Tt.handleFiles(g)},Jn=!0;pe.addEventListener("dragenter",Hc,Jn),pe.addEventListener("dragleave",Dc,Jn),t.addEventListener("dragover",Nc,Jn),t.addEventListener("drop",Fc,Jn);let js=t.ownerDocument,Oc=i=>{Qo()&&i.preventDefault()},_c=i=>{Qo()&&i.preventDefault()};js.addEventListener("dragover",Oc),js.addEventListener("drop",_c),qe.push(()=>{Se&&Se.removeEventListener("submit",yc),Rc(F),Wc.removeEventListener("keydown",bc,!0),Zt?.destroy()}),qe.push(()=>{pe.removeEventListener("dragenter",Hc,Jn),pe.removeEventListener("dragleave",Dc,Jn),t.removeEventListener("dragover",Nc,Jn),t.removeEventListener("drop",Fc,Jn),js.removeEventListener("dragover",Oc),js.removeEventListener("drop",_c),Mi()}),qe.push(()=>{_.cancel()}),Ot?qe.push(()=>{Ot?.destroy()}):Ut&&qe.push(()=>{Ut?.remove()});let It={update(i){let g=o.toolCall,h=o.messageActions,y=o.layout?.messages,A=o.colorScheme,L=o.loadingIndicator,X=o.iterationDisplay,O=o.features?.showReasoning,K=o.features?.showToolCalls,re=o.features?.toolCallDisplay,ce=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type;o={...o,...i},Ws(),rs(t,o),ws(t,o),xs(t,o),Ln(),o.colorScheme!==A&&Jl();let we=xl.getForInstance(o.plugins);r.length=0,r.push(...we),T=o.launcher?.enabled??!0,I=o.launcher?.autoExpand??!1,te=o.features?.showReasoning??!0,ge=o.features?.showToolCalls??!0,le=o.features?.scrollToBottom??{};let Ke=Xt();Z=o.features?.scrollBehavior??{},Ke!==Xt()&&(Lr(),Gn()),Fl(),tn();let ht=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!ht){if(Ce||(ue=new bs(ve),Ce=new ys(Te,ue),je=je??new vs,ue.open().then(()=>Ce?.restore()).catch(()=>{}),_.setSSEEventCallback((ee,nt)=>{o.onSSEEvent?.(ee,nt),je?.processEvent(ee,nt),Ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(nt)})})),!rt&&B){let ee=o.features?.eventStream?.classNames,nt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");rt=m("button",nt),rt.style.width="28px",rt.style.height="28px",rt.style.color=Gt.actionIconColor,rt.type="button",rt.setAttribute("aria-label","Event Stream"),rt.title="Event Stream";let At=oe("activity","18px","currentColor",1.5);At&&rt.appendChild(At);let Ge=Ie.clearChatButtonWrapper,ct=Ie.closeButtonWrapper,$t=Ge||ct;$t&&$t.parentNode===B?B.insertBefore(rt,$t):B.appendChild(rt),rt.addEventListener("click",()=>{Pe?wr():Ja()})}}else!Y&&ht&&(wr(),rt&&(rt.remove(),rt=null),Ce?.clear(),ue?.destroy(),Ce=null,ue=null,je?.reset(),je=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Ut&&(Ut.remove(),Ut=null),o.launcher?.enabled!==!1&&!Ot&&!Ut){let{instance:ee,element:nt}=al({config:o,plugins:r,onToggle:wc});Ot=ee,ee||(Ut=nt),t.appendChild(nt)}Ot&&Ot.update(o),W&&o.launcher?.title!==void 0&&(W.textContent=o.launcher.title),G&&o.launcher?.subtitle!==void 0&&(G.textContent=o.launcher.subtitle);let st=o.layout?.header;if(st?.layout!==U&&B){let ee=st?Da(o,st,{showClose:D(),onClose:()=>mt(!1,"user")}):Ho({config:o,showClose:D(),onClose:()=>mt(!1,"user")});ft.replaceHeader(ee),B=ft.header.element,k=ft.header.iconHolder,W=ft.header.headerTitle,G=ft.header.headerSubtitle,S=ft.header.closeButton,U=st?.layout}else if(st&&(k&&(k.style.display=st.showIcon===!1?"none":""),W&&(W.style.display=st.showTitle===!1?"none":""),G&&(G.style.display=st.showSubtitle===!1?"none":""),S&&(S.style.display=st.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let ee=st.showClearChat;if(ee!==void 0){Ie.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:nt}=Ie;nt&&!nt.classList.contains("persona-absolute")&&(ee?nt.classList.remove("persona-ml-auto"):nt.classList.add("persona-ml-auto"))}}let Bt=o.layout?.showHeader!==!1;B&&(B.style.display=Bt?"":"none");let R=o.layout?.showFooter!==!1;j&&(j.style.display=R?"":"none"),Oo(),tn(),T!==x?T?mt(I,"auto"):($=!0,Br()):I!==N&&mt(I,"auto"),N=I,x=T,Nr(),Lc();let $e=JSON.stringify(i.toolCall)!==JSON.stringify(g),St=JSON.stringify(o.messageActions)!==JSON.stringify(h),pt=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),xt=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,yt=o.iterationDisplay!==X,_t=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(K??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ce);($e||St||pt||xt||yt||_t)&&_&&(ri++,Pr(ye,_.getMessages(),xe));let ut=o.features?.streamAnimation?.type;if(ut!==se&&ut&&ut!=="none"){let ee=ur(ut,o.features?.streamAnimation?.plugins);ee&&Wa(ee,t)}let de=o.launcher??{},Ct=de.headerIconHidden??!1,Vt=o.layout?.header?.showIcon,Ht=Ct||Vt===!1,ot=de.headerIconName,Ve=de.headerIconSize??"48px";if(k){let ee=pe.querySelector(".persona-border-b-persona-divider"),nt=ee?.querySelector(".persona-flex-col");if(Ht)k.style.display="none",ee&&nt&&!ee.contains(nt)&&ee.insertBefore(nt,ee.firstChild);else{if(k.style.display="",k.style.height=Ve,k.style.width=Ve,ee&&nt&&(ee.contains(k)?k.nextSibling!==nt&&(k.remove(),ee.insertBefore(k,nt)):ee.insertBefore(k,nt)),ot){let Ge=parseFloat(Ve)||24,ct=oe(ot,Ge*.6,"currentColor",1);ct?k.replaceChildren(ct):k.textContent=de.agentIconText??"\u{1F4AC}"}else if(de.iconUrl){let Ge=k.querySelector("img");if(Ge)Ge.src=de.iconUrl,Ge.style.height=Ve,Ge.style.width=Ve;else{let ct=document.createElement("img");ct.src=de.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=Ve,ct.style.width=Ve,k.replaceChildren(ct)}}else{let Ge=k.querySelector("svg"),ct=k.querySelector("img");(Ge||ct)&&k.replaceChildren(),k.textContent=de.agentIconText??"\u{1F4AC}"}let At=k.querySelector("img");At&&(At.style.height=Ve,At.style.width=Ve)}}let Ze=o.layout?.header?.showTitle,kt=o.layout?.header?.showSubtitle;if(W&&(W.style.display=Ze===!1?"none":""),G&&(G.style.display=kt===!1?"none":""),S){o.layout?.header?.showCloseButton===!1?S.style.display="none":S.style.display="";let nt=de.closeButtonSize??"32px",At=de.closeButtonPlacement??"inline";S.style.height=nt,S.style.width=nt;let{closeButtonWrapper:Ge}=Ie,ct=At==="top-right",$t=Ge?.classList.contains("persona-absolute");if(Ge&&ct!==$t)if(Ge.remove(),ct)Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",pe.style.position="relative",pe.appendChild(Ge);else{let Ue=de.clearChat?.placement??"inline",Nt=de.clearChat?.enabled??!0;Ge.className=Nt&&Ue==="inline"?"":"persona-ml-auto";let Yt=pe.querySelector(".persona-border-b-persona-divider");Yt&&Yt.appendChild(Ge)}if(S.style.color=de.closeButtonColor||Gt.actionIconColor,de.closeButtonBackgroundColor?(S.style.backgroundColor=de.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),de.closeButtonBorderWidth||de.closeButtonBorderColor){let Ue=de.closeButtonBorderWidth||"0px",Nt=de.closeButtonBorderColor||"transparent";S.style.border=`${Ue} solid ${Nt}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");de.closeButtonBorderRadius?(S.style.borderRadius=de.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),de.closeButtonPaddingX?(S.style.paddingLeft=de.closeButtonPaddingX,S.style.paddingRight=de.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),de.closeButtonPaddingY?(S.style.paddingTop=de.closeButtonPaddingY,S.style.paddingBottom=de.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let on=de.closeButtonIconName??"x",vn=de.closeButtonIconText??"\xD7";S.innerHTML="";let qt=oe(on,"28px","currentColor",1);qt?S.appendChild(qt):S.textContent=vn;let Mt=de.closeButtonTooltipText??"Close chat",rn=de.closeButtonShowTooltip??!0;if(S.setAttribute("aria-label",Mt),Ge&&(Ge._cleanupTooltip&&(Ge._cleanupTooltip(),delete Ge._cleanupTooltip),rn&&Mt)){let Ue=null,Nt=()=>{if(Ue||!S)return;let Mo=S.ownerDocument,zr=Mo.body;if(!zr)return;Ue=Tn(Mo,"div","persona-clear-chat-tooltip"),Ue.textContent=Mt;let Ur=Tn(Mo,"div");Ur.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Ur);let Eo=S.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(so),Ue.style.left=`${Eo.left+Eo.width/2}px`,Ue.style.top=`${Eo.top-8}px`,Ue.style.transform="translate(-50%, -100%)",zr.appendChild(Ue)},Yt=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};Ge.addEventListener("mouseenter",Nt),Ge.addEventListener("mouseleave",Yt),S.addEventListener("focus",Nt),S.addEventListener("blur",Yt),Ge._cleanupTooltip=()=>{Yt(),Ge&&(Ge.removeEventListener("mouseenter",Nt),Ge.removeEventListener("mouseleave",Yt)),S&&(S.removeEventListener("focus",Nt),S.removeEventListener("blur",Yt))}}}let{clearChatButton:He,clearChatButtonWrapper:et}=Ie;if(He){let ee=de.clearChat??{},nt=ee.enabled??!0,At=o.layout?.header?.showClearChat,Ge=At!==void 0?At:nt,ct=ee.placement??"inline";if(et){et.style.display=Ge?"":"none";let{closeButtonWrapper:$t}=Ie;!J()&&$t&&!$t.classList.contains("persona-absolute")&&(Ge?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let on=ct==="top-right",vn=et.classList.contains("persona-absolute");if(!J()&&on!==vn&&Ge){if(et.remove(),on)et.className="persona-absolute persona-top-4 persona-z-50",et.style.right="48px",pe.style.position="relative",pe.appendChild(et);else{et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",et.style.right="";let Mt=pe.querySelector(".persona-border-b-persona-divider"),rn=Ie.closeButtonWrapper;Mt&&rn&&rn.parentElement===Mt?Mt.insertBefore(et,rn):Mt&&Mt.appendChild(et)}let qt=Ie.closeButtonWrapper;qt&&!qt.classList.contains("persona-absolute")&&(on?qt.classList.add("persona-ml-auto"):qt.classList.remove("persona-ml-auto"))}}if(Ge){if(!J()){let Ue=ee.size??"32px";He.style.height=Ue,He.style.width=Ue}let $t=ee.iconName??"refresh-cw",on=ee.iconColor??"";He.style.color=on||Gt.actionIconColor,He.innerHTML="";let vn=J()?"14px":"20px",qt=oe($t,vn,"currentColor",2);if(qt&&He.appendChild(qt),ee.backgroundColor?(He.style.backgroundColor=ee.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let Ue=ee.borderWidth||"0px",Nt=ee.borderColor||"transparent";He.style.border=`${Ue} solid ${Nt}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");ee.borderRadius?(He.style.borderRadius=ee.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),ee.paddingX?(He.style.paddingLeft=ee.paddingX,He.style.paddingRight=ee.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),ee.paddingY?(He.style.paddingTop=ee.paddingY,He.style.paddingBottom=ee.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Mt=ee.tooltipText??"Clear chat",rn=ee.showTooltip??!0;if(He.setAttribute("aria-label",Mt),et&&(et._cleanupTooltip&&(et._cleanupTooltip(),delete et._cleanupTooltip),rn&&Mt)){let Ue=null,Nt=()=>{if(Ue||!He)return;let Mo=He.ownerDocument,zr=Mo.body;if(!zr)return;Ue=Tn(Mo,"div","persona-clear-chat-tooltip"),Ue.textContent=Mt;let Ur=Tn(Mo,"div");Ur.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Ur);let Eo=He.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(so),Ue.style.left=`${Eo.left+Eo.width/2}px`,Ue.style.top=`${Eo.top-8}px`,Ue.style.transform="translate(-50%, -100%)",zr.appendChild(Ue)},Yt=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};et.addEventListener("mouseenter",Nt),et.addEventListener("mouseleave",Yt),He.addEventListener("focus",Nt),He.addEventListener("blur",Yt),et._cleanupTooltip=()=>{Yt(),et&&(et.removeEventListener("mouseenter",Nt),et.removeEventListener("mouseleave",Yt)),He&&(He.removeEventListener("focus",Nt),He.removeEventListener("blur",Yt))}}}}let nn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Al],Ao=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Cs.message,Cs.messageAndClick];M=Sl({parsers:nn,handlers:Ao,getSessionMetadata:b,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),xe=mu(o,M,Ee),_.updateConfig(o),Pr(ye,_.getMessages(),xe),oi(),pc(),gi(_.isStreaming());let $c=o.voiceRecognition?.enabled===!0,Vs=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if($c&&(Vs||Lt))if(!q||!ze){let ee=uf(o.voiceRecognition,o.sendButton);ee&&(q=ee.micButton,ze=ee.micButtonWrapper,tt.insertBefore(ze,De),q.addEventListener("click",Us),q.disabled=_.isStreaming())}else{let ee=o.voiceRecognition??{},nt=o.sendButton??{},At=ee.iconName??"mic",Ge=nt.size??"40px",ct=ee.iconSize??Ge,$t=parseFloat(ct)||24;q.style.width=ct,q.style.height=ct,q.style.minWidth=ct,q.style.minHeight=ct;let on=ee.iconColor??nt.textColor??"currentColor";q.innerHTML="";let vn=oe(At,$t,on,2);vn?q.appendChild(vn):q.textContent="\u{1F3A4}";let qt=ee.backgroundColor??nt.backgroundColor;qt?q.style.backgroundColor=qt:q.style.backgroundColor="",on?q.style.color=on:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Mt=ze?.querySelector(".persona-send-button-tooltip"),rn=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&rn)if(Mt)Mt.textContent=rn,Mt.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=rn,ze?.insertBefore(Nt,q)}else Mt&&(Mt.style.display="none");ze.style.display="",q.disabled=_.isStreaming()}else q&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Sn&&Xn());if(o.attachments?.enabled===!0)if(!We||!Re){let ee=o.attachments??{},At=(o.sendButton??{}).size??"40px";Je||(Je=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Je.style.display="none",Se.insertBefore(Je,F)),Le||(Le=document.createElement("input"),Le.type="file",Le.accept=(ee.allowedTypes??Fn).join(","),Le.multiple=(ee.maxFiles??4)>1,Le.style.display="none",Le.setAttribute("aria-label","Attach files"),Se.insertBefore(Le,F)),We=m("div","persona-send-button-wrapper"),Re=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Re.type="button",Re.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ge=ee.buttonIconName??"paperclip",ct=At,$t=parseFloat(ct)||40,on=Math.round($t*.6);Re.style.width=ct,Re.style.height=ct,Re.style.minWidth=ct,Re.style.minHeight=ct,Re.style.fontSize="18px",Re.style.lineHeight="1";let vn=oe(Ge,on,"currentColor",1.5);vn?Re.appendChild(vn):Re.textContent="\u{1F4CE}",Re.addEventListener("click",rn=>{rn.preventDefault(),Le?.click()}),We.appendChild(Re);let qt=ee.buttonTooltipText??"Attach file",Mt=m("div","persona-send-button-tooltip");Mt.textContent=qt,We.appendChild(Mt),Me?Me.append(We):Se.appendChild(We),!Tt&&Le&&Je&&(Tt=ts.fromConfig(ee),Tt.setPreviewsContainer(Je),Le.addEventListener("change",async()=>{Tt&&Le?.files&&(await Tt.handleFileSelect(Le.files),Le.value="")})),pe.querySelector(".persona-attachment-drop-overlay")||pe.appendChild(hu(ee.dropOverlay))}else{We.style.display="";let ee=o.attachments??{};Le&&(Le.accept=(ee.allowedTypes??Fn).join(","),Le.multiple=(ee.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else We&&(We.style.display="none"),Tt&&Tt.clearAttachments(),pe.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},Or=Dt.useIcon??!1,Ks=Dt.iconText??"\u2191",Xo=Dt.iconName,_r=Dt.tooltipText??"Send message",Ei=Dt.showTooltip??!1,So=Dt.size??"40px",Wn=Dt.backgroundColor,To=Dt.textColor;if(Or){if(ne.style.width=So,ne.style.height=So,ne.style.minWidth=So,ne.style.minHeight=So,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.innerHTML="",To?ne.style.color=To:ne.style.color="var(--persona-button-primary-fg, #ffffff)",Xo){let ee=parseFloat(So)||24,nt=To?.trim()||"currentColor",At=oe(Xo,ee,nt,2);At?ne.appendChild(At):ne.textContent=Ks}else ne.textContent=Ks;ne.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ne.style.backgroundColor=Wn,ne.classList.remove("persona-bg-persona-primary")):(ne.style.backgroundColor="",ne.classList.add("persona-bg-persona-primary"))}else ne.textContent=o.copy?.sendButtonLabel??"Send",ne.style.width="",ne.style.height="",ne.style.minWidth="",ne.style.minHeight="",ne.style.fontSize="",ne.style.lineHeight="",ne.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Wn?(ne.style.backgroundColor=Wn,ne.classList.remove("persona-bg-persona-accent")):ne.classList.add("persona-bg-persona-accent"),To?ne.style.color=To:ne.classList.add("persona-text-white");Dt.borderWidth?(ne.style.borderWidth=Dt.borderWidth,ne.style.borderStyle="solid"):(ne.style.borderWidth="",ne.style.borderStyle=""),Dt.borderColor?ne.style.borderColor=Dt.borderColor:ne.style.borderColor="",Dt.paddingX?(ne.style.paddingLeft=Dt.paddingX,ne.style.paddingRight=Dt.paddingX):(ne.style.paddingLeft="",ne.style.paddingRight=""),Dt.paddingY?(ne.style.paddingTop=Dt.paddingY,ne.style.paddingBottom=Dt.paddingY):(ne.style.paddingTop="",ne.style.paddingBottom="");let $r=De?.querySelector(".persona-send-button-tooltip");if(Ei&&_r)if($r)$r.textContent=_r,$r.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=_r,De?.insertBefore(ee,ne)}else $r&&($r.style.display="none");let Gs=o.layout?.contentMaxWidth??(J()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Gs?(ye.style.maxWidth=Gs,ye.style.marginLeft="auto",ye.style.marginRight="auto",ye.style.width="100%",Se&&(Se.style.maxWidth=Gs,Se.style.marginLeft="auto",Se.style.marginRight="auto"),bt&&(bt.style.maxWidth=Gs,bt.style.marginLeft="auto",bt.style.marginRight="auto")):(ye.style.maxWidth="",ye.style.marginLeft="",ye.style.marginRight="",ye.style.width="",Se&&(Se.style.maxWidth="",Se.style.marginLeft="",Se.style.marginRight=""),bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""));let Yn=o.statusIndicator??{},vf=Yn.visible??!0;if(E.style.display=vf?"":"none",_){let ee=_.getStatus();Et(E,(At=>At==="idle"?Yn.idleText??Rt.idle:At==="connecting"?Yn.connectingText??Rt.connecting:At==="connected"?Yn.connectedText??Rt.connected:At==="error"?Yn.errorText??Rt.error:Rt[At])(ee),Yn,ee)}E.classList.remove("persona-text-left","persona-text-center","persona-text-right");let wf=Yn.align==="left"?"persona-text-left":Yn.align==="center"?"persona-text-center":"persona-text-right";E.classList.add(wf)},open(){D()&&mt(!0,"api")},close(){D()&&mt(!1,"api")},toggle(){D()&&mt(!$,"api")},reconnect(){_.reconnectNow()},clearChat(){kn=!1,_.clearMessages(),yo.clear(),Gn();try{localStorage.removeItem(hr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==hr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&di(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Ce?.clear(),je?.reset(),Fe?.update()},setMessage(i){return!F||_.isStreaming()?!1:(!$&&D()&&mt(!0,"system"),F.value=i,F.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let g=i?.trim()||F.value.trim();return g?(!$&&D()&&mt(!0,"system"),F.value="",F.style.height="auto",_.sendMessage(g),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!$&&D()&&mt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Pn("user"),_.isVoiceActive()&&Go()})),!0):Sn?!0:vc()?(!$&&D()&&mt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),$s("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()}),!0):!1:Sn?(Qe.manuallyDeactivated=!0,bn(),Xn("user"),!0):!1},injectMessage(i){return!$&&D()&&mt(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!$&&D()&&mt(!0,"system");let g=_.injectAssistantMessage(i);return fe&&(fe=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),g},injectUserMessage(i){return!$&&D()&&mt(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!$&&D()&&mt(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!$&&D()&&mt(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!$&&D()&&mt(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!$&&D()&&mt(!0,"system"),_.injectTestEvent(i)},async connectStream(i,g){return _.connectStream(i,g)},__pushEventStreamEvent(i){Ce&&(je?.processEvent(i.type,i.payload),Ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Y||!Ce||Ja()},hideEventStream(){Pe&&wr()},isEventStreamVisible(){return Pe},showArtifacts(){Qt(o)&&(kn=!1,_o=!0,Ln(),Ye?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(kn=!0,Ln())},upsertArtifact(i){return Qt(o)?(ko(o.features?.artifacts,i.artifactType)==="panel"&&(kn=!1,_o=!0),_.upsertArtifact(i)):null},selectArtifact(i){Qt(o)&&_.selectArtifact(i)},clearArtifacts(){Qt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return T&&!$&&!J()||!F?!1:(F.focus(),!0)},async resolveApproval(i,g,h){let A=_.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!A?.approval)throw new Error(`Approval not found: ${i}`);if(A.approval.toolType==="webmcp"){_.resolveWebMcpApproval(A.id,g);return}return _.resolveApproval(A.approval,g,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){C(i)},on(i,g){return l.on(i,g)},off(i,g){l.off(i,g)},isOpen(){return D()&&$},isVoiceActive(){return Qe.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:D()&&$,launcherEnabled:T,voiceActive:Qe.active,streaming:_.isStreaming()}},showCSATFeedback(i){!$&&D()&&mt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let h=uu({onSubmit:async(y,A)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,A),i?.onSubmit?.(y,A)},onDismiss:i?.onDismiss,...i});ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!$&&D()&&mt(!0,"system");let g=ye.querySelector(".persona-feedback-container");g&&g.remove();let h=fu({onSubmit:async(y,A)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,A),i?.onSubmit?.(y,A)},onDismiss:i?.onDismiss,...i});ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return _.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return _.submitNPSFeedback(i,g)},destroy(){bi(),wo!=null&&(clearInterval(wo),wo=null),qe.forEach(i=>i()),ke.remove(),it?.remove(),Ot?.destroy(),Ut?.remove(),ho&&S.removeEventListener("click",ho)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:h=>h?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=g,qe.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=O=>{let K=O.detail;(!K?.instanceId||K.instanceId===i)&&It.focusInput()};if(window.addEventListener("persona:focusInput",g),qe.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let O=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&It.showEventStream()},K=re=>{let ce=re.detail;(!ce?.instanceId||ce.instanceId===i)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",K),qe.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",K)})}let h=O=>{let K=O.detail;(!K?.instanceId||K.instanceId===i)&&It.showArtifacts()},y=O=>{let K=O.detail;(!K?.instanceId||K.instanceId===i)&&It.hideArtifacts()},A=O=>{let K=O.detail;K?.instanceId&&K.instanceId!==i||K?.artifact&&It.upsertArtifact(K.artifact)},L=O=>{let K=O.detail;K?.instanceId&&K.instanceId!==i||typeof K?.id=="string"&&It.selectArtifact(K.id)},X=O=>{let K=O.detail;(!K?.instanceId||K.instanceId===i)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",X),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",X)})}let pn=uy(o.persistState);if(pn&&D()){let i=fy(pn.storage),g=`${pn.keyPrefix}widget-open`,h=`${pn.keyPrefix}widget-voice`,y=`${pn.keyPrefix}widget-voice-mode`;if(i){let A=pn.persist?.openState&&i.getItem(g)==="true",L=pn.persist?.voiceState&&i.getItem(h)==="true",X=pn.persist?.voiceState&&i.getItem(y)==="true";if(A&&setTimeout(()=>{It.open(),setTimeout(()=>{if(L||X)It.startVoiceRecognition();else if(pn.persist?.focusInput){let O=t.querySelector("textarea");O&&O.focus()}},100)},0),pn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(g,"true")}),l.on("widget:closed",()=>{i.setItem(g,"false")})),pn.persist?.voiceState&&(l.on("voice:state",O=>{i.setItem(h,O.active?"true":"false")}),l.on("user:message",O=>{i.setItem(y,O.viaVoice?"true":"false")})),pn.clearOnChatClear){let O=()=>{i.removeItem(g),i.removeItem(h),i.removeItem(y)},K=()=>O();window.addEventListener("persona:clear-chat",K),qe.push(()=>{window.removeEventListener("persona:clear-chat",K)})}}}if(w&&D()&&setTimeout(()=>{It.open()},0),Vo(),!Du){let i=Xs(()=>{_&&(ri++,yo.clear(),Pr(ye,_.getMessages(),xe))});qe.push(i)}return It};var bu=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},hy=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},yy=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},by=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},vu=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},Pl=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},wu=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Pl(t)},El=t=>{t.style.transition=""},kl=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Ll=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Ga=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},vy=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},wy=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},xy=t=>{let e=ir(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Kt(e,r)??r;return{inset:o(n?.inset,ha),canvasBackground:o(n?.canvasBackground,ya)}},xu=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},Cy=(t,e,n,o,r,s,a,l)=>{let p=fn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";vy(t,e,n,o,d),wy(t,e,n,o,p.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,P=f!=null?f.innerWidth<=C:!1;if(b&&P&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),kl(e),El(o),wu(o),Ll(n),Ga(r,o),xu(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),wu(o),hy(o,p.maxHeight),xu(o,c&&a,u,w),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",kl(e),El(o),Ll(n),Ga(r,o);let M=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",I=a?"translateX(0)":T;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=I,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",El(o),Pl(o),Ga(r,o);let M=bu(p.width,t.clientWidth),T=Math.max(0,t.clientWidth),I=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${T+M}px`,e.style.transition=I,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",kl(e),Pl(o),Ll(n),Ga(r,o);let M=p.reveal==="emerge";M?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let T=a?p.width:"0px",I=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",z=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",yy(o,p.maxHeight),o.style.overflow=M||z?"hidden":"visible",o.style.transition=I,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let N=c?`calc(${bu(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=N,r.style.minWidth=N,r.style.maxWidth=N,r.style.boxSizing="border-box"}}},Ay=(t,e)=>{let n=t.ownerDocument.createElement("div");return vu(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){vu(n,o)},destroy(){n.remove()}}},Sy=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,t),p.appendChild(t);let w=null,f=()=>{w?.disconnect(),w=null},b=null,C=()=>{b=e?.launcher?.detachedPanel===!0?xy(e):null};C();let P=()=>{Cy(a,l,p,d,c,e,u,b)},H=null,M=()=>{H?.(),H=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(H=ba(()=>{C(),P()}))},T=()=>{f(),fn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},I=!1,z=()=>{P(),T(),u&&!I&&a.dataset.personaDockMobileFullscreen!=="true"&&(I=!0,by(a,fn(e)))},N=a.ownerDocument.defaultView,x=()=>{z()};return N?.addEventListener("resize",x),fn(e).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),z(),M(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let V=U.launcherEnabled?U.open:!0;u!==V&&(u=V,z())},updateConfig(U){e=U,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),M()},destroy(){N?.removeEventListener("resize",x),H?.(),H=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},Cu=(t,e)=>Ft(e)?Sy(t,e):Ay(t,e);var As={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Au=.15,Su=1.5,Il="persona-preview-shell-theme",Ty={load:()=>null,save:()=>{},clear:()=>{}},My=["How do I get started?","Pricing & plans","Talk to support"];function Rl(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ey(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Tu(t){let e=Ey(t);return`* { box-sizing: border-box; }
|
|
112
141
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
113
|
-
html { color-scheme: ${
|
|
142
|
+
html { color-scheme: ${t}; }
|
|
114
143
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
115
144
|
.preview-iframe-mock { min-height: 100%; }
|
|
116
145
|
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
|
|
@@ -132,7 +161,7 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
132
161
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
133
162
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
134
163
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
135
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
164
|
+
.preview-workspace-card.short { height: 96px; }`}function Mu(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Il);o||(o=n.createElement("style"),o.id=Il,n.head.appendChild(o)),o.textContent=Tu(e)}var ky=`
|
|
136
165
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
137
166
|
<div class="preview-iframe-chrome">
|
|
138
167
|
<span class="preview-iframe-dot"></span>
|
|
@@ -151,7 +180,7 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
151
180
|
<div class="preview-iframe-line body"></div>
|
|
152
181
|
<div class="preview-iframe-line body"></div>
|
|
153
182
|
</div>
|
|
154
|
-
</div>`,
|
|
183
|
+
</div>`,Ly=`
|
|
155
184
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
156
185
|
<div class="preview-iframe-line hero"></div>
|
|
157
186
|
<div class="preview-iframe-line body"></div>
|
|
@@ -164,9 +193,9 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
164
193
|
<div class="preview-workspace-card short"></div>
|
|
165
194
|
<div class="preview-workspace-card short"></div>
|
|
166
195
|
</div>
|
|
167
|
-
</div>`;function
|
|
168
|
-
${
|
|
169
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${
|
|
196
|
+
</div>`;function Eu(t,e,n,o){let r=`
|
|
197
|
+
${ky}
|
|
198
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
170
199
|
<div class="preview-workspace-shell">
|
|
171
200
|
<div class="preview-workspace-topbar">
|
|
172
201
|
<div class="preview-workspace-topbar-left">
|
|
@@ -176,8 +205,8 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
176
205
|
<span class="preview-workspace-topbar-pill"></span>
|
|
177
206
|
</div>
|
|
178
207
|
<div class="preview-workspace-body">
|
|
179
|
-
<div id="preview-content-${
|
|
180
|
-
${
|
|
208
|
+
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
209
|
+
${Ly}
|
|
181
210
|
</div>
|
|
182
211
|
</div>
|
|
183
212
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -185,16 +214,16 @@ _Details: ${t.message}_`:r}var Ys=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
185
214
|
<head>
|
|
186
215
|
<meta charset="UTF-8">
|
|
187
216
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
188
|
-
<link rel="stylesheet" href="${
|
|
189
|
-
<style id="${
|
|
217
|
+
<link rel="stylesheet" href="${Rl(o)}">
|
|
218
|
+
<style id="${Il}">${Tu(e)}</style>
|
|
190
219
|
</head>
|
|
191
220
|
<body>
|
|
192
|
-
${
|
|
221
|
+
${n?s:r}
|
|
193
222
|
</body>
|
|
194
|
-
</html>`}var
|
|
195
|
-
${
|
|
196
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
197
|
-
</div>`,
|
|
223
|
+
</html>`}var Py=()=>[{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()}],Iy=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Ry(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Iy(e)?[...Py(),...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 Wy(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:My:t.suggestionChips,initialMessages:Ry(e,t,n),storageAdapter:Ty};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function By(t,e){let n=t.theme?Ro(t.theme,{validate:!1}):Ro();return{...dt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function yr(t,e){let n=t.scene??"conversation";return Wy(By(t,e),n,t.appendedMessages??[])}function ku(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:yr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:yr(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:yr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:yr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:yr(t,n),shellMode:n}]}function Hy(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,p=1,d=0;function c(){return n.device??"desktop"}function u(){return n.zoom??l}function w(){let M=getComputedStyle(t),T=parseFloat(M.paddingLeft)+parseFloat(M.paddingRight),I=parseFloat(M.paddingTop)+parseFloat(M.paddingBottom),z=40,N=(n.compareMode??"off")!=="off",x=(t.clientWidth-T-z)/(N?2:1),U=t.clientHeight-I-z;if(x<=0||U<=0)return 1;let V=As[c()]??As.desktop;return Math.min(x/V.w,U/V.h,1)}function f(){l=w();let M=Math.max(Au,Math.min(Su,u()));p=M;let T=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let I of T){let z=I.dataset.device??"desktop",N=As[z]??As.desktop;I.style.width=`${N.w*M}px`,I.style.height=`${N.h*M}px`,z==="mobile"&&(I.style.borderRadius=`${32*M}px`);let x=I.querySelector("iframe");x&&(x.style.width=`${N.w}px`,x.style.height=`${N.h}px`,x.style.transformOrigin="top left",x.style.transition="none",x.style.transform=`scale(${M})`)}n.onScaleChange?.(M)}function b(){n.onBeforeDestroy?.();for(let M of o)M.destroy();for(let M of r)M();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function P(){if(a)return;b();let M=++d,T=ku(n),I=c(),z=(n.compareMode??"off")!=="off",N=(n.scene??"conversation")==="minimized",x=n.widgetCssPath??"/widget-dist/widget.css",U=n.buildSrcdoc??Eu,V=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",J=xe=>`<div class="${V}" data-mount-id="${xe.mountId}" data-device="${I}" data-shell-mode="${xe.shellMode}">
|
|
224
|
+
${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Rl(xe.label)}</span></div>`:""}
|
|
225
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${xe.mountId}"></iframe>
|
|
226
|
+
</div>`,D=z?`<div class="preview-compare-grid">${T.map(xe=>`<div class="preview-compare-cell">${J(xe)}</div>`).join("")}</div>`:`<div class="preview-single">${J(T[0])}</div>`;n.morphContainer?n.morphContainer(t,D):t.innerHTML=D,f();let $=C(),fe=0,he=$.length,Ee=()=>{if(a||M!==d)return;for(let te of $){let ge=te.dataset.mountId;if(!ge||!te.contentDocument)continue;let Y=T.find(ue=>ue.mountId===ge);if(!Y)continue;let le=()=>{},Z=Ft(Y.config),be=Z?(()=>{let ue=te.contentDocument?.getElementById(`preview-content-${ge}`);if(!ue)return null;let Te=Cu(ue,Y.config),Ce=te.contentDocument.createElement("div");Ce.id=ge,Ce.style.height="100%",Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1",Ce.style.minHeight="0",Te.host.appendChild(Ce);let je=()=>Te.syncWidgetState(ve.getState()),Fe=le;return le=()=>{Te.destroy(),Fe()},Ce.__syncDock=je,Ce.__hostLayout=Te,Ce})():te.contentDocument.getElementById(ge);if(!be)continue;let ve=yu(be,Y.config);if(o.push(ve),Z&&be.__syncDock){let ue=be.__syncDock,Te=ve.on("widget:opened",ue),Ce=ve.on("widget:closed",ue),je=le;le=()=>{Te(),Ce(),je()},ue()}r.push(le),N&&ve.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let te of o)te.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
198
227
|
|
|
199
228
|
This is a preview of the artifact sidebar.
|
|
200
229
|
|
|
@@ -202,4 +231,4 @@ This is a preview of the artifact sidebar.
|
|
|
202
231
|
|
|
203
232
|
- Markdown rendering
|
|
204
233
|
- Document toolbar
|
|
205
|
-
- Resizable panes
|
|
234
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:$,controllers:[...o]})};for(let xe of $){let te=xe.dataset.mountId;if(!te)continue;let ge=T.find(Y=>Y.mountId===te);ge&&(xe.addEventListener("load",()=>{fe++,fe>=he&&Ee()},{once:!0}),xe.srcdoc=U(te,ge.shellMode,Ft(ge.config),x))}he===0&&Ee()}function H(){if(a)return;let M=ku(n);if(o.length!==M.length){P();return}if(M.some(I=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${I.mountId}"]`);return!z||z.dataset.shellMode!==I.shellMode})){P();return}o.forEach((I,z)=>{I.update(M[z].config),(n.scene??"conversation")==="minimized"&&I.close()});for(let I of M){let z=t.querySelector(`iframe[data-mount-id="${I.mountId}"]`);z&&Mu(z,I.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(t)),P(),{update(M){if(a)return;let T=M.device!==void 0&&M.device!==n.device||M.scene!==void 0&&M.scene!==n.scene||M.compareMode!==void 0&&M.compareMode!==n.compareMode||M.widgetCssPath!==void 0&&M.widgetCssPath!==n.widgetCssPath;n={...n,...M},T?P():H()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(M){a||(n={...n,zoom:M},f())}}}export{Hy as createThemePreview};
|