@runtypelabs/persona 4.15.0 → 4.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/context-mentions.d.cts +283 -9
- package/dist/context-mentions.d.ts +283 -9
- package/dist/index.cjs +68 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +299 -10
- package/dist/index.d.ts +299 -10
- package/dist/index.global.js +57 -57
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +69 -69
- 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 +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers.js +36 -36
- package/dist/smart-dom-reader.d.cts +283 -9
- package/dist/smart-dom-reader.d.ts +283 -9
- package/dist/testing.cjs +3 -3
- package/dist/testing.d.cts +7 -0
- package/dist/testing.d.ts +7 -0
- package/dist/testing.js +3 -3
- package/dist/theme-editor-preview.cjs +64 -64
- package/dist/theme-editor-preview.d.cts +283 -9
- package/dist/theme-editor-preview.d.ts +283 -9
- package/dist/theme-editor-preview.js +56 -56
- package/dist/theme-editor.cjs +10 -10
- package/dist/theme-editor.d.cts +283 -10
- package/dist/theme-editor.d.ts +283 -10
- package/dist/theme-editor.js +10 -10
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +66 -3
- package/dist/theme-reference.d.ts +66 -3
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +2 -2
- package/src/components/artifact-pane.test.ts +27 -0
- package/src/components/artifact-pane.ts +7 -3
- package/src/components/header-builder.ts +27 -2
- package/src/components/header-layouts.test.ts +56 -0
- package/src/components/header-layouts.ts +29 -9
- package/src/components/launcher-surface.test.ts +403 -0
- package/src/components/launcher.ts +297 -2
- package/src/components/panel.ts +69 -74
- package/src/components/suggestions.test.ts +40 -0
- package/src/components/suggestions.ts +213 -153
- package/src/components/welcome.test.ts +121 -0
- package/src/components/welcome.ts +305 -0
- package/src/components/widget-view.test.ts +5 -3
- package/src/components/widget-view.ts +14 -7
- package/src/defaults.ts +2 -2
- package/src/index-core.ts +12 -1
- package/src/install.test.ts +35 -1
- package/src/install.ts +47 -11
- package/src/launcher-global.ts +10 -7
- package/src/plugins/types.ts +66 -1
- package/src/styles/widget-styles.test.ts +220 -0
- package/src/styles/widget.css +353 -9
- package/src/testing/mock-stream.test.ts +19 -0
- package/src/testing/mock-stream.ts +20 -0
- package/src/theme-editor/sections.ts +30 -1
- package/src/theme-reference.ts +26 -4
- package/src/types/theme.ts +40 -3
- package/src/types.ts +164 -6
- package/src/ui.body-top-slot.test.ts +95 -0
- package/src/ui.content-width.test.ts +91 -0
- package/src/ui.docked.test.ts +7 -4
- package/src/ui.launcher-teaser.test.ts +162 -0
- package/src/ui.rebuild-composer.test.ts +491 -0
- package/src/ui.render-welcome.test.ts +505 -0
- package/src/ui.scroll-additive.test.ts +91 -21
- package/src/ui.scroll.test.ts +302 -14
- package/src/ui.suggest-replies.test.ts +46 -0
- package/src/ui.ts +747 -136
- package/src/ui.welcome.test.ts +504 -0
- package/src/utils/artifact-gate.test.ts +27 -0
- package/src/utils/artifact-gate.ts +9 -0
- package/src/utils/attachment-manager.test.ts +37 -0
- package/src/utils/attachment-manager.ts +15 -0
- package/src/utils/auto-follow.test.ts +23 -0
- package/src/utils/auto-follow.ts +11 -1
- package/src/utils/config-merge.ts +2 -0
- package/src/utils/content-width.test.ts +37 -0
- package/src/utils/content-width.ts +17 -0
- package/src/utils/plugin-storage.test.ts +94 -0
- package/src/utils/plugin-storage.ts +98 -0
- package/src/utils/theme.test.ts +137 -0
- package/src/utils/tokens.ts +49 -3
- package/src/welcome.test.ts +213 -0
- package/src/welcome.ts +130 -0
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!
|
|
3
|
-
`):e};var
|
|
1
|
+
import{a as Mp}from"./chunk-5EIIHQLQ.js";import{a as b,b as Tp,c as Ee,d as Pn,e as ae,f as Lp,h as Pp,i as Ip}from"./chunk-QJ4LV2KW.js";import{a as Ep,b as kp}from"./chunk-IO5VVUKP.js";var xr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(f=>(r=f,f)).catch(f=>{throw s=null,f}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:$w,load:Nm,provide:Uw,getSync:Ll}=xr({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),Ra=new Set,_m=()=>{let e=[...Ra];Ra.clear();for(let t of e)try{t()}catch{}};var $m=()=>{let e=Ll();return e?Promise.resolve(e):Nm().then(t=>(_m(),t))},Ha=e=>Ll()?()=>{}:(Ra.add(e),$m().catch(()=>{}),()=>{Ra.delete(e)});var Gn=Ll;var Um=e=>{if(e)return e},Pl=e=>{let t=null;return n=>{let o=Gn();if(!o)return mo(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Um(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},Ba=e=>e?Pl({markedOptions:e.options,renderer:e.renderer}):Pl(),Vw=Pl();var mo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var zm={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},jm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Vm=()=>{let e=null;return t=>{let n=Gn();if(!n)return mo(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!jm.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,zm)}},Da=e=>e===!1?null:typeof e=="function"?e:Vm();var Wp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Rp=e=>e.includes("|"),Hp=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},qm=e=>`| ${e.join(" | ")} |`,Km=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Gm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Bp=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Rp(r)||Wp.test(r)||!Wp.test(s))continue;let a=Hp(r).length;if(a<1)continue;let l=Km(a);t[o+1]!==l&&(t[o+1]=l,n=!0);let u=o+2;for(;u<t.length;u++){let d=t[u];if(d.trim()===""||!Rp(d))break;let c=qm(Gm(Hp(d),a));t[u]!==c&&(t[u]=c,n=!0)}o=u-1}return n?t.join(`
|
|
3
|
+
`):e};var Dp="var(--persona-md-table-scroll-fade, 24px)",Fp=new WeakSet;function Np(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Op(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Dp),e.style.setProperty("--persona-fade-r",r<=1?"0px":Dp)}function Il(e){Fp.has(e)||(Fp.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Op(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Op)}var Yn="webmcp:",Wl=new Map,_p=e=>{Wl.clear();for(let t of e){let n=t.title?.trim();n&&Wl.set(t.name,n)}},ws=e=>Wl.get(jp(e)),Fa={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$p=null;function zp(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${Ym(t.join(""))}`}function Up(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Ym(e){let t=Up(e,0).toString(36),n=Up(e,2654435761).toString(36);return`${t}.${n}`}var Oa=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Fa.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}_p(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Qm(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return In("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let v=typeof document<"u"&&!!document.modelContext;return In(v?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=jp(t),a;try{a=await r.getTools()}catch(v){let C=v instanceof Error?v.message:String(v);return In(`Failed to read WebMCP registry: ${C}`)}_p(a);let l=a.find(v=>v.name===s);if(!l)return In(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return In(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return In("Aborted by cancel()");let u=ws(s),d={toolName:s,args:n,description:l.description,...u?{title:u}:{},reason:"gate"};if(!await this.requestConfirm(d))return In("User declined the tool call.");if(o?.aborted)return In("Aborted by cancel()");let c=new AbortController,f=!1,w=setTimeout(()=>{f=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let v=await r.executeTool(l,th(n),{signal:c.signal});return Jm(v)}catch(v){if(f)return In(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return In("Aborted by cancel()");let C=v instanceof Error?v.message:String(v);return In(C)}finally{clearTimeout(w),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}($p?await $p():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Fa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Fa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??Zm;try{return await n(t)}catch(o){return Fa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Xm(t,o))}},jp=e=>e.startsWith(Yn)?e.slice(Yn.length):e,Cr=e=>e.startsWith(Yn),Xm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Qm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Jm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:nh(t)}]}},In=e=>({isError:!0,content:[{type:"text",text:e}]}),Zm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=eh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
6
|
${t}`:"")+(e.description?`
|
|
7
7
|
|
|
8
|
-
${e.description}`:"");return window.confirm(n)},Fg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Ng=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Og=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function gn(e){return e==="card"?"collapsed":e}function rr(e){return e.split(";",1)[0].trim().toLowerCase()}function _g(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(rr(r)===t)return{mode:gn(s),selector:rr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(rr(r)===o)return{mode:gn(s),selector:o}}function $g(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:gn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?rr(t.file.mimeType):void 0,p=l?_g(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:gn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:gn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:gn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:gn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:gn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function io(e,t){return $g(e,t).mode}function ns(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Ug="agent_",zg="flow_";function qd(e){return e.startsWith(Ug)?{kind:"agentId",agentId:e}:e.startsWith(zg)?{kind:"flowId",flowId:e}:null}function Kd(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=qd(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=qd(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as jg,ARR as Vg,OBJ as qg,STR as Kg}from"partial-json";var Xi="ask_user_question",os=8,sr="data-persona-ask-sheet-for",Gg="Other",Qg="Other\u2026",Qd="Type your own answer here",Xd="Send",Xg="Next",Jg="Back",Yg="Submit all",Zg="Skip",em=3,Ji="data-ask-current-index",Yi="data-ask-question-count",Jd="data-ask-answers",Zi="data-ask-grouped",Yd="data-ask-layout",tm=e=>e.layout==="pills"?"pills":"rows",nm=e=>e.getAttribute(Yd)==="pills"?"pills":"rows",Gd=!1,Zd=e=>e.replace(/["\\]/g,"\\$&"),Wo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xi,el=e=>e?.features?.askUserQuestion??{},ar=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=jg(r,Kg|qg|Vg);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},rs=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>os&&!Gd&&(Gd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${os}.`)),t.slice(0,os)},om=e=>rs(e)[0]??null,rm=(e,t)=>rs(e)[t]??null,sm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ep=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},am=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),l=y("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=ep(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},im=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},lm=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<em;c++)s.appendChild(im(o));return s}if(p.forEach((c,u)=>{s.appendChild(am(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Gg:Qg;if(o==="rows"){let u=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=y("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Qd,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),u.appendChild(w);let v=ep(o,a,p.length);v&&u.appendChild(v),s.appendChild(u)}else{let u=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,s.appendChild(u)}}return s},tp=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Qd,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Xd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},cm=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Xd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},dm=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Jg,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Zg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=y("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Yg:n.nextLabel??Xg,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ho=e=>{let t=e.getAttribute(Jd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},np=(e,t)=>{e.setAttribute(Jd,JSON.stringify(t))},mn=e=>{let t=Number(e.getAttribute(Ji)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pm=(e,t)=>{e.setAttribute(Ji,String(Math.max(0,Math.floor(t))))},ir=e=>{let t=Number(e.getAttribute(Yi)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},lo=e=>e.getAttribute(Zi)==="true",um=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},fm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},va=(e,t)=>{let{payload:n}=ar(t),o=rs(n),r=Ho(e),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},op=e=>{let t=Ho(e),n=mn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},rp=e=>{if(!lo(e))return;let t=Ho(e),n=mn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},tl=(e,t,n)=>{let o=el(n),r=nm(e),{payload:s,complete:a}=ar(t),l=lo(e),p=mn(e),d=ir(e),c=l?rm(s,p):om(s),u=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let k=typeof c?.question=="string"?c.question:"";v.textContent=k,v.classList.toggle("persona-ask-question-skeleton",!k&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let k=lm(c,o,a,r);x.replaceWith(k)}if(r!=="rows"){let k=e.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(tp(o,r))}let P=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?e.appendChild(cm(o)):(!u||l)&&P&&P.remove(),e.setAttribute("data-multi-select",u?"true":"false");let F=e.querySelector('[data-ask-nav-row="true"]');if(l){let k=dm(p,d,o);F?F.replaceWith(k):e.appendChild(k)}else F&&F.remove();op(e),rp(e)},gm=(e,t,n)=>{let o=el(t),r=tm(o),s=e.toolCall.id,a=rs(n),l=Math.max(1,a.length),p=l>1,d=um(e,a),c=p?fm(e,l):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(sr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Yi,String(l)),u.setAttribute(Ji,String(c)),u.setAttribute(Zi,p?"true":"false"),u.setAttribute(Yd,r),np(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sm(u,o);let w=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),u.appendChild(w);let P=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),u.appendChild(P),r!=="rows"&&u.appendChild(tp(o,r)),tl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},mm=(e,t,n)=>{let{payload:o}=ar(t),r=Math.max(1,rs(o).length);r>ir(e)&&(e.setAttribute(Yi,String(r)),r>1&&!lo(e)&&e.setAttribute(Zi,"true")),tl(e,t,n)};var wa=(e,t,n)=>{if(!n||!Wo(e)||el(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${sr}]`).forEach(d=>{d.getAttribute(sr)!==r&&d.remove()});let a=n.querySelector(`[${sr}="${Zd(r)}"]`);if(a){mm(a,e,t);return}let{payload:l}=ar(e),p=gm(e,t,l);n.appendChild(p)},lr=(e,t)=>{if(!e)return;let n=t?`[${sr}="${Zd(t)}"]`:`[${sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},nl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),co=(e,t)=>{let n=Ho(e),o=mn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,np(e,n),op(e),rp(e)},xa=(e,t,n,o)=>{let r=ir(e),s=Math.max(0,Math.min(r-1,o));pm(e,s),tl(e,t,n)};var Un="suggest_replies";var hm={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},ap={name:Un,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:hm,origin:"sdk",annotations:{readOnlyHint:!0}},ol=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ss=e=>e.variant==="tool"&&e.toolCall?.name===Un,ym=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},ip=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ss(n))continue;let o=ym(n.toolCall?.args);return o.length>0?o:null}return null},sp=new Set,bm=(e,t,n)=>{let o=`${e}:${t}:${n}`;sp.has(o)||(sp.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},po=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],p=n?.[a];l===void 0||p===void 0||l!==p&&bm(a,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var vm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:os,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},wm={name:Xi,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:vm,origin:"sdk",annotations:{readOnlyHint:!0}},Ca=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(wm),po(e).expose&&t.push(ap),t};import{parse as xm,STR as Cm,OBJ as Am}from"partial-json";var lp=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function yn(e){return e==="card"?"collapsed":e}function Ar(e){return e.split(";",1)[0].trim().toLowerCase()}function oh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ar(r)===t)return{mode:yn(s),selector:Ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ar(r)===o)return{mode:yn(s),selector:o}}function rh(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ar(t.file.mimeType):void 0,u=l?oh(o.files.byMediaType,l):void 0;if(l&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:l,selector:u.selector}};if(o.files.default)return{mode:yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:yn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ho(e,t){return rh(e,t).mode}function xs(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var sh="agent_",ah="flow_";function Vp(e){return e.startsWith(sh)?{kind:"agentId",agentId:e}:e.startsWith(ah)?{kind:"flowId",flowId:e}:null}function qp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=Vp(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[a];if(!u)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(l).payload}}let r=Vp(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as ih,ARR as lh,OBJ as ch,STR as dh}from"partial-json";var Rl="ask_user_question",Cs=8,Sr="data-persona-ask-sheet-for",ph="Other",uh="Other\u2026",Gp="Type your own answer here",Yp="Send",fh="Next",gh="Back",mh="Submit all",hh="Skip",yh=3,Hl="data-ask-current-index",Bl="data-ask-question-count",Xp="data-ask-answers",Dl="data-ask-grouped",Qp="data-ask-layout",bh=e=>e.layout==="pills"?"pills":"rows",vh=e=>e.getAttribute(Qp)==="pills"?"pills":"rows",Kp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Rl,Fl=e=>e?.features?.askUserQuestion??{},Tr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=ih(r,dh|ch|lh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},As=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Cs&&!Kp&&(Kp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},wh=e=>As(e)[0]??null,xh=(e,t)=>As(e)[t]??null,Ch=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Zp=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=b("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let u=Zp(n,o,t);u&&s.appendChild(u)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Th=(e,t,n,o)=>{let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,u=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(u.length===0&&!n){for(let c=0;c<yh;c++)s.appendChild(Sh(o));return s}if(u.forEach((c,f)=>{s.appendChild(Ah(c,f,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ph:uh;if(o==="rows"){let f=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(u.length)),f.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Gp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),f.appendChild(w);let v=Zp(o,a,u.length);v&&f.appendChild(v),s.appendChild(f)}else{let f=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,s.appendChild(f)}}return s},eu=(e,t)=>{let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Gp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=b("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Yp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Yp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Eh=(e,t,n)=>{let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??hh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let u=e===t-1;return l.textContent=u?n.submitAllLabel??mh:n.nextLabel??fh,l.setAttribute("data-ask-user-action",u?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(Xp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(e,t)=>{e.setAttribute(Xp,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(Hl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Bl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Dl)==="true",Lh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ph=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=Tr(t),o=As(n),r=Ko(e),s={},a=new Set;return o.forEach((l,u)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,u)&&(s[d]=r[u]))}),s},nu=e=>{let t=Ko(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(u=>r.add(u));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(u=>{let d=u.getAttribute("data-option-label")??"",c=r.has(d);u.setAttribute("aria-pressed",c?"true":"false"),u.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(u=>u.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ou=e=>{if(!yo(e))return;let t=Ko(e),n=bn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ol=(e,t,n)=>{let o=Fl(n),r=vh(e),{payload:s,complete:a}=Tr(t),l=yo(e),u=bn(e),d=Mr(e),c=l?xh(s,u):wh(s),f=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${u+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let S=typeof c?.question=="string"?c.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=Th(c,o,a,r);C.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(eu(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(Mh(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=Eh(u,d,o);B?B.replaceWith(S):e.appendChild(S)}else B&&B.remove();nu(e),ou(e)},Ih=(e,t,n)=>{let o=Fl(t),r=bh(o),s=e.toolCall.id,a=As(n),l=Math.max(1,a.length),u=l>1,d=Lh(e,a),c=u?Ph(e,l):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sr,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(Bl,String(l)),f.setAttribute(Hl,String(c)),f.setAttribute(Dl,u?"true":"false"),f.setAttribute(Qp,r),tu(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(f,o);let w=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),f.appendChild(w);let T=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(eu(o,r)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wh=(e,t,n)=>{let{payload:o}=Tr(t),r=Math.max(1,As(o).length);r>Mr(e)&&(e.setAttribute(Bl,String(r)),r>1&&!yo(e)&&e.setAttribute(Dl,"true")),Ol(e,t,n)};var _a=(e,t,n)=>{if(!n||!qo(e)||Fl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Wh(a,e,t);return}let{payload:l}=Tr(e),u=Ih(e,t,l);n.appendChild(u)},Er=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Nl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),bo=(e,t)=>{let n=Ko(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tu(e,n),nu(e),ou(e)},$a=(e,t,n,o)=>{let r=Mr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Ol(e,t,n)};var Xn="suggest_replies";var Rh={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},su={name:Xn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>e.variant==="tool"&&e.toolCall?.name===Xn,Hh=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},au=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ss(n))continue;let o=Hh(n.toolCall?.args);return o.length>0?o:null}return null},ru=new Set,Bh=(e,t,n)=>{let o=`${e}:${t}:${n}`;ru.has(o)||(ru.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},vo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],u=n?.[a];l===void 0||u===void 0||l!==u&&Bh(a,u,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Dh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Fh={name:Rl,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Dh,origin:"sdk",annotations:{readOnlyHint:!0}},Ua=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fh),vo(e).expose&&t.push(su),t};import{parse as Oh,STR as Nh,OBJ as _h}from"partial-json";var iu=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},$h=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},lu=e=>e.status==="complete"?$h(e):e.status==="pending"?"Waiting":"",Uh=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var cu=e=>e.status==="complete"?Uh(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ms=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},ja=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},$l=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ms(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ts(o,n.slice(s,a.index),[]),a[1]!==void 0?Ts(o,a[1],["bold"]):a[2]!==void 0?Ts(o,a[2],["italic"]):a[3]!==void 0&&Ts(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ts(o,n.slice(s),[]),o},Ts=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},zh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ls=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pp=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},up=()=>{let e=Mm();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},fp=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=xm(n,Cm|Am);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?lp(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=lp(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var gp=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var mp="4.15.0";var cs=mp;var km="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Lm(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var sl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Pm(e){switch(e){case"json":return fp;case"regex-json":return up;case"xml":return gp;default:return pp}}var hp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Im(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=hp(n);if(!hp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ls(e);return ls(t)!==null&&a===null?t:e}var ds=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??km,this.headers={"Content-Type":"application/json","X-Persona-Version":cs,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Pm(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new ba(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Kd(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(sl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":cs},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ma}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?jd(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ma}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(sl).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(sl).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...Ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=C=>{let $=C.reasoning?{...C.reasoning,chunks:[...C.reasoning.chunks]}:void 0,h=C.toolCall?{...C.toolCall,chunks:C.toolCall.chunks?[...C.toolCall.chunks]:void 0}:void 0,L=C.tools?C.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...C,reasoning:$,toolCall:h,tools:L}},w=C=>{if(C.role!=="assistant"||C.variant)return!0;let $=Array.isArray(C.contentParts)&&C.contentParts.length>0,h=typeof C.rawContent=="string"&&C.rawContent.trim()!=="";return typeof C.content=="string"&&C.content.trim()!==""||$||h||!!C.stopReason},g=C=>{w(C)&&n({type:"message",message:u(C)})},v=null,x=null,P={current:null},F={current:null},k=null,T="",M=new Map,U=new Map,j=new Map,A=new Map,V=new Map,K={lastId:null,byStep:new Map},ne={lastId:null,byCall:new Map},D=C=>{if(C==null)return null;try{return String(C)}catch{return null}},_=C=>D(C.stepId??C.step_id??C.step??C.parentId??C.flowStepId??C.flow_step_id),Y=C=>D(C.callId??C.call_id??C.requestId??C.request_id??C.toolCallId??C.tool_call_id??C.stepId??C.step_id),ge=o,he=!1,ce=()=>{if(v)return v;let C,$="",h=k;return!he&&ge?(C=ge,he=!0,$=r??""):ge&&h?C=`${ge}_${h}`:C=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:C,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},Z=(C,$)=>{K.lastId=$,C&&K.byStep.set(C,$)},de=(C,$)=>{let h=C.reasoningId??C.id,L=_(C);if(h){let H=String(h);return Z(L,H),H}if(L){let H=K.byStep.get(L);if(H)return K.lastId=H,H}if(K.lastId&&!$)return K.lastId;if(!$)return null;let I=`reason-${c()}`;return Z(L,I),I},te=C=>{let $=A.get(C);if($)return $;let h={id:`reason-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:C,status:"streaming",chunks:[]}};return A.set(C,h),g(h),h},ie=(C,$)=>{ne.lastId=$,C&&ne.byCall.set(C,$)},J=new Set,fe=new Map,Ce=new Set,ye=new Map,xe=C=>{if(!C)return!1;let $=C.replace(/_+/g,"_").replace(/^_|_$/g,"");return $==="emit_artifact_markdown"||$==="emit_artifact_component"},ve=(C,$)=>{let h=C.toolId??C.id,L=Y(C);if(h){let H=String(h);return ie(L,H),H}if(L){let H=ne.byCall.get(L);if(H)return ne.lastId=H,H}if(ne.lastId&&!$)return ne.lastId;if(!$)return null;let I=`tool-${c()}`;return ie(L,I),I},Ae=C=>{let $=V.get(C);if($)return $;let h={id:`tool-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:C,status:"pending"}};return V.set(C,h),g(h),h},Te=C=>{if(typeof C=="number"&&Number.isFinite(C))return C;if(typeof C=="string"){let $=Number(C);if(!Number.isNaN($)&&Number.isFinite($))return $;let h=Date.parse(C);if(!Number.isNaN(h))return h}return Date.now()},qe=C=>{if(typeof C=="string")return C;if(C==null)return"";try{return JSON.stringify(C)}catch{return String(C)}},ze=new Map,Me=new Map,Pe=new Map,Ke=(C,$,h)=>{let L=Pe.get(C);L||(L=[],Pe.set(C,L));let I=0,H=L.length;for(;I<H;){let R=I+H>>>1;L[R].seq<$?I=R+1:H=R}L[I]?.seq===$?L[I]={seq:$,text:h}:L.splice(I,0,{seq:$,text:h});let B="";for(let R=0;R<L.length;R++)B+=L[R].text;return B},Wt=(C,$)=>{let h=qe($),L=Me.get(C.id),I=Im(L,h);C.rawContent=I;let H=ze.get(C.id),B=we=>{let nt=C.content??"";we.trim()!==""&&(nt.trim().length===0||we.startsWith(nt)||we.trimStart().startsWith(nt.trim()))&&(C.content=we)},R=()=>{if(H){let we=H.close?.();we instanceof Promise&&we.catch(()=>{})}ze.delete(C.id),Me.delete(C.id),C.streaming=!1,g(C)};if(!H){B(h),R();return}let Q=ls(I);if(Q!==null&&Q.trim()!==""){B(Q),R();return}let se=we=>{let nt=typeof we=="string"?we:we?.text??null;if(nt!==null&&nt.trim()!=="")return nt;let tt=H.getExtractedText();return tt!==null&&tt.trim()!==""?tt:h},Ee;try{Ee=H.processChunk(I)}catch{B(h),R();return}if(Ee instanceof Promise){Ee.then(we=>{B(se(we)),R()}).catch(()=>{B(h),R()});return}B(se(Ee)),R()},It=null,qt=(C,$,h,L)=>{C.rawContent=$,ze.has(C.id)||ze.set(C.id,this.createStreamParser());let I=ze.get(C.id),H=$.trim().startsWith("{")||$.trim().startsWith("[");if(H&&Me.set(C.id,$),I.__isPlainTextParser===!0){C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C);return}let R=I.processChunk($);if(R instanceof Promise)R.then(Q=>{let se=typeof Q=="string"?Q:Q?.text??null;se!==null&&se.trim()!==""?(C.content=se,g(C)):!H&&!$.trim().startsWith("<")&&(C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C))}).catch(()=>{C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C)});else{let Q=typeof R=="string"?R:R?.text??null;Q!==null&&Q.trim()!==""?(C.content=Q,g(C)):!H&&!$.trim().startsWith("<")&&(C.content=L!==void 0?$:C.content+h,Me.delete(C.id),ze.delete(C.id),C.rawContent=void 0,g(C))}},xt=(C,$)=>{let h=$??C.content;if(h==null||h===""){C.streaming=!1,g(C);return}let I=Me.get(C.id)??qe(h);C.rawContent=I;let H=ze.get(C.id),B=null,R=!1;if(H&&(B=H.getExtractedText(),B===null&&(B=ls(I)),B===null)){let Q=H.processChunk(I);Q instanceof Promise?(R=!0,Q.then(se=>{let Ee=typeof se=="string"?se:se?.text??null;Ee!==null&&(C.content=Ee,C.streaming=!1,ze.delete(C.id),Me.delete(C.id),g(C))}).catch(()=>{})):B=typeof Q=="string"?Q:Q?.text??null}if(!R){B!==null&&B.trim()!==""?C.content=B:Me.has(C.id)||(C.content=qe(h));let Q=ze.get(C.id);if(Q){let se=Q.close?.();se instanceof Promise&&se.catch(()=>{}),ze.delete(C.id)}Me.delete(C.id),C.streaming=!1,g(C)}},Be=(C,$,h)=>{let L=U.get(C);if(L)return L;let I={id:`nested-${$}-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:C,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:$}};return U.set(C,I),g(I),I},ue=[],Xe,We=new Map,me=0,le="agent",Re=!1,Kt=null,pt=null,mt=new Map,z=this.config.iterationDisplay??"separate";for(Xe=()=>{for(let C=0;C<ue.length;C++){let $=ue[C].payloadType,h=ue[C].payload;if(!Re&&le!=="flow"&&typeof h.stepType=="string"&&(le="flow"),$==="reasoning_start"){let L=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(L&&I){M.set(L,I),Be(L,I,"reasoning");continue}let H=de(h,!0)??`reason-${c()}`,B=te(H);B.reasoning=B.reasoning??{id:H,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Te(h.startedAt??h.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(B.reasoning.scope=h.scope),B.streaming=!0,B.reasoning.status="streaming",g(B)}else if($==="reasoning_delta"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)&&U.has(L)){let R=U.get(L),Q=h.reasoningText??h.text??h.delta??"";Q&&h.hidden!==!0&&R.reasoning&&(R.reasoning.chunks.push(String(Q)),g(R));continue}let I=de(h,!1)??de(h,!0)??`reason-${c()}`,H=te(I);H.reasoning=H.reasoning??{id:I,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??Te(h.startedAt??h.timestamp);let B=h.reasoningText??h.text??h.delta??"";if(B&&h.hidden!==!0){let R=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(R!==void 0){let Q=Ke(I,R,String(B));H.reasoning.chunks=[Q]}else H.reasoning.chunks.push(String(B))}if(H.reasoning.status=h.done?"complete":"streaming",h.done){H.reasoning.completedAt=Te(h.completedAt??h.timestamp);let R=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-R)}H.streaming=H.reasoning.status!=="complete",g(H)}else if($==="reasoning_complete"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)&&U.has(L)){let Q=U.get(L);if(Q.reasoning){let se=typeof h.text=="string"?h.text:"";se&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(se),Q.reasoning.status="complete",Q.streaming=!1,g(Q)}M.delete(L),U.delete(L);continue}let I=de(h,!1)??de(h,!0)??`reason-${c()}`,H=typeof h.text=="string"?h.text:"";!A.get(I)&&(H||h.scope==="loop")&&te(I);let B=A.get(I);if(B?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(B.reasoning.scope=h.scope),H&&B.reasoning.chunks.length===0&&B.reasoning.chunks.push(H),B.reasoning.status="complete",B.reasoning.completedAt=Te(h.completedAt??h.timestamp);let Q=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-Q),B.streaming=!1,g(B)}let R=_(h);R&&K.byStep.delete(R)}else if($==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(me=h.iteration);let L=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??ve(h,!0)??`tool-${c()}`,I=h.toolName??h.name;if(xe(I)){J.add(L);continue}ie(Y(h),L);let H=Ae(L),B=H.toolCall??{id:L,status:"pending"};B.name=I??B.name,B.status="running",h.parameters!==void 0?B.args=h.parameters:h.args!==void 0&&(B.args=h.args),B.startedAt=B.startedAt??Te(h.startedAt??h.timestamp),B.completedAt=void 0,B.durationMs=void 0,H.toolCall=B,H.streaming=!0,h.executionId&&(H.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(H)}else if($==="tool_output_delta"){let L=ve(h,!1)??ve(h,!0)??`tool-${c()}`;if(J.has(L))continue;let I=Ae(L),H=I.toolCall??{id:L,status:"running"};H.startedAt=H.startedAt??Te(h.startedAt??h.timestamp);let B=h.text??h.delta??h.message??"";B&&(H.chunks=H.chunks??[],H.chunks.push(String(B))),H.status="running",I.toolCall=H,I.streaming=!0;let R=h.agentContext;(R||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:R?.executionId??h.executionId,iteration:R?.iteration??h.iteration}),g(I)}else if($==="tool_complete"){let L=ve(h,!1)??ve(h,!0)??`tool-${c()}`;if(J.has(L)){J.delete(L);continue}let I=Ae(L),H=I.toolCall??{id:L,status:"running"};H.status="complete",h.result!==void 0&&(H.result=h.result),typeof h.duration=="number"&&(H.duration=h.duration),H.completedAt=Te(h.completedAt??h.timestamp);let B=h.duration??h.executionTime;if(typeof B=="number")H.durationMs=B;else{let se=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-se)}I.toolCall=H,I.streaming=!1;let R=h.agentContext;(R||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:R?.executionId??h.executionId,iteration:R?.iteration??h.iteration}),g(I);let Q=Y(h);Q&&ne.byCall.delete(Q)}else if($==="await"&&h.toolName){let L=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,I=L??h.toolId??`local-${c()}`,H=Ae(I),B=h.toolName,R=h.origin==="webmcp"&&!or(B)?`webmcp:${B}`:B,Q=or(R),se=H.toolCall??{id:I,status:"pending"};se.name=R,se.args=h.parameters,se.status=Q?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Te(h.startedAt??h.timestamp??h.awaitedAt),Q?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,H.toolCall=se,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:h.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...L?{webMcpToolCallId:L}:{}},g(H)}else if($==="text_start"){let L=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(L&&I){M.set(L,I);continue}let H=v;H&&(le==="flow"?(xt(H),It=H):(H.streaming=!1,g(H)),v=null),k=typeof h.id=="string"?h.id:k,T=""}else if($==="text_delta"){let L=typeof h.id=="string"?h.id:null,I=L?M.get(L):void 0;if(L&&I){let B=typeof h.delta=="string"?h.delta:"",R=(j.get(L)??"")+B;if(j.set(L,R),R.trim()==="")continue;let Q=Be(L,I);Q.agentMetadata={...Q.agentMetadata,executionId:h.executionId,parentToolId:I},qt(Q,R,B,void 0);continue}if(k=typeof h.id=="string"?h.id:k,le==="flow"){let B=typeof h.delta=="string"?h.delta:"";if(T+=B,T.trim()==="")continue;let R=ce();R.agentMetadata={executionId:h.executionId,iteration:h.iteration},qt(R,T,B,void 0),x=R;continue}let H=ce();H.content+=h.delta??"",H.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:Kt??void 0,agentName:pt?.agentName},x=H,g(H)}else if($==="text_complete"){let L=typeof h.id=="string"?h.id:null;if(L&&M.has(L)){let H=U.get(L);H&&xt(H),M.delete(L),j.delete(L),U.delete(L);continue}let I=v;I&&(le==="flow"?(xt(I),It=I):((I.content??"")===""&&typeof h.text=="string"&&(I.content=h.text),I.streaming=!1,g(I)),v=null),k=null,T=""}else if($==="step_complete"){let L=h.stepType,I=h.executionType;if(L==="tool"||I==="context")continue;if(h.success===!1){let H=h.error,B=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(B)});let R=v;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"});continue}{let H=It;It=null;let B=h.stopReason,R=h.result?.response;if(H)B&&(H.stopReason=B),R!=null?Wt(H,R):H.streaming!==!1&&(ze.delete(H.id),Me.delete(H.id),H.streaming=!1,g(H));else{let Q=R!=null&&R!=="";if(Q||B){let se=ce();B&&(se.stopReason=B),Q?xt(se,R):(se.streaming=!1,g(se))}}continue}}else if($==="execution_start")le=h.kind==="flow"?"flow":"agent",Re=!0,le==="agent"&&(pt={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Te(h.startedAt)});else if($==="turn_start"){let L=typeof h.iteration=="number"?h.iteration:me;if(L!==me){if(pt&&(pt.currentIteration=L),z==="separate"&&L>1){let I=v;I&&(I.streaming=!1,g(I),mt.set(L-1,I),v=null)}me=L}Kt=typeof h.id=="string"?h.id:null,x=null}else if($==="tool_input_delta"){let L=h.toolCallId??ne.lastId;if(L){let I=V.get(L);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(h.delta??""),g(I))}}else{if($==="tool_input_complete")continue;if($==="turn_complete"){let L=h.stopReason,I=v??x;if(L&&I!==null){let H=h.id;(!H||I.agentMetadata?.turnId===H)&&(I.stopReason=L,g(I))}Kt===h.id&&(Kt=null)}else if($==="media_start"){let L=String(h.id);We.set(L,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if($==="media_delta"){let L=We.get(String(h.id));L&&typeof h.delta=="string"&&L.parts.push(h.delta)}else if($==="media_complete"){let L=String(h.id),I=We.get(L);We.delete(L);let H=(typeof h.mediaType=="string"?h.mediaType:void 0)??I?.mediaType??"application/octet-stream",B=typeof h.data=="string"?h.data:void 0,R=typeof h.url=="string"?h.url:I&&I.parts.length>0?I.parts.join(""):void 0,Q=null;if(B)Q={type:"media",data:B,mediaType:H};else if(R){let nt=H.toLowerCase();Q={type:nt==="image"||nt.startsWith("image/")?"image-url":"file-url",url:R,mediaType:H}}let se=h.toolCallId??I?.toolCallId,Ee=Q?[Q]:[],we=[];for(let nt of Ee){if(!nt||typeof nt!="object")continue;let tt=nt,_e=typeof tt.type=="string"?tt.type:void 0,Je=typeof tt.mediaType=="string"?tt.mediaType.toLowerCase():"",q=null,$e="";if(_e==="media"){let De=typeof tt.data=="string"?tt.data:void 0;if(!De)continue;$e=Je.length>0?Je:"application/octet-stream",q=`data:${$e};base64,${De}`}else if(_e==="image-url"){let De=typeof tt.url=="string"?tt.url:void 0;if(!De)continue;$e=Je,q=De}else if(_e==="file-url"){let De=typeof tt.url=="string"?tt.url:void 0;if(!De)continue;$e=Je,q=De}else continue;if(q)if(_e==="image-url"||$e.startsWith("image/"))we.push({type:"image",image:q,...$e.includes("/")?{mimeType:$e}:{}});else if($e.startsWith("audio/"))we.push({type:"audio",audio:q,mimeType:$e});else if($e.startsWith("video/"))we.push({type:"video",video:q,mimeType:$e});else{let De=$e||"application/octet-stream";we.push({type:"file",data:q,mimeType:De,filename:Lm(De)})}}if(we.length>0){let nt=c(),tt=se,Je={id:`agent-media-${typeof tt=="string"&&tt.length>0?`${tt}-${nt}`:String(nt)}`,role:"assistant",content:"",contentParts:we,createdAt:new Date().toISOString(),streaming:!1,sequence:nt,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:me}};g(Je);let q=v;q&&(q.streaming=!1,g(q)),v=null,P.current=null}}else if($==="execution_complete"){let L=h.kind??le;L==="agent"&&pt&&(pt.status=h.success?"complete":"error",pt.completedAt=Te(h.completedAt),pt.stopReason=h.stopReason);let I=v;I&&(L==="flow"&&I.streaming!==!1?xt(I):(I.streaming=!1,g(I)),v=null),k=null,T="",It=null,n({type:"status",status:"idle",terminal:!0})}else if($==="execution_error"){let L=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(L)})}else if($!=="ping"){if($==="approval_start"){let L=h.approvalId??`approval-${c()}`,I={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:"pending",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(I)}else if($==="step_await"&&h.awaitReason==="approval_required"){let L=h.approvalId??`approval-${c()}`,I={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:"pending",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(I)}else if($==="approval_complete"){let L=h.approvalId;if(L){let H={id:`approval-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:L,status:h.decision??"approved",agentId:pt?.agentId??"virtual",executionId:h.executionId??pt?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(H)}}else if($==="artifact_start"||$==="artifact_delta"||$==="artifact_update"||$==="artifact_complete"){if($==="artifact_start"){let L=h.artifactType,I=String(h.id),H=typeof h.title=="string"?h.title:void 0,B=h.file,R;B&&typeof B=="object"&&!Array.isArray(B)&&typeof B.path=="string"&&typeof B.mimeType=="string"&&(R={path:B.path,mimeType:B.mimeType,...typeof B.language=="string"?{language:B.language}:{}}),n({type:"artifact_start",id:I,artifactType:L,title:H,component:typeof h.component=="string"?h.component:void 0,...R?{file:R}:{}});let Q=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(ye.set(I,{markdown:"",title:H,file:R,...Q?{props:Q}:{}}),!Ce.has(I)){Ce.add(I);let se=io(this.config.features?.artifacts,{artifactType:L,...R?{file:R}:{}}),Ee=typeof h.component=="string"?h.component:void 0,we={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ns(se,{artifactId:I,title:H,artifactType:L,status:"streaming",...R?{file:R}:{},...Ee?{component:Ee}:{}})};fe.set(I,we),g(we)}}else if($==="artifact_delta"){let L=String(h.id),I=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:L,artDelta:I});let H=ye.get(L);H&&(H.markdown+=I)}else if($==="artifact_update"){let L=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:L,component:typeof h.component=="string"?h.component:void 0});let I=ye.get(String(h.id));I&&(I.props={...I.props??{},...L})}else if($==="artifact_complete"){let L=String(h.id);n({type:"artifact_complete",id:L});let I=fe.get(L);if(I){I.streaming=!1;try{let H=JSON.parse(I.rawContent??"{}");if(H.props){H.props.status="complete";let B=ye.get(L);B?.markdown&&(H.props.markdown=B.markdown),B?.file&&(H.props.file=B.file),H.component==="PersonaArtifactInline"&&B?.props&&Object.keys(B.props).length>0&&(H.props.componentProps=B.props)}I.rawContent=JSON.stringify(H)}catch{}ye.delete(L),g(I),fe.delete(L)}}}else if($==="transcript_insert"){let L=h.message;if(!L||typeof L!="object")continue;let I=String(L.id??`msg-${c()}`),H=L.role,R={id:I,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof L.content=="string"?L.content:"",rawContent:typeof L.rawContent=="string"?L.rawContent:void 0,createdAt:typeof L.createdAt=="string"?L.createdAt:new Date().toISOString(),streaming:L.streaming===!0,...typeof L.variant=="string"?{variant:L.variant}:{},sequence:c()};if(g(R),R.rawContent)try{let se=JSON.parse(R.rawContent)?.props?.artifactId;typeof se=="string"&&Ce.add(se)}catch{}v=null,P.current=null,ze.delete(I),Me.delete(I)}else if($==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let L=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(L)});let I=v;I&&I.streaming&&(I.streaming=!1,g(I)),n({type:"status",status:"idle"})}}else if($==="step_error"||$==="dispatch_error"||$==="flow_error"){let L=null;if(h.error instanceof Error)L=h.error;else if($==="dispatch_error"){let I=h.message??h.error;I!=null&&I!==""&&(L=new Error(String(I)))}else{let I=h.error;typeof I=="string"&&I!==""?L=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(L=new Error(String(I.message??I)))}if(L){n({type:"error",error:L});let I=v;I&&I.streaming&&(I.streaming=!1,g(I)),n({type:"status",status:"idle"})}}}}}ue.length=0};;){let{done:C,value:$}=await s.read();if(C)break;l+=a.decode($,{stream:!0});let h=l.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},uu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var gu="4.17.0";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ul=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Oa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=qp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Ul).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
|
|
12
12
|
|
|
13
|
-
`);l=h.pop()??"";for(let
|
|
14
|
-
`),H="message",B="",R=null;for(let we of I)we.startsWith("event:")?H=we.replace("event:","").trim():we.startsWith("data:")?B+=we.replace("data:","").trim():we.startsWith("id:")&&(R=we.slice(3).trim());let Q=()=>{R!==null&&R!==""&&n({type:"cursor",id:R})};if(!B){Q();continue}let se;try{se=JSON.parse(B)}catch(we){n({type:"error",error:we instanceof Error?we:new Error("Failed to parse chat stream payload")});continue}let Ee=H!=="message"?H:se.type??"message";if(this.onSSEEvent?.(Ee,se),this.parseSSEEvent){P.current=v;let we=await this.handleCustomSSEEvent(se,n,P,g,c,F);if(P.current&&P.current!==v&&(v=P.current),we){Q();continue}}ue.push({payloadType:Ee,payload:se}),Xe(),Q()}}Xe()}};function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function cr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ka="[Image]";function yp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function dr(e){return{type:"text",text:e}}var bp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Rm=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],zn=[...bp,...Rm];function Wm(e){return bp.includes(e)||e.startsWith("image/")}function La(e){return Wm(e.type)}async function vp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;La(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function wp(e,t=zn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Hm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function xp(e,t){let n=Hm(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Cp=16e3,Bm=24e3,Dm=4096,Fm=1380533830;function Nm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Fm?new Uint8Array(e,44):new Uint8Array(e)}function Om(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Cp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Cp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Ed(Bm);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Om(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Dm,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Nm(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Bo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ps(e.runtype);case"browser":if(!Bo.isSupported())throw new Error("Browser speech recognition not supported");return new Bo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ap(e){if(e?.type==="custom"&&e.custom)return pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return pr({type:"runtype",runtype:e.runtype});if(Bo.isSupported())return pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function al(e){try{return Ap(e),!0}catch{return!1}}function Pa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var ur=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Pa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var us=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function il(e){if(!e)return"";let t=_m(e);return Sp(t!==null?t:e)}function _m(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Sp(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);l=h.pop()??"";for(let W of h){let L=W.split(`
|
|
14
|
+
`),R="message",q="",$=null;for(let de of L)de.startsWith("event:")?R=de.replace("event:","").trim():de.startsWith("data:")?q+=de.replace("data:","").trim():de.startsWith("id:")&&($=de.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!q){K();continue}let ce;try{ce=JSON.parse(q)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let je=R!=="message"?R:ce.type??"message";if(this.onSSEEvent?.(je,ce),this.parseSSEEvent){T.current=v;let de=await this.handleCustomSSEEvent(ce,n,T,g,c,B);if(T.current&&T.current!==v&&(v=T.current),de){K();continue}}et.push({payloadType:je,payload:ce}),Le(),K()}}Le()}};function Ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Lr(e){return{type:"text",text:e}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qn=[...yu,...Yh];function Xh(e){return yu.includes(e)||e.startsWith("image/")}function Ya(e){return Xh(e.type)}async function bu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function vu(e,t=Qn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wu(e,t){let n=Qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var xu=16e3,Jh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:xu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mp(Jh);if(r!==this.callGeneration){u.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ny(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let w=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let u=l.inputBuffer.getChannelData(0),d=new Int16Array(u.length);for(let c=0;c<u.length;c++){let f=Math.max(-1,Math.min(1,u[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=ty(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Go=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!Go.isSupported())throw new Error("Browser speech recognition not supported");return new Go(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Cu(e){if(e?.type==="custom"&&e.custom)return Pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Pr({type:"runtype",runtype:e.runtype});if(Go.isSupported())return Pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zl(e){try{return Cu(e),!0}catch{return!1}}function Xa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ir=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function jl(e){if(!e)return"";let t=oy(e);return Au(t!==null?t:e)}function oy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Au(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
|
-
`),t.trim()}var
|
|
16
|
+
`),t.trim()}var Su=null;var Vl=()=>Su?Su():import("./runtype-tts-entry-UJAEF7NZ.js");var ry=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function sy(e,t){return ry.some(n=>e[n]!==t[n])}function ql(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),Mp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ep=e=>or(e)||e===Un,Ia=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new us(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(or(n.name)||n.name===Un&&po(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ds(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||ll().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return al(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ur.isSupported()?new ur({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return ll().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=pr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!Um(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new ds(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?Ea():n==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:g}=o,x={id:p??(r==="user"?Ea():r==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...g!==void 0&&{rawContent:g}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),Tu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Mu=e=>Cr(e)||e===Xn,Qa=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Is(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Cr(n.name)||n.name===Xn&&vo(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ls(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Vl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return zl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ir.isSupported()?new Ir({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Vl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:u})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new u(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Pr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let u=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=u.id}if(l){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let u=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=u.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!sy(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Ls(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:u,streaming:d=!1,voiceProcessing:c,rawContent:f}=t,g={id:a??(n==="user"?Ka():n==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...f!==void 0&&{rawContent:f}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:u,createdAt:d,sequence:c,streaming:f=!1,voiceProcessing:w,rawContent:g}=o,C={id:u??(r==="user"?Ka():r==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:u}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...u!==void 0&&{sequence:u}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
20
|
`),a=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];s&&d.push(dr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(dr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ea(),s=cr();this.activeAssistantMessageId=null;let a=n?.contentParts&&yp(n.contentParts)?ka:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let w=cl(c,this.config.errorMessage);if(w){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=cr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=cl(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let v=c[g],x=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Un?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??d;if(d===Un)return{dedupeKey:u,resumeKey:g,output:ol(),toolMessage:p,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let x=this.client.executeWebMcpToolCall(d,p.toolCall?.args,v.signal),P;if(!x)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await x}catch(F){let k=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return k||this.callbacks.onError?.(F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(p,fs(k?"Aborted by cancel()":Mp(F)),w),this.webMcpInflightKeys.delete(u),null}return v.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:P,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Un?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,fs("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(x){this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Un,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",g=a;try{let v;if(d?v=ol():u?v=await u:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),a);return}let x=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,x,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||x||p.aborted)&&this.markWebMcpToolComplete(t,fs(x||p.aborted?"Aborted by cancel()":Mp(v)),a),x||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=io(this.config.features?.artifacts,t),r=ns(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=io(this.config.features?.artifacts,n),s=ns(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>cl(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=cr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=il(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Pa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=il(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Ep(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,v=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&Ep(g)&&r.toolCall?.status==="complete";(u||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ra={allowedTypes:zn,maxFileSize:10*1024*1024,maxFiles:4};function zm(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function jm(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var gs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ra.allowedTypes,maxFileSize:t.maxFileSize??Ra.maxFileSize,maxFiles:t.maxFiles??Ra.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ra.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=wp(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await vp(n),s=La(n)?URL.createObjectURL(n):null,a={id:zm(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=La(t.file),o=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=jm(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=y("span");d.textContent=xp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Lt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Wa=Vt+1;var Vm=8,qm=8,dl=10,pl=new WeakMap,kp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Km=e=>{let t=e.getRootNode?.();return kp(t)?t:e.ownerDocument.body},ul=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ot(e){pl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Vm,viewportPadding:a=qm}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,u=null,w=!1,g=!1,v=!1,x=()=>(typeof o=="function"?o():o).trim(),P=()=>{u?.(),u=null,d?.remove(),d=null,c=null},F=()=>{if(!d)return;let ne=l(),D=p(),_=t.getBoundingClientRect(),Y=d.getBoundingClientRect(),ge=ne.documentElement.clientWidth||D.innerWidth,he=ne.documentElement.clientHeight||D.innerHeight,ce=ge-a-Y.width,Z=_.left+_.width/2-Y.width/2,de=ul(Z,a,ce),te=_.top-a,ie=he-a-_.bottom,J=Y.height+s,fe=te>=J||te>=ie?"top":"bottom",Ce=fe==="top"?_.top-s-Y.height:_.bottom+s,ye=he-a-Y.height,xe=ul(Ce,a,ye),ve=_.left+_.width/2,Ae=Math.max(dl,Y.width-dl),Te=ul(ve-de,dl,Ae);d.dataset.placement=fe,d.style.left=`${de}px`,d.style.top=`${xe}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Te}px`)},k=()=>{if(v||!r||d||!t.isConnected)return;let ne=x(),D=Km(t);if(!ne||!D)return;let _=l(),Y=p();d=_.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Wa),c=_.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=ne,d.appendChild(c);let ge=_.createElement("span");ge.className="persona-control-tooltip__arrow",d.appendChild(ge),D.appendChild(d),F(),d.dataset.state="open";let he=()=>{if(!t.isConnected){P();return}c&&(c.textContent=x()),F()};Y.addEventListener("scroll",he,!0),Y.addEventListener("resize",he);let ce=t.getRootNode(),Z=kp(ce)?ce:_.documentElement,de=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||P()});de?.observe(Z,{childList:!0,subtree:!0}),u=()=>{Y.removeEventListener("scroll",he,!0),Y.removeEventListener("resize",he),de?.disconnect()}},T=()=>{w||g?k():P()},M=()=>{let ne=p();(!ne.matchMedia||!ne.matchMedia("(hover: none)").matches)&&(w=!0,T())},U=()=>{w=!1,T()},j=()=>{g=!0,T()},A=()=>{g=!1,T()},V=ne=>{ne.key==="Escape"&&(w=!1,g=!1,P())};n.addEventListener("mouseenter",M),n.addEventListener("mouseleave",U),t.addEventListener("focus",j),t.addEventListener("blur",A),t.addEventListener("keydown",V);let K={get isOpen(){return d!==null},show:k,hide:P,reposition:F,destroy:()=>{v||(v=!0,P(),n.removeEventListener("mouseenter",M),n.removeEventListener("mouseleave",U),t.removeEventListener("focus",j),t.removeEventListener("blur",A),t.removeEventListener("keydown",V),pl.delete(t))}};return pl.set(t,K),K}function Lp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=y("div","persona-send-button-wrapper"),d=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Ot({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:Lw,load:Gm}=nr({fallbackImport:()=>import("./context-mentions-BTSTIBFC.js")});var fl=Gm;var{setLoader:Rw,load:Qm}=nr({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Pp=Qm;function ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ie("span",{className:On("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=y("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ie("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Ip(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Pd(t).filter(T=>T.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(T=>T.sources.some(M=>typeof M.matchCommand=="function")),r=T=>o.some(M=>M.trigger?M.position==="line-start"?T.split(`
|
|
23
|
-
`).some(
|
|
24
|
-
`)[0]).startsWith(M.trigger):!1),s=(T,M)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:M}))}catch{}},a=Ie("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,u=null,w=null,g=null,v=()=>{if(l)return Promise.resolve(l);if(p)return p;let T=fl().then(M=>(l=M.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:k,emit:s}),l)).catch(M=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",M),p===T&&(p=null),null));return p=T,T},x=()=>{Pp().then(T=>{let M=T.mountInlineComposer({textarea:e.textarea,renderToken:j=>ms(j,{render:t.renderMentionToken}),onMentionRemoved:j=>l?.untrackMention(j)});c=M.input,u=M.destroy;let U=d;U.replaceWith(M.element),d=M.element,g={next:M.element,prev:U},w?.(M.element,U),l?l.rebindComposer(M.input):p&&p.then(j=>j?.rebindComposer(M.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};t.display==="inline"&&x();let P=[],F=new Map;for(let T of n){if(!T.showButton)continue;let M=Lp({config:{...t,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(U=>U?.openMenu(T.trigger))}});P.push(M),F.set(T.trigger,M.button)}let k=(T,M,U)=>{let j=F.get(M);j&&(j.setAttribute("aria-expanded",T?"true":"false"),T?j.setAttribute("aria-controls",U):j.removeAttribute("aria-controls"))};return{affordanceButtons:P.map(T=>T.wrapper),contextRow:a,handleInput:T=>{if(l){l.handleInput();return}if(!Ld(T))return;let M=d,U=M.selectionStart??0;kd(M.value,U,n)&&v().then(j=>j?.handleInput())},handleKeydown:T=>{if(l?.isMenuOpen())return l.handleKeydown(T);if(T.key==="Backspace"&&l?.hasMentions()&&!g){let M=d,U=M.selectionStart===0&&M.selectionEnd===0;if((M.value.length===0||U)&&l.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async T=>r(T)?(l??await v())?.dispatchInlineCommand(T)??null:null,clear:()=>l?.clear(),prefetch:()=>{fl().catch(()=>{})},onComposerSwap:T=>{w=T,g&&T(g.next,g.prev)},destroy:()=>{l?.destroy(),u?.();for(let T of P)T.wrapper.remove();a.remove()}}}var Rp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function hs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Rp(s)&&Rp(r)?n[o]=hs(s,r):n[o]=r}return n}var jn="min(440px, calc(100vw - 24px))",Hp="440px",Xm={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Xm,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Wp(e,t){if(!(!e&&!t))return e?t?hs(e,t):e:t}function Ha(e){return e?{...rt,...e,theme:Wp(rt.theme,e.theme),darkTheme:Wp(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=rt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=rt.features?.streamAnimation,p=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&p===void 0?void 0:{...l,...p},x=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...v!==void 0?{streamAnimation:v}:{},...x!==void 0?{askUserQuestion:x}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var Ba="16px",Da="transparent",Jm={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ym={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Zm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:jn,maxWidth:Hp,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ba,canvasBackground:Da},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Xt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Xt(e,o):o}function Bp(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Xt(e,a);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eh(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Dp(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Dp(s,r):n[o]=r}return n}function th(e,t){return t?Dp(e,t):e}function fr(e,t={}){let n={palette:Jm,semantic:Ym,components:Zm},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:th(n.components,e?.components)};if(t.validate!==!1){let r=eh(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Fp(e){let t=Bp(e),n={};for(let[A,V]of Object.entries(t)){let K=A.replace(/\./g,"-");n[`--persona-${K}`]=V.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Ba,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Da,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let w=d?.toggleGroup;w&&(w.gap&&(n["--persona-toggle-group-gap"]=w.gap),w.borderRadius&&(n["--persona-toggle-group-radius"]=w.borderRadius));let g=d?.artifact;if(g?.toolbar){let A=g.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Xt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(g?.tab){let A=g.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(g?.pane){let A=g.pane;if(A.toolbarBackground){let V=Xt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=V}}if(g?.card){let A=g.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(g?.inline){let A=g.inline;A.background&&(n["--persona-artifact-inline-bg"]=Xt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Xt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let v=d?.code;v&&(v.keywordColor&&(n["--persona-code-keyword-color"]=v.keywordColor),v.stringColor&&(n["--persona-code-string-color"]=v.stringColor),v.commentColor&&(n["--persona-code-comment-color"]=v.commentColor),v.numberColor&&(n["--persona-code-number-color"]=v.numberColor),v.tagColor&&(n["--persona-code-tag-color"]=v.tagColor),v.attrColor&&(n["--persona-code-attr-color"]=v.attrColor),v.propertyColor&&(n["--persona-code-property-color"]=v.propertyColor),v.lineNumberColor&&(n["--persona-code-line-number-color"]=v.lineNumberColor),v.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=v.gutterBorderColor),v.background&&(n["--persona-code-bg"]=Xt(e,v.background)??v.background));let x=n["--persona-surface"],P=n["--persona-container"],F=n["--persona-palette-colors-gray-100"]??"#f3f4f6",k=n["--persona-palette-colors-gray-200"]??"#e5e7eb",T=n["--persona-palette-colors-gray-300"]??"#d1d5db",M=!P||P===x,U=M?F:P,j=M?k:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??U,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??j,M&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??T),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??U,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??U,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??U,n}var nh={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Np=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},gl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",oh=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":gl()},Op=e=>oh(e),rh=e=>fr(e),sh=e=>fr({...e,palette:{...e?.palette,colors:{...nh.colors,...e?.palette?.colors}}},{validate:!1}),gr=e=>{let t=Op(e),n=Np(e?.theme),o=Np(e?.darkTheme);return t==="dark"?sh(hs(n??{},o??{})):rh(n)},ah=e=>Fp(e),ys=(e,t)=>{let n=gr(t),o=ah(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Op(t))},Fa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(gl())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(gl());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Ln(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function _p(e){let t=Ln(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Na(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,u=r.contentParts.length>0;if(l){let d=[];s&&d.push(Lr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(u){let d=[];a&&d.push(Lr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ka(),s=kr();this.activeAssistantMessageId=null;let a=n?.contentParts&&hu(n.contentParts)?Ga:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let c=this.messages.find(f=>f.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:u.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let w=ql(c,this.config.errorMessage);if(w){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=kr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=ql(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let u=this.config.approval,d=u&&typeof u=="object"?u.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let f=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let w=typeof f[0]?.question=="string"?f[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,u=t.toolCall?.args,d=Array.isArray(u?.questions)?u.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([f,w])=>`${f}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((f,w)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let v=c[g],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Xn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{let d=u.toolCall?.name,c=u.toolCall?.id;if(!d||!c)return null;let f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(f),o.push(f);let w=this.markWebMcpToolRunning(u),g=u.agentMetadata?.webMcpToolCallId??d;if(d===Xn)return{dedupeKey:f,resumeKey:g,output:_l(),toolMessage:u,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,u.toolCall?.args,v.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch(B){let S=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return S||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(u,Ws(S?"Aborted by cancel()":Tu(B)),w),this.webMcpInflightKeys.delete(f),null}return v.signal.aborted?(this.markWebMcpToolComplete(u,Ws("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:T,toolMessage:u,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let u={};for(let c of l)u[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,u,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Xn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Ws("Aborted by cancel()"),c.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:u}=l;this.setStreaming(!0);let d=o===Xn,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,u),w="execute",g=a;try{let v;if(d?v=_l():f?v=await f:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),u.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:u})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||u.aborted)&&this.markWebMcpToolComplete(t,Ws(C||u.aborted?"Aborted by cancel()":Tu(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ho(this.config.features?.artifacts,t),r=xs(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ho(this.config.features?.artifacts,n),s=xs(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ql(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=kr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=jl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Xa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=jl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,f=n.approval;a.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,u=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Mu(l)&&u&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${u}:${d}`,f=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,v=r.agentMetadata?.executionId===u&&r.toolCall?.id===d&&g!==void 0&&Mu(g)&&r.toolCall?.status==="complete";(f||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ja={allowedTypes:Qn,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Rs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ja.allowedTypes,maxFileSize:t.maxFileSize??Ja.maxFileSize,maxFiles:t.maxFiles??Ja.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ja.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=vu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await bu(n),s=Ya(n)?URL.createObjectURL(n):null,a={id:ay(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ya(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=iy(t.file.type),u=ae(l,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let d=b("span");d.textContent=wu(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Nt=1e5,Za=Nt+1;var ly=8,cy=8,Kl=10,Gl=new WeakMap,Eu=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,dy=e=>{let t=e.getRootNode?.();return Eu(t)?t:e.ownerDocument.body},Yl=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function _t(e){Gl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=ly,viewportPadding:a=cy}=e,l=()=>t.ownerDocument,u=()=>l().defaultView??window,d=null,c=null,f=null,w=!1,g=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),T=()=>{f?.(),f=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let te=l(),A=u(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),ie=te.documentElement.clientWidth||A.innerWidth,Y=te.documentElement.clientHeight||A.innerHeight,ue=ie-a-Q.width,X=G.left+G.width/2-Q.width/2,ge=Yl(X,a,ue),Z=G.top-a,pe=Y-a-G.bottom,ee=Q.height+s,me=Z>=ee||Z>=pe?"top":"bottom",we=me==="top"?G.top-s-Q.height:G.bottom+s,he=Y-a-Q.height,ke=Yl(we,a,he),Ne=G.left+G.width/2,Ue=Math.max(Kl,Q.width-Kl),Qe=Yl(Ne-ge,Kl,Ue);d.dataset.placement=me,d.style.left=`${ge}px`,d.style.top=`${ke}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Qe}px`)},S=()=>{if(v||!r||d||!t.isConnected)return;let te=C(),A=dy(t);if(!te||!A)return;let G=l(),Q=u();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Za),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=te,d.appendChild(c);let ie=G.createElement("span");ie.className="persona-control-tooltip__arrow",d.appendChild(ie),A.appendChild(d),B(),d.dataset.state="open";let Y=()=>{if(!t.isConnected){T();return}c&&(c.textContent=C()),B()};Q.addEventListener("scroll",Y,!0),Q.addEventListener("resize",Y);let ue=t.getRootNode(),X=Eu(ue)?ue:G.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||T()});ge?.observe(X,{childList:!0,subtree:!0}),f=()=>{Q.removeEventListener("scroll",Y,!0),Q.removeEventListener("resize",Y),ge?.disconnect()}},k=()=>{w||g?S():T()},P=()=>{let te=u();(!te.matchMedia||!te.matchMedia("(hover: none)").matches)&&(w=!0,k())},H=()=>{w=!1,k()},F=()=>{g=!0,k()},N=()=>{g=!1,k()},z=te=>{te.key==="Escape"&&(w=!1,g=!1,T())};n.addEventListener("mouseenter",P),n.addEventListener("mouseleave",H),t.addEventListener("focus",F),t.addEventListener("blur",N),t.addEventListener("keydown",z);let j={get isOpen(){return d!==null},show:S,hide:T,reposition:B,destroy:()=>{v||(v=!0,T(),n.removeEventListener("mouseenter",P),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",F),t.removeEventListener("blur",N),t.removeEventListener("keydown",z),Gl.delete(t))}};return Gl.set(t,j),j}function ku(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",u=b("div","persona-send-button-wrapper"),d=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),u.appendChild(d),_t({anchor:d,trigger:u,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:u}}var{setLoader:aC,load:py}=xr({fallbackImport:()=>import("./context-mentions-BTSTIBFC.js")});var Xl=py;var{setLoader:cC,load:uy}=xr({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Lu=uy;function Hs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ee("span",{className:Pn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=b("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ee("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Pu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Lp(t).filter(k=>k.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(k=>k.sources.some(P=>typeof P.matchCommand=="function")),r=k=>o.some(P=>P.trigger?P.position==="line-start"?k.split(`
|
|
23
|
+
`).some(F=>F.startsWith(P.trigger)):(P.position==="anywhere"?k:k.split(`
|
|
24
|
+
`)[0]).startsWith(P.trigger):!1),s=(k,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${k}`,{detail:P}))}catch{}},a=Ee("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,u=null,d=e.textarea,c=null,f=null,w=null,g=null,v=()=>{if(l)return Promise.resolve(l);if(u)return u;let k=Xl().then(P=>(l=P.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:s}),l)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),u===k&&(u=null),null));return u=k,k},C=()=>{Lu().then(k=>{let P=k.mountInlineComposer({textarea:e.textarea,renderToken:F=>Hs(F,{render:t.renderMentionToken}),onMentionRemoved:F=>l?.untrackMention(F)});c=P.input,f=P.destroy;let H=d;H.replaceWith(P.element),d=P.element,g={next:P.element,prev:H},w?.(P.element,H),l?l.rebindComposer(P.input):u&&u.then(F=>F?.rebindComposer(P.input))}).catch(k=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",k)})};t.display==="inline"&&C();let T=[],B=new Map;for(let k of n){if(!k.showButton)continue;let P=ku({config:{...t,buttonIconName:k.buttonIconName,buttonTooltipText:k.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(H=>H?.openMenu(k.trigger))}});T.push(P),B.set(k.trigger,P.button)}let S=(k,P,H)=>{let F=B.get(P);F&&(F.setAttribute("aria-expanded",k?"true":"false"),k?F.setAttribute("aria-controls",H):F.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(k=>k.wrapper),contextRow:a,handleInput:k=>{if(l){l.handleInput();return}if(!kp(k))return;let P=d,H=P.selectionStart??0;Ep(P.value,H,n)&&v().then(F=>F?.handleInput())},handleKeydown:k=>{if(l?.isMenuOpen())return l.handleKeydown(k);if(k.key==="Backspace"&&l?.hasMentions()&&!g){let P=d,H=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||H)&&l.removeLastChip())return k.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async k=>r(k)?(l??await v())?.dispatchInlineCommand(k)??null:null,clear:()=>l?.clear(),prefetch:()=>{Xl().catch(()=>{})},onComposerSwap:k=>{w=k,g&&k(g.next,g.prev)},destroy:()=>{l?.destroy(),f?.();for(let k of T)k.wrapper.remove();a.remove()}}}var Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Iu(s)&&Iu(r)?n[o]=Bs(s,r):n[o]=r}return n}var Jn="min(440px, calc(100vw - 24px))",Ru="440px",fy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},rt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:fy,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Wu(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function ei(e){return e?{...rt,...e,theme:Wu(rt.theme,e.theme),darkTheme:Wu(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=rt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=rt.features?.streamAnimation,u=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&u===void 0?void 0:{...l,...u},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...g!==void 0?{scrollBehavior:g}:{},...f!==void 0?{artifacts:f}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var ti="16px",ni="transparent",gy={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},my={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},hy={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Jn,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ti,canvasBackground:ni},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Qt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Qt(e,o):o}function Hu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let u=Qt(e,a);u!==void 0&&(t[l]={path:l,value:u,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yy(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Bu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Bu(s,r):n[o]=r}return n}function by(e,t){return t?Bu(e,t):e}function Wr(e,t={}){let n={palette:gy,semantic:my,components:hy},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:by(n.components,e?.components)};if(t.validate!==!1){let r=yy(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Du(e){let t=Hu(e),n={};for(let[A,G]of Object.entries(t)){let Q=A.replace(/\./g,"-");n[`--persona-${Q}`]=G.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ti,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ni,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],a=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=a&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let u=n["--persona-components-markdown-heading-h1-fontSize"];u&&(n["--persona-md-h1-size"]=u);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let w=n["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(n["--persona-md-prose-font-family"]=w),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let g=e.components,v=g?.iconButton;v&&(v.background&&(n["--persona-icon-btn-bg"]=v.background),v.border&&(n["--persona-icon-btn-border"]=v.border),v.color&&(n["--persona-icon-btn-color"]=v.color),v.padding&&(n["--persona-icon-btn-padding"]=v.padding),v.borderRadius&&(n["--persona-icon-btn-radius"]=v.borderRadius),v.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=v.hoverBackground),v.hoverColor&&(n["--persona-icon-btn-hover-color"]=v.hoverColor),v.activeBackground&&(n["--persona-icon-btn-active-bg"]=v.activeBackground),v.activeBorder&&(n["--persona-icon-btn-active-border"]=v.activeBorder));let C=g?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let T=g?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let B=g?.artifact;if(B?.toolbar){let A=B.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(B?.tab){let A=B.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(B?.pane){let A=B.pane;if(A.toolbarBackground){let G=Qt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(B?.card){let A=B.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(B?.inline){let A=B.inline;A.background&&(n["--persona-artifact-inline-bg"]=Qt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let S=g?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=Qt(e,S.background)??S.background));let k=n["--persona-surface"],P=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",F=n["--persona-palette-colors-gray-200"]??"#e5e7eb",N=n["--persona-palette-colors-gray-300"]??"#d1d5db",z=!P||P===k,j=z?H:P,te=z?F:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??te,z&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??N),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var vy={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Fu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ql=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",wy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ql()},Ou=e=>wy(e),xy=e=>Wr(e),Cy=e=>Wr({...e,palette:{...e?.palette,colors:{...vy.colors,...e?.palette?.colors}}},{validate:!1}),Rr=e=>{let t=Ou(e),n=Fu(e?.theme),o=Fu(e?.darkTheme);return t==="dark"?Cy(Bs(n??{},o??{})):xy(n)},Ay=e=>Du(e),Ds=(e,t)=>{let n=Rr(t),o=Ay(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Ou(t))},oi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ql())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ql());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var xo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function Bn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Nu(e){let t=Bn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ri(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
25
25
|
`);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
|
|
26
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
27
|
-
`).length,g=e.artifactType==="markdown"?e.file:void 0,v={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:
|
|
26
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Yo(e){let t=Nu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Co(e){switch(Yo(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Nu(e.path);return t?t.toUpperCase():"File"}}}function _u(e){let t=e.markdown??"";return e.file?{filename:Bn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:ri(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Jl="http://www.w3.org/2000/svg";function $u(e){let t=document.createElementNS(Jl,"svg");t.setAttribute("class",Pn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Jl,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Jl,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var Ao=(e,t,n)=>{let o=n;for(let r of t){let s=b("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Uu(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Ao(e,t,0)}var Zl="persona-artifact-status-label",zu="persona-artifact-status-detail",ju="data-artifact-status-label",ec=new Map,Vu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Hr(e){e&&ec.delete(e)}function Sy(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Co(t):e.artifactType==="component"?"Component":"Document"}function Br(e,t,n){let o=Sy(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,l=ec.get(a);e.status!=="complete"&&l===void 0&&(l=Vu(),ec.set(a,l));let u=l===void 0?0:Math.max(0,Vu()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:c.length,w=d||c===""?0:c.split(`
|
|
27
|
+
`).length,g=e.artifactType==="markdown"?e.file:void 0,v={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:w,elapsedMs:u,content:()=>d?"":c,surface:n};try{let C=s(v);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function Ty(e){e.className=Zl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Xo(e,t,n){let o=e.querySelector(`:scope > .${Zl}`);o||(o=b("span",Zl),e.appendChild(o)),o.getAttribute(ju)!==t.label&&(Ty(o),Uu(o,t.label,n),o.setAttribute(ju,t.label));let r=e.querySelector(`:scope > .${zu}`),s=t.detail;s?(r||(r=b("span",zu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var My={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Ey=15e4,si={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function ky(e,t){let n=(e||"").trim().toLowerCase();if(n&&si[n])return si[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(si[r])return si[r]}}return null}function ai(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let l of t){l.re.lastIndex=o;let u=l.re.exec(e);if(u&&u.index===o&&u[0].length>0){s(o);let d=l.map?l.map(u[0]):l.type;n.push({type:d,value:u[0]}),o+=u[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var Ly=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Py=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>Ly.has(e)?"keyword":"plain"}];function qu(e){return ai(e,Py)}var Iy=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Wy(e){let t=ai(e,Iy);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Ry=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Ku(e){let t=ai(e,Ry),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let l=t[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Hy=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function By(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),l=a===-1?o:a+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),l=a===-1?o:a+1,u=e.slice(r,l);for(let c of ai(u,Hy))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(u);if(d&&!/\/>\s*$/.test(u)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=w?r+w.index:o,v=e.slice(r,g),C=c==="script"?qu(v):Ku(v);for(let T of C)t.push(T);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Dy(e,t){switch(t){case"html":return By(e);case"css":return Ku(e);case"js":return qu(e);case"json":return Wy(e)}}function Fy(e){let t=Tp(),n=b("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=My[r];if(a){let l=b("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
28
28
|
`);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
29
|
-
`)),n=y("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Qp(e,t,n){let o=e.length<=dh?ph(t,n):null,r=o?vh(e,o):[{type:"plain",value:e}];return wh(r)}function yr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Wa)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let P=ae(g.icon,16,"currentColor",1.5);P&&v.appendChild(P)}let x=document.createElement("span");x.textContent=g.label,v.appendChild(x),v.addEventListener("click",P=>{P.stopPropagation(),c(),n(g.id)}),a.appendChild(v)}let l=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Pt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,p=y("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Fo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=y("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ae(t,s??14,"currentColor",2);w&&c.appendChild(w)}let u=y("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,g]of Object.entries(p))c.setAttribute(w,g);return c}function $a(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=y("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=Pt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=y("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Xp(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=e,d=y("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=y("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=ae(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=yr({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",g=>{g.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let g=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var Ua="persona-artifact-custom-action-btn";function br(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Ua+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+Ua+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Fo({icon:e.icon,label:e.label,className:Ua+(n?" persona-artifact-doc-copy-btn":"")}):o=Pt({icon:e.icon,label:e.label,className:Ua+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function vs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Jp(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Ln(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?fo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let x=t?.config?.features?.artifacts,P={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},F=hr(P,x,"card");Do(v,F,x)}else s&&mr(s),v.textContent=d;if(w.append(g,v),c.append(u,w),a==="complete"){let x=t?.config?.features?.artifacts?.cardActions;if(x&&x.length>0){let F={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let k of x)try{if(k.visible===void 0||k.visible(F)){let T=br(k);T.setAttribute("data-artifact-custom-action",k.id),T.className=`${T.className} persona-flex-shrink-0`,c.append(T)}}catch{}}let P=Fo({label:"Download",className:"persona-flex-shrink-0"});P.title=`Download ${r}`,P.setAttribute("data-download-artifact",s),c.append(P)}return c}var za=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Jp(e,t)});if(l)return l}return Jp(e,t)};var mo=new WeakMap;function bl(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=mo.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function nu(e){return mo.has(e)}function xh(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Yp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Ln(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?fo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ch(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Zp=180,Ah=240,Sh=.8,Th=300,Mh=500,Eh="cubic-bezier(0.2, 0, 0, 1)",eu=240,kh=.35;function Lh(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Zp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let F of a)F.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(Mh,Math.max(Th,Ah+d*Sh))),u=Math.round(c*kh),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=w?w.animate([{opacity:0},{opacity:1}],{duration:eu,delay:u,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Eh});e.style.height=`${p}px`;let x=!1,P=()=>{x||(x=!0,l(),r())};Promise.allSettled([v.finished,g?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+eu)+120)},Zp)}function Ph(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var ws="--persona-artifact-inline-body-height";function Ih(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:g}}function tu(e,t){let n=xh(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Ph(o),p=o?.inlineActions??[],d=Ih(o),c=d.completeDisplay==="card",u=null,w=n,g=y("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let v=te=>za(Ch(te),t),x=te=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(ws),g.replaceChildren(v(te)),mo.set(g,ie=>{g.replaceChildren(v(ie))})};if(c&&n.status==="complete")return x(n),g;let P=ja(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),F=y("div","persona-artifact-inline-body");F.appendChild(P.el);let k=te=>{let ie=te.status!=="complete",J=ie?d.streamingHeight:d.completeHeight,fe=typeof J=="number";fe?g.style.setProperty(ws,`${J}px`):g.style.removeProperty(ws);let Ce=!!P.el.querySelector(".persona-code-pre"),ye=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");F.classList.toggle("persona-artifact-content-flush",Ce),F.classList.toggle("persona-artifact-inline-body--sized",fe&&ye),F.classList.toggle("persona-artifact-inline-body--cap",!ie&&!ye&&typeof d.completeHeight=="number")},T=n.status,M=(te,ie)=>{T!=="complete"&&te.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(ws,`${d.completeHeight}px`):g.style.removeProperty(ws),ru(F,ie?.suppressTransition?"none":d.transition,te.id,()=>{P.update(te),k(te)})):P.update(te),k(te),T=te.status};k(n);let U=d.overflow==="clip"&&a&&!!n.id;if(U&&(F.setAttribute("data-expand-artifact-inline",n.id),F.setAttribute("role","button"),F.setAttribute("tabindex","0"),F.classList.add("persona-cursor-pointer"),F.setAttribute("aria-label",`Open ${Yp(n).title} in panel`)),!r)return g.appendChild(F),mo.set(g,M),g;let j=y("div","persona-artifact-inline-chrome");j.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let A=y("div","persona-artifact-inline-chrome-lead"),V=y("span","persona-flex persona-items-center persona-flex-shrink-0"),K=ae("file-text",16,"currentColor",2);K&&V.appendChild(K);let ne=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),D=y("span","persona-artifact-inline-type");A.append(V,ne,D);let _=y("div","persona-artifact-inline-chrome-actions"),Y=y("span","persona-flex persona-items-center persona-gap-1"),ge=()=>u??d.viewMode,he=l?$a({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ge(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:te=>{let ie=te==="source"?"source":"rendered";ie!==ge()&&(u=ie,P.update(w),k(w))}}):null,ce=s?Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ce&&n.id&&ce.setAttribute("data-copy-artifact",n.id);let Z=a?Pt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Z&&n.id&&Z.setAttribute("data-expand-artifact-inline",n.id),_.appendChild(Y),he&&_.appendChild(he.element),ce&&_.appendChild(ce),Z&&_.appendChild(Z),j.append(A,_),g.append(j,F);let de=te=>{let{title:ie,typeLabel:J}=Yp(te);ne.textContent=ie,ne.title=ie,U&&F.setAttribute("aria-label",`Open ${ie} in panel`);let fe=te.status!=="complete";if(fe){D.classList.contains("persona-artifact-inline-status")||(D.className="persona-artifact-inline-status",D.removeAttribute("data-preserve-animation"),D.replaceChildren());let Ce=hr(te,o,"inline-chrome");Do(D,Ce,o)}else mr(te.id),D.className="persona-artifact-inline-type",D.removeAttribute("data-preserve-animation"),D.replaceChildren(),D.textContent=J;if(ce&&ce.classList.toggle("persona-hidden",fe),he){let Ce=te.artifactType==="markdown"?te.file:void 0,ye=!1;if(!fe&&Ce&&d.viewMode!=="source"){let xe=bs(Ce);xe==="markdown"?ye=!0:(xe==="html"||xe==="svg")&&(ye=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ye),he.setSelected(ge())}if(Y.replaceChildren(),!fe&&p.length>0){let Ce=vs(te);if(Ce)for(let ye of p)try{if(ye.visible===void 0||ye.visible(Ce)){let xe=br(ye,{documentChrome:!0});xe.setAttribute("data-artifact-custom-action",ye.id),xe.classList.add("persona-flex-shrink-0"),Y.appendChild(xe)}}catch{}}};return de(n),mo.set(g,(te,ie)=>{if(c&&T!=="complete"&&te.status==="complete"){let J=g.isConnected?g.getBoundingClientRect().height:0;T="complete";let fe=te,Ce=!1,ye=xe=>{fe=xe,Ce=!0};mo.set(g,ye),Lh(g,J,{swap:()=>{x(fe),Ce=!1,mo.set(g,ye)},onSettled:()=>{Ce?x(fe):mo.set(g,xe=>{g.replaceChildren(v(xe))})}});return}(te.status!=="complete"||te.id!==w.id)&&(u=null),w=te,M(te,ie),de(te)}),g}var ou=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>tu(e,t)});if(l)return l}return tu(e,t)};var vl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Vn=new vl;Vn.register("PersonaArtifactCard",za,{bubbleChrome:!1});Vn.register("PersonaArtifactInline",ou,{bubbleChrome:!1});function xs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Na(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var wl=!1;function Rh(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ru(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||wl||s){o();return}wl=!0;let a=Rh(n);e.style.setProperty("view-transition-name",a);let l=()=>{wl=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Wh="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Hh="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Bh(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Dh(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Fh=220;function Nh(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Oh(e){return`
|
|
30
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function _h(e,t,n){let o=y("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=y("div","persona-artifact-frame-loading-indicator");r.appendChild(Up());let s=null;return n.label!==!1&&(s=y("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function $h(e,t,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(T=>clearTimeout(T)),d.clear()},u=(T,M)=>{let U=setTimeout(()=>{d.delete(U),T()},M);d.add(U)},w=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let T=_h(r,s,o);a=T.el,e.appendChild(a),l=Date.now(),o.label!==!1&&u(T.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,Fh))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",F):t.removeEventListener("load",k)},P=()=>{if(p||(p=!0,x(),c(),!a))return;let T=Math.max(0,o.minVisibleMs-(Date.now()-l));T>0?u(v,T):v()};function F(T){if(n===null)return;let M=T.data;!M||M.persona!=="artifact-preview-ready"||M.token!==n||T.source===t.contentWindow&&P()}function k(){let T=M=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>M()):setTimeout(M,0)};T(()=>T(()=>P()))}return u(g,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",F):t.addEventListener("load",k),()=>{p=!0,c(),x(),w()}}function ja(e,t){let{config:n}=t,o=t.registry??Vn,r=t.bodyLayout,s=n.markdown?ma(n.markdown):null,a=ha(n.sanitize),l=e,p=!1,d=Z=>{let de=_n()!==null;s&&!de&&!p&&(p=!0,ga(()=>ce(l)));let te=s?s(Z):ao(Z);return s&&de&&a?a(te):te},c=y("div","persona-artifact-preview-body"),u=null,w=null,g=null,v=()=>{g&&(g(),g=null),u=null,w=null},x=null,P=null,F=null,k=!1,T=()=>{x=null,P=null,F=null,k=!1},M=null,U=null,j=()=>{M=null,U=null},A=40,V=0,K=Z=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>Z()):setTimeout(Z,0),ne=Z=>Z.scrollHeight-Z.clientHeight-Z.scrollTop<=A,D=Z=>{if(!r)return;let de=Z.scrollHeight-Z.clientHeight>1,te=Z.scrollHeight-Z.clientHeight-Z.scrollTop;Z.classList.toggle("persona-artifact-fade-top",r.fadeTop&&de&&Z.scrollTop>1),Z.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&de&&te>1)},_=Z=>{V||(V=K(()=>{V=0,Z.scrollTop=Z.scrollHeight,D(Z)}))},Y=(Z,de,te,ie)=>{let J=!!r,fe=te.id+"|"+(J?"w":"p");if(!x||F!==fe||x.parentElement!==c){v(),j(),c.replaceChildren();let xe=y("pre",Wh+" persona-code-pre"),ve=y("code","persona-code");if(xe.appendChild(ve),J){let Ae=y("div","persona-artifact-source-window");if(Ae.appendChild(xe),c.appendChild(Ae),!(r?.overflow==="clip")&&typeof Ae.addEventListener=="function"){let qe=()=>Ae.scrollHeight-Ae.clientHeight>1;Ae.addEventListener("scroll",()=>{ne(Ae)&&(k=!1),D(Ae)},{passive:!0}),Ae.addEventListener("wheel",ze=>{qe()&&ze.deltaY<0&&(k=!0)},{passive:!0}),Ae.addEventListener("touchmove",()=>{qe()&&(k=!0)},{passive:!0})}x=Ae}else c.appendChild(xe),x=xe;P=ve,F=fe}let Ce=J?x:null;Ce&&(Ce.classList.toggle("persona-artifact-source-window--fixed",ie),Ce.classList.toggle("persona-artifact-source-window--clip",ie&&r?.overflow==="clip"));let ye=Ce?ne(Ce):!0;if(P.replaceChildren(Qp(Z,de?.language,de?.path)),Ce){let xe=te.status!=="complete";ie&&xe&&r?.followOutput&&!k&&ye?_(Ce):xe||(k=!1),D(Ce)}},ge=Z=>{v(),T(),j(),c.replaceChildren();let de=y("div",Hh);de.innerHTML=d(Z),c.appendChild(de)},he=Z=>{let de=Z.id,te=n.features?.artifacts,ie=hr(Z,te,"status-body");if(M&&U===de&&M.parentElement===c){let Ce=M.querySelector(".persona-artifact-status-view-text");Ce&&Do(Ce,ie,te);return}v(),T(),c.replaceChildren();let J=y("div","persona-artifact-status-view"),fe=y("div","persona-artifact-status-view-text");Do(fe,ie,te),J.appendChild(fe),c.appendChild(J),M=J,U=de},ce=Z=>{l=Z;let de=t.resolveViewMode?.(Z)??r?.viewMode??"rendered",te=Z.artifactType==="markdown"?Z.file:void 0,ie=Z.status!=="complete";ie||mr(Z.id);let J=ie?r?.streamingHeight:r?.completeHeight,fe=!!r&&typeof J=="number";if(r?.streamingView==="status"&&ie){he(Z);return}if(te){let ye=Na(Z.markdown??""),xe=bs(te),ve=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ie&&de==="rendered"&&ve&&(xe==="html"||xe==="svg")){let Te=Z.id+"\0"+ye;if(u&&w===Te&&u.parentElement===c)return;T(),j(),v(),c.replaceChildren();let qe=n.features?.artifacts?.filePreview,ze=qe?.iframeSandbox??"allow-scripts";!qe?.dangerouslyAllowSameOrigin&&ze.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),ze=ze.split(/\s+/).filter(It=>It&&It!=="allow-same-origin").join(" "));let Me=Dh(qe?.loading),Pe=y("div","persona-artifact-frame"),Ke=y("iframe","persona-artifact-iframe");Ke.setAttribute("sandbox",ze),Ke.setAttribute("data-artifact-id",Z.id);let Wt=null;Me.enabled&&Me.injectReadySignal?(Wt=Nh(),Ke.srcdoc=ye+Oh(Wt)):Ke.srcdoc=ye,Pe.appendChild(Ke),c.appendChild(Pe),Me.enabled&&(g=$h(Pe,Ke,Wt,Me,Z.id,n)),u=Pe,w=Te;return}if(v(),!ie&&xe==="markdown"&&de==="rendered"){ge(ye);return}Y(ye,{language:te.language,path:te.path},Z,fe);return}if(Z.artifactType==="markdown"){if(de==="source"){v(),Y(Z.markdown??"",void 0,Z,fe);return}ge(Z.markdown??"");return}v(),T(),j(),c.replaceChildren();let Ce=Z.component?o.get(Z.component):void 0;if(Ce){let xe={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ve=Ce(Z.props??{},xe);if(ve){c.appendChild(ve);return}}catch{}}c.appendChild(Bh(Z))};return ce(e),{el:c,update(Z){ce(Z)}}}import{Idiomorph as Uh}from"idiomorph";var Va=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Uh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var su=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var xl={index:-1,draft:""};function au(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function iu(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function lu(){return new Map}function cu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function du(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function uu(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Pn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ho(e,t){return Pn(e)-e.scrollTop<=t}function Ka(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Ga(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function fu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},zh=["pre","code","a","script","style"],Qa=e=>({type:e?.type??Cs.type,placeholder:e?.placeholder??Cs.placeholder,speed:e?.speed??Cs.speed,duration:e?.duration??Cs.duration,buffer:e?.buffer??Cs.buffer}),jh=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],yu=new Map;for(let e of jh)yu.set(e.name,e);var vr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:yu.get(e)??null,Xa=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
-
`);return s<0?"":e.slice(0,s)}return e},Vh=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},qh=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Cl=/\s/,Kh=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Gh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Cl.test(s[l])){let p=l;for(;p<s.length&&Cl.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!Cl.test(s[d]);)p.appendChild(Vh(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,e)},Qh=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(qh(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},As=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??zh).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Kh(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Gh:Qh;for(let u of l)c(u,n,d);return r.innerHTML},Ja=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ss=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},hu=new WeakMap,Xh=(e,t)=>{if(!e.styles)return;let n=hu.get(t);if(n||(n=new Set,hu.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Al=new WeakMap,Jh=(e,t)=>{if(!e.onAttach)return;let n=Al.get(t);if(n||(n=new Map,Al.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},bu=e=>{let t=Al.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ya=(e,t)=>{Xh(e,t),Jh(e,t)};function Sl(e,t=Vt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Ts=0,yo=null;function Tl(e=document){if(Ts++,Ts===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;yo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Ts=Math.max(0,Ts-1),Ts===0&&yo)){let n=e.body,o=e.defaultView??window;n.style.overflow=yo.originalOverflow,n.style.position=yo.originalPosition,n.style.top=yo.originalTop,n.style.width=yo.originalWidth,o.scrollTo(0,yo.scrollY),yo=null}}}var Ms={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Dt=e=>(e?.launcher?.mountMode??"floating")==="docked",Es=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",hn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ms.side,width:t?.width??Ms.width,animate:t?.animate??Ms.animate,reveal:t?.reveal??Ms.reveal,maxHeight:t?.maxHeight??Ms.maxHeight}};var Ml=e=>e==="followUp"?"follow-up":e,Yh=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Zh=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},vu=new WeakSet,ey=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,ty=e=>{ey()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Za=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let u=getComputedStyle(e).direction==="rtl",w=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),g=4,v=w<=g,x=w>=c-g,P=u?!x:!v,F=u?!v:!x;e.toggleAttribute("data-scroll-left",P),e.toggleAttribute("data-scroll-right",F)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,u,w,g,v,x)=>{e.replaceChildren(),t.length=0,n.length=0;let P=x?.source??"config",F=x?.surface??(P==="config"?"starter":"followUp"),k=F==="followUp",T=x?.variant??"chip",M=x?.behavior??"send",U=x?.overflow??"wrap",j=x?.config??{},A=x?.plugins??[],V=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,K=k?"followUps":"starters";!vu.has(j)&&j.debug===!0&&T!=="chip"&&j.suggestions?.[K]?.overflow!==void 0&&(vu.add(j),console.info(`[persona] suggestions.${K}.overflow applies to the "chip" variant only; the "${T}" variant manages its own stacking.`));let ne=ce=>ce.map(Yh).filter(Z=>Z!==null).map(Z=>({...Z,behavior:Z.behavior??M})),D=ne(c??[]);A.forEach(ce=>{ce.transformSuggestions&&(D=ne(ce.transformSuggestions({suggestions:D.map(Z=>({...Z})),surface:F,source:P,config:j})))});let _=V===void 0?D:D.slice(0,V);if(!_.length){e.hidden=!0,o=null,s();return}if(!k&&(g??u.getMessages()).some(Z=>Z.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ml(F),e.dataset.variant=T,e.dataset.overflow=U;let Y=document.createDocumentFragment(),ge=u.isStreaming();_.forEach((ce,Z)=>{var Ce,ye,xe;let de=ce.behavior,te=()=>{if(u.isStreaming())return;let ve={suggestion:{...ce},surface:F,source:P,behavior:de},Ae=e.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:ve,bubbles:!0,composed:!0,cancelable:!0}));if(k&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:ce.prompt},bubbles:!0,composed:!0})),!!Ae){for(let Te of A)if(Te.onSuggestionSelect?.({suggestion:{...ce},surface:F,source:P,variant:T,config:j})===!1)return;if(de==="fill"){w.value=ce.prompt,w.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),w.focus();return}w.value="",u.sendMessage(ce.prompt)}},ie=()=>{let ve=y("button",`persona-suggestion persona-suggestion--${T}`);if(ve.type="button",ve.disabled=ge,ve.dataset.suggestionId=ce.id,ve.dataset.emphasis=ce.emphasis,ve.dataset.behavior=de,T==="chip"&&(v?.fontFamily&&(ve.style.fontFamily=Zh(v.fontFamily)),v?.fontWeight&&(ve.style.fontWeight=v.fontWeight),v?.paddingX&&(ve.style.paddingLeft=v.paddingX,ve.style.paddingRight=v.paddingX),v?.paddingY&&(ve.style.paddingTop=v.paddingY,ve.style.paddingBottom=v.paddingY)),ce.icon){let Te=ae(ce.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__icon"),ce.iconColor&&(Te.style.color=ce.iconColor),ve.appendChild(Te))}let Ae=y("span","persona-suggestion__copy");if(Ae.appendChild(Ie("span",{className:"persona-suggestion__label",text:ce.label})),ce.description&&Ae.appendChild(Ie("span",{className:"persona-suggestion__description",text:ce.description})),ve.appendChild(Ae),T!=="chip"){let Te=ae("arrow-right",16,"currentColor",1.8);Te&&(Te.classList.add("persona-suggestion__arrow"),ve.appendChild(Te))}return ve.addEventListener("click",te),ve},J=null;for(let ve of A)if(ve.renderSuggestion&&(J=ve.renderSuggestion({suggestion:{...ce},index:Z,surface:F,source:P,variant:T,streaming:ge,config:j,defaultRenderer:ie,select:te}),J))break;J??(J=ie()),(Ce=J.dataset).suggestionId||(Ce.suggestionId=ce.id),(ye=J.dataset).behavior||(ye.behavior=de),(xe=J.dataset).emphasis||(xe.emphasis=ce.emphasis),J instanceof HTMLButtonElement||J.setAttribute("aria-disabled",ge?"true":"false"),Y.appendChild(J),n.push(J),[...J instanceof HTMLButtonElement?[J]:[],...Array.from(J.querySelectorAll("button"))].forEach(ve=>{t.includes(ve)||(ve.disabled=ge,t.push(ve))})}),e.appendChild(Y),a(),l();let he=JSON.stringify({normalized:_,surface:F,variant:T,source:P});he!==o&&(o=he,ty(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:_.map(ce=>({...ce})),surface:F,source:P,variant:T},bubbles:!0,composed:!0})),k&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:_.map(ce=>ce.prompt)},bubbles:!0,composed:!0})))}}};var Sn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var ny="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ei=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=ny,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",p=y("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ie("button",{className:On("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ae(u,s,"currentColor",1);return x?(x.style.display="block",v.appendChild(x)):v.textContent=w,p.appendChild(v),Ot({anchor:v,trigger:p,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:p}},oy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ti=(e,t={})=>{let{wrapperClassName:n=oy,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",g=a.borderRadius??"",v=a.paddingX??"",x=a.paddingY??"",P=a.tooltipText??"Clear chat",F=a.showTooltip??!0,k=y("div",n),T=!!(u||w),M=Ie("button",{className:On("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:T?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),U=ae(p,r,"currentColor",1);return U&&(U.style.display="block",M.appendChild(U)),k.appendChild(M),Ot({anchor:M,trigger:k,text:()=>M.getAttribute("aria-label")??P,enabled:F}),{button:M,wrapper:k}};var Jt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},No=e=>{let{config:t,showClose:n=!0}=e,o=Ie("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=Ie("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let U=parseFloat(s)||24,j=ae(p,U*.6,"currentColor",1);j?d.replaceChildren(j):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let U=y("img");U.src=t.launcher.iconUrl,U.alt="",U.className="persona-rounded-xl persona-object-cover",U.style.height=s,U.style.width=s,d.replaceChildren(U)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Ie("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),w=Ie("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let g=r.clearChat??{},v=g.enabled??!0,x=g.placement??"inline",P=null,F=null;if(v){let j=ti(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=j.button,F=j.wrapper,x==="top-right"&&(F.style.right="48px"),x==="inline"&&o.appendChild(F)}let k=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:M}=ei(t,{showClose:n,wrapperClassName:k});return a!=="top-right"&&o.appendChild(M),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:T,closeButtonWrapper:M,clearChatButton:P,clearChatButtonWrapper:F}},ks=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var ry=e=>{let t=No({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function sy(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=y("div","persona-relative");s.appendChild(r);let a=yr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var ay=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Xp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=y("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Jt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),sy(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let T=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||T()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),T())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Jt.actionIconColor;let v=a.closeButtonIconName??"x",x=ae(v,"28px","currentColor",1);x?g.appendChild(x):g.textContent="\xD7",o&&g.addEventListener("click",o),w.appendChild(g),l.appendChild(w);let P=y("div");P.style.display="none";let F=y("span");return F.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:F,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},wu={default:ry,minimal:ay},iy=e=>wu[e]??wu.default,ni=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=y("div");l.style.display="none";let p=y("span"),d=y("span"),c=y("button");c.style.display="none";let u=y("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=iy(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var oi=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let p=t.style.maxHeight;if(p!==s){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,a());t.style.height=`${p}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},ri=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",w=t.backgroundColor,g=t.textColor,v=y("div","persona-send-button-wrapper"),x=Ie("button",{className:On("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&w||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),P=null,F=null;if(n){let M=parseFloat(t.iconSize??"")||Math.round((parseFloat(u)||24)*.5),U=t.iconStrokeWidth??2,j=g?.trim()||"currentColor";r?(P=ae(r,M,j,U),P?x.appendChild(P):x.textContent=o):x.textContent=o,F=ae(s,M,j,U)}else x.textContent=p;x.setAttribute("aria-label",a),v.appendChild(x),Ot({anchor:x,trigger:v,text:()=>x.getAttribute("aria-label")??"",enabled:c});let k="send";return{button:x,wrapper:v,setMode:M=>{if(M===k)return;k=M;let U=M==="stop"?l:a;if(x.setAttribute("aria-label",U),n){if(P&&F){let j=M==="stop"?F:P;x.replaceChildren(j)}}else x.textContent=M==="stop"?d:p}}},si=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,w=y("div","persona-send-button-wrapper"),g=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=ae(l,d,u||"currentColor",1.5);x?g.appendChild(x):g.textContent="\u{1F3A4}",w.appendChild(g);let P=t.tooltipText??"Start voice recognition",F=t.showTooltip??!1;return Ot({anchor:g,trigger:w,text:()=>g.getAttribute("aria-label")??P,enabled:F}),{button:g,wrapper:w}},ai=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??zn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=y("div","persona-send-button-wrapper"),c=Ie("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=ae(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return Ot({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},ii=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=y("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},li=()=>Ie("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ci=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=li(),r=Ie("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=oi(t);a();let l=ri(t),p=si(t),d=ai(t),c=ii(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Ie("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&g.append(p.wrapper),g.append(l.wrapper),u.append(w,g),r.append(u),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:g,setSendButtonMode:l.setMode}};var xu=()=>{let e=Ie("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Cu=e=>{let{config:t}=e,n=Ie("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=li(),r=ii(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=oi(t);s.style.maxHeight="100px",a();let l=ri(t),p=si(t),d=ai(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ie("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==p?.button&&v.target!==p?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var Au=e=>{let t=e?.launcher?.enabled??!0,n=Dt(e);if(Es(e)){let c=e?.launcher?.composerBar??{},u=y("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Vt);let w=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let g=y("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Vt),{wrapper:u,panel:w,pillRoot:g}}if(n){let c=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Sn[r.position]?Sn[r.position]:Sn["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Vt);let l=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??jn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},di=e=>{let t=Ie("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ml(e)}});return t.hidden=!0,t},ly=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ei(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let j=ti(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=j.button,l=j.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Ie("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ie("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=di("starter"),g=Ie("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},c,u,w),v=y("div","persona-flex persona-flex-col persona-gap-3"),x=di("followUp"),P=e?.layout?.contentMaxWidth;P&&(v.style.maxWidth=P,v.style.marginLeft="auto",v.style.marginRight="auto",v.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,v,x);let k=Ie("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=Cu({config:e}),{root:M,textNode:U}=xu();return n.append(p,r,d,k),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:v,starterSuggestions:w,transcriptSuggestions:x,composerOverlay:k,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:M,peekTextNode:U}},Su=(e,t=!0)=>{if(Es(e))return ly(e,t);let n=Ie("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ni(e,o,{showClose:t}):No({config:e,showClose:t}),a=Ie("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let l=Ie("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ie("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=di("starter"),c=Ie("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Dt(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),w=di("followUp"),g=e?.layout?.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u,w);let x=ci({config:e}),P=e?.layout?.showFooter!==!1;r?ks(n,s,e):(s.header.style.display="none",ks(n,s,e)),n.append(a);let F=Ie("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return P||(x.footer.style.display="none"),n.append(x.footer),n.append(F),{container:n,body:a,messagesWrapper:u,starterSuggestions:d,transcriptSuggestions:w,composerOverlay:F,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,introTitle:l,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var El=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
29
|
+
`)),n=b("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Gu(e,t,n){let o=e.length<=Ey?ky(t,n):null,r=o?Dy(e,o):[{type:"plain",value:e}];return Fy(r)}function Dr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Za)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let T=ae(g.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let C=document.createElement("span");C.textContent=g.label,v.appendChild(C),v.addEventListener("click",T=>{T.stopPropagation(),c(),n(g.id)}),a.appendChild(v)}let l=null;function u(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function f(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:f,destroy:w}}function Wt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,u=b("button","persona-icon-btn"+(s?" "+s:""));u.type="button",u.setAttribute("aria-label",n),u.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&u.appendChild(d),a&&u.addEventListener("click",a),l)for(let[c,f]of Object.entries(l))u.setAttribute(c,f);return u}function Qo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:u}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=b("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ae(t,s??14,"currentColor",2);w&&c.appendChild(w)}let f=b("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),u)for(let[w,g]of Object.entries(u))c.setAttribute(w,g);return c}function ii(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=b("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function u(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let f;c.icon?f=Wt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,u(),o(c.id)}}):(f=b("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{a=c.id,u(),o(c.id)})),f.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:f}),s.appendChild(f)}function d(c){a=c,u()}return{element:s,setSelected:d}}function Yu(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:u}=e,d=b("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=b("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),u&&(d.style.borderRadius=u.borderRadius??"10px",d.style.padding=u.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=u.background??"",d.style.borderColor=u.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=Dr({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",g=>{g.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let g=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var li="persona-artifact-custom-action-btn";function Fr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+li+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+li+(n?" persona-artifact-doc-icon-btn":"");o=b("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Qo({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-copy-btn":"")}):o=Wt({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Fs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Xu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Bn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Co(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...u?{presentation:u}:{}},B=Br(T,C,"card");Xo(v,B,C)}else s&&Hr(s),v.textContent=d;if(w.append(g,v),c.append(f,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let S of C)try{if(S.visible===void 0||S.visible(B)){let k=Fr(S);k.setAttribute("data-artifact-custom-action",S.id),k.className=`${k.className} persona-flex-shrink-0`,c.append(k)}}catch{}}let T=Qo({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),c.append(T)}return c}var ci=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Xu(e,t)});if(l)return l}return Xu(e,t)};var So=new WeakMap;function tc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=So.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function tf(e){return So.has(e)}function Oy(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Qu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Bn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Co(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ny(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Ju=180,_y=240,$y=.8,Uy=300,zy=500,jy="cubic-bezier(0.2, 0, 0, 1)",Zu=240,Vy=.35;function qy(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Ju,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let u=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!u||Math.abs(u-t)<1){l(),r();return}let d=Math.abs(t-u),c=Math.round(Math.min(zy,Math.max(Uy,_y+d*$y))),f=Math.round(c*Vy),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=w?w.animate([{opacity:0},{opacity:1}],{duration:Zu,delay:f,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${u}px`}],{duration:c,easing:jy});e.style.height=`${u}px`;let C=!1,T=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,g?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+Zu)+120)},Ju)}function Ky(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Os="--persona-artifact-inline-body-height";function Gy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",u=l==="clip"?!1:t?.followOutput!==!1,d,c,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:u,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:g}}function ef(e,t){let n=Oy(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Ky(o),u=o?.inlineActions??[],d=Gy(o),c=d.completeDisplay==="card",f=null,w=n,g=b("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let v=Z=>ci(Ny(Z),t),C=Z=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Os),g.replaceChildren(v(Z)),So.set(g,pe=>{g.replaceChildren(v(pe))})};if(c&&n.status==="complete")return C(n),g;let T=di(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),B=b("div","persona-artifact-inline-body");B.appendChild(T.el);let S=Z=>{let pe=Z.status!=="complete",ee=pe?d.streamingHeight:d.completeHeight,me=typeof ee=="number";me?g.style.setProperty(Os,`${ee}px`):g.style.removeProperty(Os);let we=!!T.el.querySelector(".persona-code-pre"),he=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",we),B.classList.toggle("persona-artifact-inline-body--sized",me&&he),B.classList.toggle("persona-artifact-inline-body--cap",!pe&&!he&&typeof d.completeHeight=="number")},k=n.status,P=(Z,pe)=>{k!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Os,`${d.completeHeight}px`):g.style.removeProperty(Os),of(B,pe?.suppressTransition?"none":d.transition,Z.id,()=>{T.update(Z),S(Z)})):T.update(Z),S(Z),k=Z.status};S(n);let H=d.overflow==="clip"&&a&&!!n.id;if(H&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Qu(n).title} in panel`)),!r)return g.appendChild(B),So.set(g,P),g;let F=b("div","persona-artifact-inline-chrome");F.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let N=b("div","persona-artifact-inline-chrome-lead"),z=b("span","persona-flex persona-items-center persona-flex-shrink-0"),j=ae("file-text",16,"currentColor",2);j&&z.appendChild(j);let te=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),A=b("span","persona-artifact-inline-type");N.append(z,te,A);let G=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),ie=()=>f??d.viewMode,Y=l?ii({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ie(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let pe=Z==="source"?"source":"rendered";pe!==ie()&&(f=pe,T.update(w),S(w))}}):null,ue=s?Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ue&&n.id&&ue.setAttribute("data-copy-artifact",n.id);let X=a?Wt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;X&&n.id&&X.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),Y&&G.appendChild(Y.element),ue&&G.appendChild(ue),X&&G.appendChild(X),F.append(N,G),g.append(F,B);let ge=Z=>{let{title:pe,typeLabel:ee}=Qu(Z);te.textContent=pe,te.title=pe,H&&B.setAttribute("aria-label",`Open ${pe} in panel`);let me=Z.status!=="complete";if(me){A.classList.contains("persona-artifact-inline-status")||(A.className="persona-artifact-inline-status",A.removeAttribute("data-preserve-animation"),A.replaceChildren());let we=Br(Z,o,"inline-chrome");Xo(A,we,o)}else Hr(Z.id),A.className="persona-artifact-inline-type",A.removeAttribute("data-preserve-animation"),A.replaceChildren(),A.textContent=ee;if(ue&&ue.classList.toggle("persona-hidden",me),Y){let we=Z.artifactType==="markdown"?Z.file:void 0,he=!1;if(!me&&we&&d.viewMode!=="source"){let ke=Yo(we);ke==="markdown"?he=!0:(ke==="html"||ke==="svg")&&(he=o?.filePreview?.enabled!==!1)}Y.element.classList.toggle("persona-hidden",!he),Y.setSelected(ie())}if(Q.replaceChildren(),!me&&u.length>0){let we=Fs(Z);if(we)for(let he of u)try{if(he.visible===void 0||he.visible(we)){let ke=Fr(he,{documentChrome:!0});ke.setAttribute("data-artifact-custom-action",he.id),ke.classList.add("persona-flex-shrink-0"),Q.appendChild(ke)}}catch{}}};return ge(n),So.set(g,(Z,pe)=>{if(c&&k!=="complete"&&Z.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;k="complete";let me=Z,we=!1,he=ke=>{me=ke,we=!0};So.set(g,he),qy(g,ee,{swap:()=>{C(me),we=!1,So.set(g,he)},onSettled:()=>{we?C(me):So.set(g,ke=>{g.replaceChildren(v(ke))})}});return}(Z.status!=="complete"||Z.id!==w.id)&&(f=null),w=Z,P(Z,pe),ge(Z)}),g}var nf=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>ef(e,t)});if(l)return l}return ef(e,t)};var nc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Zn=new nc;Zn.register("PersonaArtifactCard",ci,{bubbleChrome:!1});Zn.register("PersonaArtifactInline",nf,{bubbleChrome:!1});function Ns(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ri(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var oc=!1;function Yy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function of(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||oc||s){o();return}oc=!0;let a=Yy(n);e.style.setProperty("view-transition-name",a);let l=()=>{oc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Xy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Qy="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Jy(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Zy(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var eb=220;function tb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function nb(e){return`
|
|
30
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function ob(e,t,n){let o=b("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=b("div","persona-artifact-frame-loading-indicator");r.appendChild($u());let s=null;return n.label!==!1&&(s=b("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function rb(e,t,n,o,r,s){let a=null,l=0,u=!1,d=new Set,c=()=>{d.forEach(k=>clearTimeout(k)),d.clear()},f=(k,P)=>{let H=setTimeout(()=>{d.delete(H),k()},P);d.add(H)},w=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||u)return;let k=ob(r,s,o);a=k.el,e.appendChild(a),l=Date.now(),o.label!==!1&&f(k.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),f(w,eb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",S)},T=()=>{if(u||(u=!0,C(),c(),!a))return;let k=Math.max(0,o.minVisibleMs-(Date.now()-l));k>0?f(v,k):v()};function B(k){if(n===null)return;let P=k.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||k.source===t.contentWindow&&T()}function S(){let k=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};k(()=>k(()=>T()))}return f(g,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",S),()=>{u=!0,c(),C(),w()}}function di(e,t){let{config:n}=t,o=t.registry??Zn,r=t.bodyLayout,s=n.markdown?Ba(n.markdown):null,a=Da(n.sanitize),l=e,u=!1,d=X=>{let ge=Gn()!==null;s&&!ge&&!u&&(u=!0,Ha(()=>ue(l)));let Z=s?s(X):mo(X);return s&&ge&&a?a(Z):Z},c=b("div","persona-artifact-preview-body"),f=null,w=null,g=null,v=()=>{g&&(g(),g=null),f=null,w=null},C=null,T=null,B=null,S=!1,k=()=>{C=null,T=null,B=null,S=!1},P=null,H=null,F=()=>{P=null,H=null},N=40,z=0,j=X=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>X()):setTimeout(X,0),te=X=>X.scrollHeight-X.clientHeight-X.scrollTop<=N,A=X=>{if(!r)return;let ge=X.scrollHeight-X.clientHeight>1,Z=X.scrollHeight-X.clientHeight-X.scrollTop;X.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&X.scrollTop>1),X.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Z>1)},G=X=>{z||(z=j(()=>{z=0,X.scrollTop=X.scrollHeight,A(X)}))},Q=(X,ge,Z,pe)=>{let ee=!!r,me=Z.id+"|"+(ee?"w":"p");if(!C||B!==me||C.parentElement!==c){v(),F(),c.replaceChildren();let ke=b("pre",Xy+" persona-code-pre"),Ne=b("code","persona-code");if(ke.appendChild(Ne),ee){let Ue=b("div","persona-artifact-source-window");if(Ue.appendChild(ke),c.appendChild(Ue),!(r?.overflow==="clip")&&typeof Ue.addEventListener=="function"){let Oe=()=>Ue.scrollHeight-Ue.clientHeight>1;Ue.addEventListener("scroll",()=>{te(Ue)&&(S=!1),A(Ue)},{passive:!0}),Ue.addEventListener("wheel",_e=>{Oe()&&_e.deltaY<0&&(S=!0)},{passive:!0}),Ue.addEventListener("touchmove",()=>{Oe()&&(S=!0)},{passive:!0})}C=Ue}else c.appendChild(ke),C=ke;T=Ne,B=me}let we=ee?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",pe),we.classList.toggle("persona-artifact-source-window--clip",pe&&r?.overflow==="clip"));let he=we?te(we):!0;if(T.replaceChildren(Gu(X,ge?.language,ge?.path)),we){let ke=Z.status!=="complete";pe&&ke&&r?.followOutput&&!S&&he?G(we):ke||(S=!1),A(we)}},ie=X=>{v(),k(),F(),c.replaceChildren();let ge=b("div",Qy);ge.innerHTML=d(X),c.appendChild(ge)},Y=X=>{let ge=X.id,Z=n.features?.artifacts,pe=Br(X,Z,"status-body");if(P&&H===ge&&P.parentElement===c){let we=P.querySelector(".persona-artifact-status-view-text");we&&Xo(we,pe,Z);return}v(),k(),c.replaceChildren();let ee=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");Xo(me,pe,Z),ee.appendChild(me),c.appendChild(ee),P=ee,H=ge},ue=X=>{l=X;let ge=t.resolveViewMode?.(X)??r?.viewMode??"rendered",Z=X.artifactType==="markdown"?X.file:void 0,pe=X.status!=="complete";pe||Hr(X.id);let ee=pe?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&pe){Y(X);return}if(Z){let he=ri(X.markdown??""),ke=Yo(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!pe&&ge==="rendered"&&Ne&&(ke==="html"||ke==="svg")){let Qe=X.id+"\0"+he;if(f&&w===Qe&&f.parentElement===c)return;k(),F(),v(),c.replaceChildren();let Oe=n.features?.artifacts?.filePreview,_e=Oe?.iframeSandbox??"allow-scripts";!Oe?.dangerouslyAllowSameOrigin&&_e.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),_e=_e.split(/\s+/).filter(gt=>gt&>!=="allow-same-origin").join(" "));let Ae=Zy(Oe?.loading),Se=b("div","persona-artifact-frame"),ze=b("iframe","persona-artifact-iframe");ze.setAttribute("sandbox",_e),ze.setAttribute("data-artifact-id",X.id);let Gt=null;Ae.enabled&&Ae.injectReadySignal?(Gt=tb(),ze.srcdoc=he+nb(Gt)):ze.srcdoc=he,Se.appendChild(ze),c.appendChild(Se),Ae.enabled&&(g=rb(Se,ze,Gt,Ae,X.id,n)),f=Se,w=Qe;return}if(v(),!pe&&ke==="markdown"&&ge==="rendered"){ie(he);return}Q(he,{language:Z.language,path:Z.path},X,me);return}if(X.artifactType==="markdown"){if(ge==="source"){v(),Q(X.markdown??"",void 0,X,me);return}ie(X.markdown??"");return}v(),k(),F(),c.replaceChildren();let we=X.component?o.get(X.component):void 0;if(we){let ke={message:{id:X.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=we(X.props??{},ke);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Jy(X))};return ue(e),{el:c,update(X){ue(X)}}}import{Idiomorph as sb}from"idiomorph";var pi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;sb.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var rf=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var rc={index:-1,draft:""};function sf(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function af(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function lf(){return new Map}function cf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function df(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function uf(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function ui(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Dn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function eo(e,t){return Dn(e)-e.scrollTop<=t}function fi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&u&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function gi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function ff(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sc(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function gf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var _s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ab=["pre","code","a","script","style"],mi=e=>({type:e?.type??_s.type,placeholder:e?.placeholder??_s.placeholder,speed:e?.speed??_s.speed,duration:e?.duration??_s.duration,buffer:e?.buffer??_s.buffer}),ib=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],hf=new Map;for(let e of ib)hf.set(e.name,e);var Or=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:hf.get(e)??null,hi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
+
`);return s<0?"":e.slice(0,s)}return e},lb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},cb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},ac=/\s/,db=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(ac.test(s[l])){let u=l;for(;u<s.length&&ac.test(s[u]);)u+=1;a.appendChild(o.createTextNode(s.slice(l,u))),l=u}else{let u=o.createElement("span");u.className="persona-stream-word-group";let d=l;for(;d<s.length&&!ac.test(s[d]);)u.appendChild(lb(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(u),l=d}r.replaceChild(a,e)},ub=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let u of l)u&&(/^\s+$/.test(u)?a.appendChild(o.createTextNode(u)):(a.appendChild(cb(o,u,t,n.value)),n.value+=1));r.replaceChild(a,e)},$s=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ab).map(f=>f.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],u=a.nextNode();for(;u;)db(u,s)||l.push(u),u=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?pb:ub;for(let f of l)c(f,n,d);return r.innerHTML},yi=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Us=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},mf=new WeakMap,fb=(e,t)=>{if(!e.styles)return;let n=mf.get(t);if(n||(n=new Set,mf.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},ic=new WeakMap,gb=(e,t)=>{if(!e.onAttach)return;let n=ic.get(t);if(n||(n=new Map,ic.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},yf=e=>{let t=ic.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},bi=(e,t)=>{fb(e,t),gb(e,t)};function lc(e,t=Nt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var zs=0,To=null;function cc(e=document){if(zs++,zs===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;To={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,zs=Math.max(0,zs-1),zs===0&&To)){let n=e.body,o=e.defaultView??window;n.style.overflow=To.originalOverflow,n.style.position=To.originalPosition,n.style.top=To.originalTop,n.style.width=To.originalWidth,o.scrollTo(0,To.scrollY),To=null}}}var js={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=e=>(e?.launcher?.mountMode??"floating")==="docked",Vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",vn=e=>{let t=e?.launcher?.dock;return{side:t?.side??js.side,width:t?.width??js.width,animate:t?.animate??js.animate,reveal:t?.reveal??js.reveal,maxHeight:t?.maxHeight??js.maxHeight}};var dc=e=>e==="followUp"?"follow-up":e,pc=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},mb=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},bf=new WeakSet,hb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yb=e=>{hb()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},uc=e=>{var S,k,P;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:u,chipsConfig:d,session:c,getTextarea:f,eventTarget:w}=e,g=o==="followUp",v=t.behavior,C=()=>{if(c.isStreaming())return;let H={suggestion:{...t},surface:o,source:r,behavior:v},F=w.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:H,bubbles:!0,composed:!0,cancelable:!0}));if(g&&w.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!F)return;for(let z of u)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let N=f();if(v==="fill"){N.value=t.prompt,N.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),N.focus();return}N.value="",c.sendMessage(t.prompt)},T=()=>{let H=b("button",`persona-suggestion persona-suggestion--${s}`);if(H.type="button",H.disabled=a,H.dataset.suggestionId=t.id,H.dataset.emphasis=t.emphasis,H.dataset.behavior=v,s==="chip"&&(d?.fontFamily&&(H.style.fontFamily=mb(d.fontFamily)),d?.fontWeight&&(H.style.fontWeight=d.fontWeight),d?.paddingX&&(H.style.paddingLeft=d.paddingX,H.style.paddingRight=d.paddingX),d?.paddingY&&(H.style.paddingTop=d.paddingY,H.style.paddingBottom=d.paddingY)),t.icon){let N=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);N&&(N.classList.add("persona-suggestion__icon"),t.iconColor&&(N.style.color=t.iconColor),H.appendChild(N))}let F=b("span","persona-suggestion__copy");if(F.appendChild(Ee("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&F.appendChild(Ee("span",{className:"persona-suggestion__description",text:t.description})),H.appendChild(F),s!=="chip"){let N=ae("arrow-right",16,"currentColor",1.8);N&&(N.classList.add("persona-suggestion__arrow"),H.appendChild(N))}return H.addEventListener("click",C),H},B=null;for(let H of u)if(H.renderSuggestion&&(B=H.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:T,select:C}),B))break;return B??(B=T()),(S=B.dataset).suggestionId||(S.suggestionId=t.id),(k=B.dataset).behavior||(k.behavior=v),(P=B.dataset).emphasis||(P.emphasis=t.emphasis),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",a?"true":"false"),B},qs=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let f=getComputedStyle(e).direction==="rtl",w=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),g=4,v=w<=g,C=w>=c-g,T=f?!C:!v,B=f?!v:!C;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",B)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return u?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),u?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,w,g,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let T=C?.source??"config",B=C?.surface??(T==="config"?"starter":"followUp"),S=B==="followUp",k=C?.variant??"chip",P=C?.behavior??"send",H=C?.overflow??"wrap",F=C?.config??{},N=C?.plugins??[],z=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,j=S?"followUps":"starters";!bf.has(F)&&F.debug===!0&&k!=="chip"&&F.suggestions?.[j]?.overflow!==void 0&&(bf.add(F),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${k}" variant manages its own stacking.`));let te=ue=>ue.map(pc).filter(X=>X!==null).map(X=>({...X,behavior:X.behavior??P})),A=te(c??[]);N.forEach(ue=>{ue.transformSuggestions&&(A=te(ue.transformSuggestions({suggestions:A.map(X=>({...X})),surface:B,source:T,config:F})))});let G=z===void 0?A:A.slice(0,z);if(!G.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(X=>X.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=dc(B),e.dataset.variant=k,e.dataset.overflow=H;let Q=document.createDocumentFragment(),ie=f.isStreaming();G.forEach((ue,X)=>{let ge=uc({item:ue,index:X,surface:B,source:T,variant:k,streaming:ie,config:F,plugins:N,chipsConfig:v,session:f,getTextarea:()=>w,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(pe=>{t.includes(pe)||(pe.disabled=ie,t.push(pe))})}),e.appendChild(Q),a(),l();let Y=JSON.stringify({normalized:G,surface:B,variant:k,source:T});Y!==o&&(o=Y,yb(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(ue=>({...ue})),surface:B,source:T,variant:k},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(ue=>ue.prompt)},bubbles:!0,composed:!0})))}}};var ln={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var bb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",vi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=bb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",u=b("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,f=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ae(f,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,u.appendChild(v),_t({anchor:v,trigger:u,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:u}},vb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wi=(e,t={})=>{let{wrapperClassName:n=vb,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",u=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",f=a.borderWidth??"",w=a.borderColor??"",g=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",T=a.tooltipText??"Clear chat",B=a.showTooltip??!0,S=b("div",n),k=!!(f||w),P=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:k?`${f||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),H=ae(u,r,"currentColor",1);return H&&(H.style.display="block",P.appendChild(H)),S.appendChild(P),_t({anchor:P,trigger:S,text:()=>P.getAttribute("aria-label")??T,enabled:B}),{button:P,wrapper:S}};var Kt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},fc={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},wb={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},Jo=e=>{let{config:t,showClose:n=!0}=e,o=Ee("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,u=r.headerIconName,d=Ee("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(u){let H=parseFloat(s)||24,F=ae(u,H*.6,"currentColor",1);F?d.replaceChildren(F):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let H=b("img");H.src=t.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=s,H.style.width=s,d.replaceChildren(H)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Ee("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor,...fc}}),w=Ee("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor,...wb}});c.append(f,w),l?o.append(c):o.append(d,c);let g=r.clearChat??{},v=g.enabled??!0,C=g.placement??"inline",T=null,B=null;if(v){let F=wi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=F.button,B=F.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:P}=vi(t,{showClose:n,wrapperClassName:S});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:w,closeButton:k,closeButtonWrapper:P,clearChatButton:T,clearChatButtonWrapper:B}},Ks=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var xb=e=>{let t=Jo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Cb(e,t,n){if(t?.length)for(let o of t){let r=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Kt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=b("div","persona-relative");s.appendChild(r);let a=Dr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Ab=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=r?.titleMenu,d,c;if(u)d=Yu({label:a.title??"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=b("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,Object.assign(c.style,fc),c.textContent=a.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let P=r.onTitleClick;d.addEventListener("click",H=>{H.target.closest("button")||P()}),d.addEventListener("keydown",H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),P())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=a.closeButtonSize??"32px",w=b("div",""),g=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=f,g.style.width=f,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Kt.actionIconColor;let v=a.closeButtonIconName??"x",C=ae(v,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),w.appendChild(g);let T=b("div","persona-flex persona-items-center persona-gap-1");u||Cb(T,r?.trailingActions,r?.onAction??s),T.appendChild(w),l.appendChild(T);let B=b("div");B.style.display="none";let S=b("span");return S.style.display="none",{header:l,iconHolder:B,headerTitle:c,headerSubtitle:S,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},vf={default:xb,minimal:Ab},Sb=e=>vf[e]??vf.default,xi=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=b("div");l.style.display="none";let u=b("span"),d=b("span"),c=b("button");c.style.display="none";let f=b("div");return f.style.display="none",{header:a,iconHolder:l,headerTitle:u,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Sb(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ci=e=>{let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let u=t.ownerDocument?.defaultView;if(!u?.getComputedStyle)return o;let d=u.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let u=t.style.maxHeight;if(u!==s){let c=parseFloat(u);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let u=Math.min(t.scrollHeight,a());t.style.height=`${u}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},Ai=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",u=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,f=t.size??"40px",w=t.backgroundColor,g=t.textColor,v=b("div","persona-send-button-wrapper"),C=Ee("button",{className:Pn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&w||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,B=null;if(n){let P=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),H=t.iconStrokeWidth??2,F=g?.trim()||"currentColor";r?(T=ae(r,P,F,H),T?C.appendChild(T):C.textContent=o):C.textContent=o,B=ae(s,P,F,H)}else C.textContent=u;C.setAttribute("aria-label",a),v.appendChild(C),_t({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let S="send";return{button:C,wrapper:v,setMode:P=>{if(P===S)return;S=P;let H=P==="stop"?l:a;if(C.setAttribute("aria-label",H),n){if(T&&B){let F=P==="stop"?B:T;C.replaceChildren(F)}}else C.textContent=P==="stop"?d:u}}},Si=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",u=t.iconSize??a,d=parseFloat(u)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,w=b("div","persona-send-button-wrapper"),g=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:u,height:u,minWidth:u,minHeight:u,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ae(l,d,f||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",w.appendChild(g);let T=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return _t({anchor:g,trigger:w,text:()=>g.getAttribute("aria-label")??T,enabled:B}),{button:g,wrapper:w}},Ti=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Qn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,u=Math.round(l*.6),d=b("div","persona-send-button-wrapper"),c=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),f=ae(s,u,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return _t({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},Mi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=b("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Ei=()=>Ee("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Gs=e=>{let{config:t}=e,n=Ee("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Ei(),r=Ee("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ci(t);a();let l=Ai(t),u=Si(t),d=Ti(t),c=Mi(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let f=Ee("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),u&&g.append(u.wrapper),g.append(l.wrapper),f.append(w,g),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:w,rightActions:g,setSendButtonMode:l.setMode}};var wf=()=>{let e=Ee("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ki=e=>{let{config:t}=e,n=Ee("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ei(),r=Mi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ci(t);s.style.maxHeight="100px",a();let l=Ai(t),u=Si(t),d=Ti(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ee("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let w=b("div","persona-widget-composer__right-actions persona-pill-composer__right");u&&w.append(u.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(f,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:f,rightActions:w,setSendButtonMode:l.setMode}};var Tb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Mb=(e,t)=>{if(!e)return null;let n=Tb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Eb=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},kb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},gc=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},mc=320,Sf=320,Lb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Pb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Rb=e=>{if(!e||e.length===0)return null;let t=Ee("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ee("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=b("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ee("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Hb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Hs(o.ref,{readonly:!0,render:t}))}return n},xf="\uE000",Cf="\uE001",Bb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${xf}${r}:${w}${Cf}`,a=t.map((w,g)=>w.kind==="text"?w.text:s(g)).join(""),l=n(a);if(!t.every((w,g)=>w.kind==="text"||l.includes(s(g)))){e.replaceChildren(Hb(t,o));return}e.innerHTML=l;let d=new RegExp(`${xf}${r}:(\\d+)${Cf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let w=c.nextNode();w;w=c.nextNode())f.push(w);for(let w of f){let g=w;for(let v=d.exec(g.data);v;v=d.exec(g.data)){let C=t[Number(v[1])],T=g.splitText(v.index);T.data=T.data.slice(v[0].length),C?.kind==="mention"&&T.parentNode?.insertBefore(Hs(C.ref,{readonly:!0,render:o}),T),g=T}}},Db=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,u)=>{let d=b("img");d.alt=l.alt?.trim()||`Attached image ${u+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${mc}px`,d.style.maxHeight=`${Sf}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),kb(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Fb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!gc(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ob=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!gc(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,r.style.maxHeight=`${Sf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!gc(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ys=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},_b=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},$b=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Af=(e,t,n="div")=>{let o=b(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Xs=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Ub=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=b("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",u=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[u],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let g=(v,C,T)=>{let B=Wt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",T),B};return o&&w.appendChild(g("copy","Copy message","copy")),a&&w.appendChild(g("volume-2","Read aloud","read-aloud")),r&&w.appendChild(g("thumbs-up","Upvote","upvote")),s&&w.appendChild(g("thumbs-down","Downvote","downvote")),w},hc=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",u=a.avatar,d=a.timestamp,c=u?.show??!1,f=d?.show??!1,w=u?.position??"left",g=d?.position??"below",v=Xs(e.role,l),C=b("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Lb(e),B=e.content?.trim()??"",k=T.length>0&&B===Ga,P=mi(s?.widgetConfig?.features?.streamAnimation),H=s?.widgetConfig?.features?.streamAnimation?.plugins,F=e.role==="assistant"&&P.type!=="none"?Or(P.type,H):null,N=e.role==="assistant"&&F?.isAnimating?.(e)===!0,z=e.role==="assistant"&&F!==null&&(!!e.streaming||N);z&&F?.bubbleClass&&C.classList.add(F.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),z&&F&&(F.containerClass&&j.classList.add(F.containerClass),j.style.setProperty("--persona-stream-step",`${P.speed}ms`),j.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let te=z?hi(e.content??"",P.buffer,F,e,!!e.streaming):e.content??"",A=()=>{let ee=t({text:te,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&F?.wrap==="char"?$s(ee,"char",e.id,{skipTags:F.skipTags}):z&&F?.wrap==="word"?$s(ee,"word",e.id,{skipTags:F.skipTags}):ee},G=null;if(k?(G=document.createElement("div"),G.innerHTML=A(),G.style.display="none",j.appendChild(G)):e.contentSegments?.length?Bb(j,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):j.innerHTML=A(),z&&F?.useCaret&&!k&&B){let ee=yi(),me=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=me[me.length-1];if(we?.parentNode)we.parentNode.insertBefore(ee,we.nextSibling);else{let he=j.lastElementChild;he?he.appendChild(ee):j.appendChild(ee)}}if(f&&g==="inline"&&e.createdAt){let ee=Af(e,d,"span");ee.classList.add("persona-timestamp-inline");let me=j.lastElementChild;me?me.appendChild(ee):j.appendChild(ee)}if(T.length>0){let ee=Db(T,!k&&!!B,()=>{k&&G&&(G.style.display="")});ee?C.appendChild(ee):k&&G&&(G.style.display="")}let Q=Pb(e);if(Q.length>0){let ee=Fb(Q);ee&&C.appendChild(ee)}let ie=Ib(e);if(ie.length>0){let ee=Ob(ie);ee&&C.appendChild(ee)}let Y=Wb(e);if(Y.length>0){let ee=Nb(Y);ee&&C.appendChild(ee)}let ue=e.contentSegments?.length?null:Rb(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(j),f&&g==="below"&&e.createdAt){let ee=Af(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let X=e.role==="assistant"?Mb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(te&&te.trim()),me=P.placeholder==="skeleton",we=me&&P.buffer==="line"&ⅇif(ee)we&&C.appendChild(Us());else if(me)C.appendChild(Us());else{let he=_b("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(X&&e.stopReason&&!e.streaming&&(B||(j.style.display="none"),C.appendChild(Eb(e.stopReason,X))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Ub(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),pe=$b(u,e.role);return w==="right"||w==="left"&&e.role==="user"?Z.append(C,pe):Z.append(pe,C),Z};var zb=40,jb=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ae(t.name,zb);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Ee("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Ee("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Tf=(e,t,n={})=>{let o=Ee("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=b("h2","persona-welcome-title"),s=b("p","persona-welcome-subtitle");return{host:Ee("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},Nr=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},Pi=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",jb(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Vb="data-persona-welcome-plugin",Mf="data-persona-welcome-overlay",Li="persona-welcome-overlay-active",yc=new WeakMap,Ef=(e,t,n)=>{n.setAttribute(Vb,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Mf,""),e.classList.contains(Li)||(yc.set(e,e.scrollTop),e.classList.add(Li),e.scrollTop=0)},kf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Mf),e.classList.contains(Li)&&(e.classList.remove(Li),e.scrollTop=yc.get(e)??e.scrollTop,yc.delete(e))},Lf=()=>{let e=Ee("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Ii=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Ee("div",{className:Xs("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Ee("div",{className:"persona-flex"},r)),e.hidden=!1},qb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Pf=(e,t)=>{if(qb()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Kb="Hello \u{1F44B}",Gb="I can answer questions and help you get things done here.",If=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,Yb=(e,t)=>{!e||e.debug!==!0||!t.length||If.has(e)||(If.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Zo=e=>{let t=e?.welcome,n=e?.copy,o=wn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":wn(t,"dismiss")?t.dismiss:"never",s=[];return wn(t,"title")&&wn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(t,"subtitle")&&wn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(t,"variant")&&wn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&wn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&wn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),Yb(e,s),{title:wn(t,"title")?t.title:n?.welcomeTitle??Kb,subtitle:wn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??Gb,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},_r=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Wf=e=>{let t=e?.launcher?.enabled??!0,n=Rt(e);if(Vs(e)){let c=e?.launcher?.composerBar??{},f=b("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Nt);let w=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",f.appendChild(w);let g=b("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Nt),{wrapper:f,panel:w,pillRoot:g}}if(n){let c=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},s=r.position&&ln[r.position]?ln[r.position]:ln["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Nt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??Jn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},bc=e=>{let t=Ee("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":dc(e)}});return t.hidden=!0,t},Rf=(e,t)=>{let n=bc("starter"),o=Tf(e,n,{flatShadow:Rt(e)}),r=Zo(e);Pi(o,r),Nr(t,o.host,_r(r,e?.initialMessages));let s=Lf();return Ii(s,r.message,e),{welcome:o,greetingHost:s}},Xb=(e,t)=>{let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=vi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let N=wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=N.button,l=N.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let u=Ee("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ee("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:f}=Rf(e,d),{host:w,title:g,subtitle:v}=c,C=c.starterSuggestions,T=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),B=bc("followUp"),S=xo(e,!0);S&&(T.style.maxWidth=S,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(w,f,T,B);let k=Ee("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),P=ki({config:e}),{root:H,textNode:F}=wf();return n.append(u,r,d,k),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:C,transcriptSuggestions:B,composerOverlay:k,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,welcomeHost:w,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:g,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:u,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:H,peekTextNode:F}},Hf=(e,t=!0)=>{if(Vs(e))return Xb(e,t);let n=Ee("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?xi(e,o,{showClose:t}):Jo({config:e,showClose:t}),a=Ee("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:u}=Rf(e,a),{host:d,title:c,subtitle:f}=l,w=l.starterSuggestions,g=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),v=bc("followUp"),C=xo(e,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(d,u,g,v);let T=Gs({config:e}),B=e?.layout?.showFooter!==!1;r?Ks(n,s,e):(s.header.style.display="none",Ks(n,s,e)),n.append(a);let S=Ee("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return B||(T.footer.style.display="none"),n.append(T.footer),n.append(S),{container:n,body:a,messagesWrapper:g,starterSuggestions:w,transcriptSuggestions:v,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:u,introTitle:c,introSubtitle:f,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var vc=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
32
32
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
33
33
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
34
34
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -36,14 +36,14 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
36
36
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
37
37
|
</span>
|
|
38
38
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
39
|
-
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Dt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let T=a.title??"Chat Assistant";p.textContent=T,p.setAttribute("title",T)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let T=a.subtitle??"Here to help you get answers fast";d.textContent=T,d.setAttribute("title",T)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let T=a.agentIconSize??"40px";if(u.style.height=T,u.style.width=T,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let M=parseFloat(T)||24,U=ae(a.agentIconName,M*.6,"var(--persona-text-inverse, #ffffff)",2);U?(u.appendChild(U),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let T=a.agentIconSize??"40px";w.style.height=T,w.style.width=T,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let T=a.callToActionIconSize??"32px";g.style.height=T,g.style.width=T,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let M=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,M=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let U=parseFloat(T)||24,j=Math.max(U-M,8),A=ae(a.callToActionIconName,j,"currentColor",2);A?g.appendChild(A):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&Sn[a.position]?Sn[a.position]:Sn["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",P="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?P:`${x} ${v}`,l||(n.style.zIndex=String(a.zIndex??Vt));let F="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??F,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:k,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Tu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Au(e),s=Su(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},kl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>El(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=El(e,n);return{instance:r,element:r.element}};var cy=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},dy=(e,t)=>{if(!e)return null;let n=cy(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},py=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},uy=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Ll=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Pl=320,Lu=320,fy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),my=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),hy=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),yy=e=>{if(!e||e.length===0)return null;let t=Ie("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ie("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ie("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},by=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:t}))}return n},Mu="\uE000",Eu="\uE001",vy=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${Mu}${r}:${w}${Eu}`,a=t.map((w,g)=>w.kind==="text"?w.text:s(g)).join(""),l=n(a);if(!t.every((w,g)=>w.kind==="text"||l.includes(s(g)))){e.replaceChildren(by(t,o));return}e.innerHTML=l;let d=new RegExp(`${Mu}${r}:(\\d+)${Eu}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let w=c.nextNode();w;w=c.nextNode())u.push(w);for(let w of u){let g=w;for(let v=d.exec(g.data);v;v=d.exec(g.data)){let x=t[Number(v[1])],P=g.splitText(v.index);P.data=P.data.slice(v[0].length),x?.kind==="mention"&&P.parentNode?.insertBefore(ms(x.ref,{readonly:!0,render:o}),P),g=P}}},wy=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=y("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Pl}px`,d.style.maxHeight=`${Lu}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),uy(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},xy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Ll(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cy=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Ll(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pl}px`,r.style.maxHeight=`${Lu}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ay=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Ll(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ls=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Sy=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ls};if(t){let r=t(o);if(r!==null)return r}return Ls()},Ty=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},ku=(e,t,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Il=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},My=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=y("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let g=(v,x,P)=>{let F=Pt({icon:v,label:x,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",P),F};return o&&w.appendChild(g("copy","Copy message","copy")),a&&w.appendChild(g("volume-2","Read aloud","read-aloud")),r&&w.appendChild(g("thumbs-up","Upvote","upvote")),s&&w.appendChild(g("thumbs-down","Downvote","downvote")),w},Rl=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",g=d?.position??"below",v=Il(e.role,l),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let P=fy(e),F=e.content?.trim()??"",T=P.length>0&&F===ka,M=Qa(s?.widgetConfig?.features?.streamAnimation),U=s?.widgetConfig?.features?.streamAnimation?.plugins,j=e.role==="assistant"&&M.type!=="none"?vr(M.type,U):null,A=e.role==="assistant"&&j?.isAnimating?.(e)===!0,V=e.role==="assistant"&&j!==null&&(!!e.streaming||A);V&&j?.bubbleClass&&x.classList.add(j.bubbleClass);let K=document.createElement("div");K.classList.add("persona-message-content"),e.streaming&&K.classList.add("persona-content-streaming"),V&&j&&(j.containerClass&&K.classList.add(j.containerClass),K.style.setProperty("--persona-stream-step",`${M.speed}ms`),K.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let ne=V?Xa(e.content??"",M.buffer,j,e,!!e.streaming):e.content??"",D=()=>{let J=t({text:ne,message:e,streaming:!!e.streaming,raw:e.rawContent});return V&&j?.wrap==="char"?As(J,"char",e.id,{skipTags:j.skipTags}):V&&j?.wrap==="word"?As(J,"word",e.id,{skipTags:j.skipTags}):J},_=null;if(T?(_=document.createElement("div"),_.innerHTML=D(),_.style.display="none",K.appendChild(_)):e.contentSegments?.length?vy(K,e.contentSegments,J=>t({text:J,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):K.innerHTML=D(),V&&j?.useCaret&&!T&&F){let J=Ja(),fe=K.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=fe[fe.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(J,Ce.nextSibling);else{let ye=K.lastElementChild;ye?ye.appendChild(J):K.appendChild(J)}}if(u&&g==="inline"&&e.createdAt){let J=ku(e,d,"span");J.classList.add("persona-timestamp-inline");let fe=K.lastElementChild;fe?fe.appendChild(J):K.appendChild(J)}if(P.length>0){let J=wy(P,!T&&!!F,()=>{T&&_&&(_.style.display="")});J?x.appendChild(J):T&&_&&(_.style.display="")}let Y=gy(e);if(Y.length>0){let J=xy(Y);J&&x.appendChild(J)}let ge=my(e);if(ge.length>0){let J=Cy(ge);J&&x.appendChild(J)}let he=hy(e);if(he.length>0){let J=Ay(he);J&&x.appendChild(J)}let ce=e.contentSegments?.length?null:yy(e.contextMentions);if(ce&&x.appendChild(ce),x.appendChild(K),u&&g==="below"&&e.createdAt){let J=ku(e,d);J.classList.add("persona-mt-1"),x.appendChild(J)}let Z=e.role==="assistant"?dy(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(ne&&ne.trim()),fe=M.placeholder==="skeleton",Ce=fe&&M.buffer==="line"&&J;if(J)Ce&&x.appendChild(Ss());else if(fe)x.appendChild(Ss());else{let ye=Sy("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&x.appendChild(ye)}}if(Z&&e.stopReason&&!e.streaming&&(F||(K.style.display="none"),x.appendChild(py(e.stopReason,Z))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let J=My(e,o,r);x.appendChild(J)}if(!c||e.role==="system")return x;let te=y("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ie=Ty(p,e.role);return w==="right"||w==="left"&&e.role==="user"?te.append(x,ie):te.append(ie,x),te};var wr=new Set,Ey=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ky=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
-
`):""},
|
|
41
|
-
`);let r=
|
|
42
|
-
`):""},Hl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Iy=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Py(e,o?.previewMaxLines??3),a=n?dp(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=rl(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=rl(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},Iu=(e,t,n)=>{let o=xr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ae(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Bl=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&xr.has(e.id),{summary:p,previewText:d,isActive:c}=Iy(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),x=()=>{let D=y("span","");return D.setAttribute("data-tool-elapsed",v),D.textContent=is(n),D},P=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:is(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(g.textContent=P,w.appendChild(g)):P instanceof HTMLElement?w.appendChild(P):(g.textContent=p,w.appendChild(g));let F=s.loadingAnimation??"none",k=o.activeTextTemplate,T=o.completeTextTemplate,M=c?k:T,U=P instanceof HTMLElement,j=(D,_)=>{g.textContent="";let Y=n.name?.trim()||"tool",ge=Ta(D,Y),he=0;for(let ce of ge){let Z=ce.styles.length>0?(()=>{let de=y("span",ce.styles.map(te=>`persona-tool-text-${te}`).join(" "));return g.appendChild(de),de})():g;if(ce.isDuration&&c)Z.appendChild(x());else{let de=ce.isDuration?is(n):ce.text;_?he=go(Z,de,he):Z.appendChild(document.createTextNode(de))}}};if(!U)if(c&&F!=="none"){let D=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),F==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),M&&j(M,!1);else if(g.classList.add(`persona-tool-loading-${F}`),g.style.setProperty("--persona-tool-anim-duration",`${D}ms`),F==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),M)j(M,!0);else{let _=g.textContent||p;g.textContent="",go(g,_,0)}}else M&&j(M,!1);let A=null;if(a){A=y("div","persona-flex persona-items-center");let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",_=ae(l?"chevron-up":"chevron-down",16,D,2);_?A.appendChild(_):A.textContent=l?"Hide":"Show";let Y=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(A),u.append(w,Y)}else u.append(w);let V=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","tool"),V.style.display="none",V.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let D=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Ly(V,D)||(V.textContent=d),V.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,V),r;let K=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(K.style.display=l?"":"none",o.contentBackgroundColor&&(K.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(K.style.color=o.contentTextColor),o.contentPaddingX&&(K.style.paddingLeft=o.contentPaddingX,K.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(K.style.paddingTop=o.contentPaddingY,K.style.paddingBottom=o.contentPaddingY),n.name){let D=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?D.style.color=o.contentTextColor:o.headerTextColor&&(D.style.color=o.headerTextColor),D.textContent=n.name,K.appendChild(D)}if(n.args!==void 0){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Arguments";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=uo(n.args),D.append(_,Y),K.appendChild(D)}if(n.chunks&&n.chunks.length){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Activity";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=n.chunks.join(""),D.append(_,Y),K.appendChild(D)}if(n.status==="complete"&&n.result!==void 0){let D=y("div","persona-space-y-1"),_=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(_.style.color=o.labelTextColor),_.textContent="Result";let Y=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",Hl(Y,o),Y.textContent=uo(n.result),D.append(_,Y),K.appendChild(D)}if(n.status==="complete"&&typeof n.duration=="number"){let D=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(D.style.color=o.contentTextColor),D.textContent=`Duration: ${n.duration}ms`,K.appendChild(D)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),A){A.innerHTML="";let D=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",_=ae(l?"chevron-up":"chevron-down",16,D,2);_?A.appendChild(_):A.textContent=l?"Hide":"Show"}K.style.display=l?"":"none",V.style.display=l?"none":V.textContent||V.childNodes.length?"":"none"})(),r.append(u,V,K),r};var Oo=new Map,pi=e=>{let n=(e.startsWith($n)?e.slice($n.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Ru=e=>e?.approval!==!1?e?.approval:void 0,Wu=(e,t)=>{let n=Ru(t)?.detailsDisplay??"collapsed";return Oo.get(e)??n==="expanded"},Hu=(e,t,n)=>{let o=Ru(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Bu=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Wu(e,n);Hu(o,s,n),r.style.display=s?"":"none"};var ui=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=y("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ae(p,20,d,2);c&&l.appendChild(c);let u=y("div","persona-flex-1 persona-min-w-0"),w=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",w.appendChild(g),!r){let A=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");A.setAttribute("data-approval-status",n.status),n.status==="approved"?(A.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",A.style.color="var(--persona-palette-colors-success-700, #15803d)",A.textContent="Approved"):n.status==="denied"?(A.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",A.style.color="var(--persona-palette-colors-error-700, #b91c1c)",A.textContent="Denied"):n.status==="timeout"&&(A.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",A.style.color="var(--persona-palette-colors-warning-700, #b45309)",A.textContent="Timeout"),w.appendChild(A)}u.appendChild(w);let x=n.toolType==="webmcp"||n.toolName.startsWith($n)?ts(n.toolName):void 0,P=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),F=!n.toolName,k=P||(F?n.description:`The assistant wants to use \u201C${x??pi(n.toolName)}\u201D.`),T=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=k,u.appendChild(T),n.reason){let A=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");A.setAttribute("data-approval-reason","true"),o?.reasonColor?A.style.color=o.reasonColor:o?.descriptionColor&&(A.style.color=o.descriptionColor);let V=y("span","persona-font-medium");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,A.appendChild(V),A.appendChild(document.createTextNode(n.reason)),u.appendChild(A)}let M=o?.detailsDisplay??"collapsed",U=!!n.description&&!F,j=U||!!n.parameters;if(M!=="hidden"&&j){let A=Wu(e.id,t),V=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");V.type="button",V.setAttribute("data-expand-header","true"),V.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(V.style.color=o.descriptionColor);let K=y("span");K.setAttribute("data-approval-details-label","true");let ne=y("span","persona-inline-flex persona-items-center");ne.setAttribute("data-approval-details-chevron","true"),V.append(K,ne),Hu(V,A,t),u.appendChild(V);let D=y("div");if(D.setAttribute("data-approval-details","true"),D.style.display=A?"":"none",U){let _=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(_.style.color=o.descriptionColor),_.textContent=n.description,D.appendChild(_)}if(n.parameters){let _=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(_.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(_.style.color=o.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=uo(n.parameters),D.appendChild(_)}u.appendChild(D)}if(r){let A=y("div","persona-flex persona-gap-2 persona-mt-2");A.setAttribute("data-approval-buttons","true");let V=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");V.type="button",V.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",V.style.color=o?.approveButtonTextColor??"#ffffff",V.setAttribute("data-approval-action","approve");let K=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);K&&(K.style.marginRight="4px",V.appendChild(K));let ne=document.createTextNode(o?.approveLabel??"Approve");V.appendChild(ne);let D=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.denyButtonColor??"transparent",D.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",D.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,D.setAttribute("data-approval-action","deny");let _=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);_&&(_.style.marginRight="4px",D.appendChild(_));let Y=document.createTextNode(o?.denyLabel??"Deny");D.appendChild(Y),A.append(V,D),u.appendChild(A)}return a.append(l,u),s.appendChild(a),s};var Ry=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Du=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},_o=(e,t)=>{Du(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Wy=e=>e?.approval!==!1?e?.approval:void 0,Hy=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Oo.get(e)??n==="expanded"},Dl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},By=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith($n)?ts(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??pi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Dy=e=>{let t=y("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=e.toolName?pi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Fy=(e,t,n,o,r,s,a)=>{let l=y("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&Hy(t.id,o),g=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",w?"true":"false"),x.setAttribute("aria-label",w?v:g)):x.setAttribute("data-static","true");let P=y("span","persona-approval-logo"),F=ae("shield-check",16,"currentColor",2);F&&P.appendChild(F),x.appendChild(P);let k=By(n,o);if(u){let V=y("span","persona-approval-toggle");V.setAttribute("aria-hidden","true");let K=ae("chevron-down",14,"currentColor",2);K&&V.appendChild(K),k.append(" "),k.appendChild(V)}x.appendChild(k),l.appendChild(x);let T=y("div","persona-approval-body");if(u){let V=y("div","persona-approval-details");if(V.setAttribute("data-role","params"),V.hidden=!w,d){let K=y("p","persona-approval-desc");o?.descriptionColor&&(K.style.color=o.descriptionColor),K.textContent=n.description,V.appendChild(K)}if(c){let K=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(K.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(K.style.color=o.parameterTextColor),K.textContent=uo(n.parameters),V.appendChild(K)}T.appendChild(V)}if(n.reason){let V=y("p","persona-approval-reason");o?.reasonColor?V.style.color=o.reasonColor:o?.descriptionColor&&(V.style.color=o.descriptionColor);let K=y("span","persona-approval-reason-label");K.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,V.append(K,document.createTextNode(n.reason)),T.appendChild(V)}let M=y("div","persona-approval-actions"),U=null,j=V=>{o?.approveButtonColor&&(V.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(V.style.color=o.approveButtonTextColor)},A=y("button","persona-approval-deny");if(A.type="button",A.setAttribute("data-action","deny"),o?.denyButtonColor&&(A.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(A.style.color=o.denyButtonTextColor),A.append(o?.denyLabel??"Deny"),a){let V=y("div","persona-approval-split"),K=y("button","persona-approval-primary");K.type="button",K.setAttribute("data-action","always"),j(K),K.append(o?.approveLabel??"Always allow",Dl("\u23CE"));let ne=y("button","persona-approval-caret");ne.type="button",ne.setAttribute("data-action","toggle-menu"),ne.setAttribute("aria-label","More options"),j(ne);let D=ae("chevron-down",15,"currentColor",2);D&&ne.appendChild(D),V.append(K,ne),M.append(V,A),A.append(Dl("Esc"));let _=y("div","persona-approval-menu"),Y=y("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",Dl("\u2318\u23CE")),_.appendChild(Y),U=Id({anchor:V,content:_,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,U),Y.addEventListener("click",()=>{_o(e,t.id),r()})}else{let V=y("button","persona-approval-primary persona-approval-primary--solo");V.type="button",V.setAttribute("data-action","allow"),j(V),V.append(o?.approveLabel??"Allow"),M.append(V,A)}return T.appendChild(M),l.appendChild(T),l.addEventListener("click",V=>{let K=V.target instanceof Element?V.target.closest("[data-action]"):null;if(!K)return;let ne=K.getAttribute("data-action");if(ne==="toggle-params"){let D=l.querySelector('[data-role="params"]');if(D){let _=D.hidden;D.hidden=!_,x.setAttribute("aria-expanded",_?"true":"false"),x.setAttribute("aria-label",_?v:g),Oo.set(t.id,_)}return}if(ne==="toggle-menu"){U?.toggle();return}if(ne==="always"){_o(e,t.id),r({remember:!0});return}if(ne==="allow"){_o(e,t.id),r();return}if(ne==="deny"){_o(e,t.id),s();return}}),l},Fu=()=>{let e=Ry();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let p=Wy(a);if(l.status!=="pending"){if(_o(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Dy(l)}Du(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Fy(e,o,l,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=w=>{Rd(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),_o(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])_o(e,o);e.latestPendingApprovalId=null}}};var Ps=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Is=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var Ny=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Oy=new Set(["step_start","execution_start"]),_y=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),$y=new Set(["step_complete","agent_turn_complete"]),Uy=new Set(["flow_complete","agent_complete"]),Nu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),_u=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,$o=(e,t)=>{let n=e[t];return _u(n)?n:void 0};function Fl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function zy(e,t){return typeof t.type=="string"?t.type:e}function jy(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Vy(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Ou(e){let t=$o(e,"result"),n=[$o(e,"tokens"),$o(e,"totalTokens"),t?$o(t,"tokens"):void 0,$o(e,"usage"),t?$o(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function qy(e){let t=$o(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function Ky(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=Ky){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:fi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!_u(n)){Nu.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=zy(t,n),r=this.now();if(Ny.has(o)){this.startRun(r);return}if(Oy.has(o)){this.run||this.startRun(r);return}if(_y.has(o)){if(!Vy(o,n))return;let s=jy(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Fl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:fi(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if($y.has(o)){if(!this.run)return;let s=this.run,a=Ou(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+Fl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:fi(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Uy.has(o)){if(!this.run)return;let s=this.run,a=Ou(n),l=a??s.exactOutputTokens+Fl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:fi(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Nu.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:qy(n)??o-t.startedAt}};function Cr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Gy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Qy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Xy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Jy=100;function Yy(e,t){let n={...Gy,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Qy}function Zy(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function eb(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function tb(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function nb(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function ob(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function rb(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function sb(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function ab(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Nl(e,t,n,o,r,s,a,l){let p=r.has(e.id),d=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Cr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=y("div",""),g=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);x&&v.appendChild(x);let P=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),F=o.timestampFormat??"relative";P.textContent=F==="relative"?Zy(e.timestamp,n):eb(e.timestamp);let k=null;o.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let T=Yy(e.type,o.badgeColors),M=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");M.style.backgroundColor=T.bg,M.style.color=T.text,M.style.borderColor=T.text+"50",M.textContent=e.type;let U=o.descriptionFields??Xy,j=tb(e.payload,U),A=null;j&&(A=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),A.textContent=j);let V=y("div","persona-flex-1 persona-min-w-0"),K=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),ne=ae("clipboard","12px","currentColor",1.5);return ne&&K.appendChild(ne),K.addEventListener("click",async D=>{D.stopPropagation(),await nb(ob(e)),K.innerHTML="";let _=ae("check","12px","currentColor",1.5);_&&K.appendChild(_),setTimeout(()=>{K.innerHTML="";let Y=ae("clipboard","12px","currentColor",1.5);Y&&K.appendChild(Y)},1500)}),g.appendChild(v),g.appendChild(P),k&&g.appendChild(k),g.appendChild(M),A&&g.appendChild(A),g.appendChild(V),g.appendChild(K),w.appendChild(g),p&&w.appendChild(ab(e,a,l)),w}}function $u(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return g();function g(){let v=u.classNames,x=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Cr(x,v?.panel);let P=[],F="",k="",T=null,M=[],U={},j=0,A=qa(),V=0,K=0,ne=!1,D=null,_=!1,Y=0,ge=new Set,he=new Map,ce="",Z="",de=null,te,ie,J,fe,Ce=null,ye=null,xe=null;function ve(){let R=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Q=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Cr(Q,v?.headerBar),a){ye=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",Ce=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ce.textContent="-- tok/s",xe=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),xe.style.display="none",xe.style.pointerEvents="none";let De=ye,Ht=xe,vt=()=>{if(!Ht.textContent)return;let Fs=De.getBoundingClientRect(),Kn=R.getBoundingClientRect();Ht.style.left=`${Fs.left-Kn.left}px`,Ht.style.top=`${Fs.bottom-Kn.top+4}px`,Ht.style.display="block"},Gt=()=>{Ht.style.display="none"};ye.addEventListener("mouseenter",vt),ye.addEventListener("mouseleave",Gt),ye.appendChild(Ce)}let se=y("div","persona-flex-1");te=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ee=y("option","");Ee.value="",Ee.textContent="All events (0)",te.appendChild(Ee),ie=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ie.type="button",ie.title="Copy All";let nt=ae("clipboard-copy","12px","currentColor",1.5);nt&&ie.appendChild(nt);let tt=y("span","persona-event-copy-all persona-text-xs");tt.textContent="Copy All",ie.appendChild(tt),ye&&Q.appendChild(ye),Q.appendChild(se),Q.appendChild(te),Q.appendChild(ie);let _e=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Cr(_e,v?.searchBar);let Je=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),q=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Je&&q.appendChild(Je),J=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Cr(J,v?.searchInput),J.type="text",J.placeholder="Search event payloads...",fe=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),fe.type="button",fe.style.display="none";let $e=ae("x","12px","currentColor",2);return $e&&fe.appendChild($e),_e.appendChild(q),_e.appendChild(J),_e.appendChild(fe),R.appendChild(Q),R.appendChild(_e),xe&&R.appendChild(xe),R}let Ae,Te=s.find(R=>R.renderEventStreamToolbar);Te?.renderEventStreamToolbar&&r?Ae=Te.renderEventStreamToolbar({config:r,defaultRenderer:()=>ve(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{F=Q,Xe(),le()},onSearchChange:Q=>{k=Q,Xe(),le()}})??ve():Ae=ve();let qe=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");qe.style.display="none";function ze(){if(!a||!Ce||!ye)return;let R=a(),Q=rb(R);Ce.textContent=Q;let se=sb(R);xe&&(xe.textContent=se,se||(xe.style.display="none")),ye.setAttribute("aria-label",se?`Throughput: ${Q}, ${se}`:`Throughput: ${Q}`)}let Me=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Pe=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Pe.style.height="100%";let Ke=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Cr(Ke,v?.scrollIndicator),Ke.style.display="none",Ke.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Wt=ae(d,"14px","currentColor",2);Wt&&Ke.appendChild(Wt);let It=y("span","");It.textContent=c,Ke.appendChild(It);let qt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");qt.style.display="none",Me.appendChild(Pe),Me.appendChild(qt),Me.appendChild(Ke),x.setAttribute("tabindex","0"),x.appendChild(Ae),x.appendChild(qe),x.appendChild(Me);function xt(){let R=t.getAll(),Q={};for(let _e of R)Q[_e.type]=(Q[_e.type]||0)+1;let se=Object.keys(Q).sort(),Ee=se.length!==M.length||!se.every((_e,Je)=>_e===M[Je]),we=!Ee&&se.some(_e=>Q[_e]!==U[_e]),nt=R.length!==Object.values(U).reduce((_e,Je)=>_e+Je,0);if(!Ee&&!we&&!nt||(M=se,U=Q,!te))return;let tt=te.value;if(te.options[0].textContent=`All events (${R.length})`,Ee){for(;te.options.length>1;)te.remove(1);for(let _e of se){let Je=y("option","");Je.value=_e,Je.textContent=`${_e} (${Q[_e]||0})`,te.appendChild(Je)}tt&&se.includes(tt)?te.value=tt:tt&&(te.value="",F="")}else for(let _e=1;_e<te.options.length;_e++){let Je=te.options[_e];Je.textContent=`${Je.value} (${Q[Je.value]||0})`}}function Be(){let R=t.getAll();if(F&&(R=R.filter(Q=>Q.type===F)),k){let Q=k.toLowerCase();R=R.filter(se=>se.type.toLowerCase().includes(Q)||se.payload.toLowerCase().includes(Q))}return R}function ue(){return F!==""||k!==""}function Xe(){j=0,V=0,A.resume(),Ke.style.display="none"}function We(R){ge.has(R)?ge.delete(R):ge.add(R),de=R;let Q=Pe.scrollTop,se=A.isFollowing();_=!0,A.pause(),le(),Pe.scrollTop=Q,se&&A.resume(),_=!1}function me(){return ho(Pe,50)}function le(){K=Date.now(),ne=!1,ze(),xt();let R=t.getEvictedCount();R>0?(qe.textContent=`${R.toLocaleString()} older events truncated`,qe.style.display=""):qe.style.display="none",P=Be();let Q=P.length,se=t.getSize()>0;Q===0&&se&&ue()?(qt.textContent=k?`No events matching '${k}'`:"No events matching filter",qt.style.display="",Pe.style.display="none"):(qt.style.display="none",Pe.style.display=""),ie&&(ie.title=ue()?`Copy Filtered (${Q})`:"Copy All"),p&&!A.isFollowing()&&Q>j&&(V+=Q-j,It.textContent=c?`${c}${V>0?` (${V})`:""}`:"",Ke.style.display=""),j=Q;let Ee=t.getAll(),we=Ee.length>0?Ee[0].timestamp:0,nt=new Set(P.map(Je=>Je.id));for(let Je of ge)nt.has(Je)||ge.delete(Je);let tt=F!==ce||k!==Z,_e=he.size===0&&P.length>0;if(tt||_e||P.length===0){Pe.innerHTML="",he.clear();let Je=document.createDocumentFragment();for(let q=0;q<P.length;q++){let $e=Nl(P[q],q,we,u,ge,We,s,r);he.set(P[q].id,$e),Je.appendChild($e)}Pe.appendChild(Je),ce=F,Z=k,de=null}else{if(de!==null){let q=he.get(de);if(q&&q.parentNode===Pe){let $e=P.findIndex(De=>De.id===de);if($e>=0){let De=Nl(P[$e],$e,we,u,ge,We,s,r);Pe.insertBefore(De,q),q.remove(),he.set(de,De)}}de=null}let Je=new Set(P.map(q=>q.id));for(let[q,$e]of he)Je.has(q)||($e.remove(),he.delete(q));for(let q=0;q<P.length;q++){let $e=P[q];if(!he.has($e.id)){let De=Nl($e,q,we,u,ge,We,s,r);he.set($e.id,De),Pe.appendChild(De)}}}A.isFollowing()&&(Pe.scrollTop=Pe.scrollHeight)}function Re(){if(Date.now()-K>=Jy){D!==null&&(cancelAnimationFrame(D),D=null),le();return}ne||(ne=!0,D=requestAnimationFrame(()=>{D=null,le()}))}let Kt=(R,Q)=>{if(!ie)return;ie.innerHTML="";let se=ae(R,"12px","currentColor",1.5);se&&ie.appendChild(se);let Ee=y("span","persona-text-xs");Ee.textContent="Copy All",ie.appendChild(Ee),setTimeout(()=>{ie.innerHTML="";let we=ae("clipboard-copy","12px","currentColor",1.5);we&&ie.appendChild(we);let nt=y("span","persona-text-xs");nt.textContent="Copy All",ie.appendChild(nt),ie.disabled=!1},Q)},pt=async()=>{if(ie){ie.disabled=!0;try{let R;ue()?R=P:n?(R=await n(),R.length===0&&(R=t.getAll())):R=t.getAll();let Q=R.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),Kt("check",1500)}catch{Kt("x",1500)}}},mt=()=>{te&&(F=te.value,Xe(),le())},z=()=>{!J||!fe||(fe.style.display=J.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{k=J.value,Xe(),le()},150))},C=()=>{!J||!fe||(J.value="",k="",fe.style.display="none",T&&clearTimeout(T),Xe(),le())},$=()=>{if(_)return;let R=Pe.scrollTop,{action:Q,nextLastScrollTop:se}=Ka({following:A.isFollowing(),currentScrollTop:R,lastScrollTop:Y,nearBottom:me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=se,Q==="resume"?(A.resume(),V=0,Ke.style.display="none"):Q==="pause"&&(A.pause(),p&&(It.textContent=c,Ke.style.display=""))},h=R=>{let Q=Ga({following:A.isFollowing(),deltaY:R.deltaY,nearBottom:me(),resumeWhenNearBottom:!0});Q==="pause"?(A.pause(),p&&(It.textContent=c,Ke.style.display="")):Q==="resume"&&(A.resume(),V=0,Ke.style.display="none")},L=()=>{p&&(Pe.scrollTop=Pe.scrollHeight,A.resume(),V=0,Ke.style.display="none")},I=R=>{let Q=R.target;if(!Q||Q.closest("button"))return;let se=Q.closest("[data-event-id]");if(!se)return;let Ee=se.getAttribute("data-event-id");Ee&&We(Ee)},H=R=>{if((R.metaKey||R.ctrlKey)&&R.key==="f"){R.preventDefault(),J?.focus(),J?.select();return}R.key==="Escape"&&(J&&document.activeElement===J?(C(),J.blur(),x.focus()):o&&o())};ie&&ie.addEventListener("click",pt),te&&te.addEventListener("change",mt),J&&J.addEventListener("input",z),fe&&fe.addEventListener("click",C),Pe.addEventListener("scroll",$),Pe.addEventListener("wheel",h,{passive:!0}),Pe.addEventListener("click",I),Ke.addEventListener("click",L),x.addEventListener("keydown",H);function B(){T&&clearTimeout(T),D!==null&&(cancelAnimationFrame(D),D=null),ne=!1,he.clear(),ie&&ie.removeEventListener("click",pt),te&&te.removeEventListener("change",mt),J&&J.removeEventListener("input",z),fe&&fe.removeEventListener("click",C),Pe.removeEventListener("scroll",$),Pe.removeEventListener("wheel",h),Pe.removeEventListener("click",I),Ke.removeEventListener("click",L),x.removeEventListener("keydown",H)}return{element:x,update:Re,destroy:B}}}function Uu(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(g=>g===w||g.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let g=w;if(u.key===r)g=Math.min(w+1,s.length-1);else if(u.key===o)g=Math.max(w-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==w&&t.onSelect(g)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((g,v)=>{g.setAttribute("role","tab");let x=v===w;g.setAttribute("aria-selected",x?"true":"false"),g.tabIndex=x||w<0&&v===0?0:-1}),a){let g=(w>=0?u[w]:void 0)??u[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function zu(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=z=>({start:z===!1?!1:typeof z=="object"&&z?z.start!==!1:!0,end:z===!1?!1:typeof z=="object"&&z?z.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),_?.hide()};w&&w.addEventListener("click",()=>{g(),t.onDismiss?.()});let v=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let x=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");x.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&x.classList.add("persona-artifact-toolbar-document");let P=y("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let F=Pt({icon:"x",label:a});F.addEventListener("click",()=>{g(),t.onDismiss?.()});let k="rendered",T=$a({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:z=>{k=z==="source"?"source":"rendered",Kt()}}),M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=n?.documentToolbarShowCopyLabel===!0,j=n?.documentToolbarShowCopyChevron===!0,A=n?.documentToolbarCopyMenuItems,V=!!(j&&A&&A.length>0),K=null,ne,D=null,_=null;if(r&&(U||j)&&!V){if(ne=U?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),j){let z=ae("chevron-down",14,"currentColor",2);z&&ne.appendChild(z)}}else r&&V?(K=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ne=U?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),D=Pt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),K.append(ne,D)):r?ne=Pt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(ne=Pt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&ne.classList.add("persona-hidden"));let Y=r?Pt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pt({icon:"refresh-cw",label:"Refresh"}),ge=r?Pt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Pt({icon:"x",label:a}),he=Pt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let ce=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),Z=e.features?.artifacts?.toolbarActions??[],de=()=>{let z=Me.find(L=>L.id===Pe)??Me[Me.length-1],C=z?.id??null,$=z?.artifactType==="markdown"?z.markdown??"":"",h=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:$,jsonPayload:h,id:C}},te=async()=>{let z=Me.find(C=>C.id===Pe)??Me[Me.length-1];try{await navigator.clipboard.writeText(xs(z))}catch{}};if(ne.addEventListener("click",async()=>{let z=n?.onDocumentToolbarCopyMenuSelect;if(z&&V){let{markdown:C,jsonPayload:$,id:h}=de();try{await z({actionId:"primary",artifactId:h,markdown:C,jsonPayload:$})}catch{}return}await te()}),D&&A?.length){let z=()=>v.closest("[data-persona-root]")??document.body,C=()=>{_=yr({items:A.map($=>({id:$.id,label:$.label})),onSelect:async $=>{let{markdown:h,jsonPayload:L,id:I}=de(),H=n?.onDocumentToolbarCopyMenuSelect;try{H?await H({actionId:$,artifactId:I,markdown:h,jsonPayload:L}):$==="markdown"||$==="md"?await navigator.clipboard.writeText(h):$==="json"||$==="source"?await navigator.clipboard.writeText(L):await navigator.clipboard.writeText(h||L)}catch{}},anchor:K??D,position:"bottom-right",portal:z()})};v.isConnected?C():requestAnimationFrame(C),D.addEventListener("click",$=>{$.stopPropagation(),_?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Kt()}),ge.addEventListener("click",()=>{g(),t.onDismiss?.()});let ie=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)x.replaceChildren(),K?M.append(K,Y,ge):M.append(ne,Y,ge),M.insertBefore(ce,ge),M.insertBefore(he,ge),x.append(T.element,ie,M);else{let z=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");z.append(ne,ce,he,F),x.appendChild(P),x.appendChild(z)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let J=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&J.style.setProperty("--persona-artifact-tab-fade-size",p);let fe=e.features?.artifacts?.renderTabBar,Ce=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Uu(J,{onSelect:z=>t.onSelect(Me[z].id)}),xe=z=>{let C=z.scrollWidth-z.clientWidth,$=C>1,h=Math.abs(z.scrollLeft);z.classList.toggle("persona-artifact-tab-fade-start",c&&$&&h>1),z.classList.toggle("persona-artifact-tab-fade-end",u&&$&&h<C-1)},ve=0,Ae=()=>{if(ve)return;let z=()=>{ve=0,xe(J)};ve=typeof requestAnimationFrame=="function"?requestAnimationFrame(z):setTimeout(z,0)};J.addEventListener("scroll",()=>Ae(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>xe(J)).observe(J);let Te=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),qe=()=>{Te.scrollLeft=0},ze=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(qe):setTimeout(qe,0)};if(l){for(let z of[J,Ce])z.style.paddingLeft=l,z.style.paddingRight=l;Te.style.padding=l}v.appendChild(x),v.appendChild(J),v.appendChild(Ce),v.appendChild(Te);let Me=[],Pe=null,Ke=!1,Wt=!1,It=!0,qt=!1,xt=null,Be="",ue=null,Xe=!1,We=z=>z.artifactType==="markdown"&&!!z.file||r?k:"rendered",me=z=>{r||(z&&!Xe?(x.insertBefore(T.element,P),Xe=!0):!z&&Xe&&(T.element.remove(),Xe=!1))},le=()=>Pe&&Me.find(z=>z.id===Pe)||Me[Me.length-1],Re=()=>{let z=vs(le());if(!z){ce.replaceChildren();return}let C=Z.filter($=>$.visible===void 0||$.visible(z)).map($=>br($,{documentChrome:r,onClick:()=>{let h=vs(le());if(h)try{Promise.resolve($.onClick(h)).catch(()=>{})}catch{}}}));ce.replaceChildren(...C)},Kt=()=>{Re();let z=r&&Me.length<=1,C=!!fe;if(J.classList.toggle("persona-hidden",z||C),Ce.classList.toggle("persona-hidden",z||!C),C&&fe){let L=Me.map(I=>I.id).join("|")+" "+(Pe??"");if(L!==Be){Be=L;let I=fe({records:Me,selectedId:Pe,onSelect:t.onSelect});Ce.firstElementChild!==I&&Ce.replaceChildren(I)}}else{ye.beforeRender(),J.replaceChildren();let L=[],I=-1;for(let[H,B]of Me.entries()){let R=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");R.type="button";let Q=B.artifactType==="markdown"?B.file:void 0,se=Q?Ln(Q.path):B.title||B.id.slice(0,8),Ee=Q?.path||B.title||se;R.textContent=se,R.title=Ee,R.setAttribute("aria-label",Ee),B.id===Pe&&(R.classList.add("persona-bg-persona-container","persona-border-persona-border"),I=H),R.addEventListener("click",()=>t.onSelect(B.id)),J.appendChild(R),L.push(R)}if(ye.render(L,I),I>=0&&Pe!==xt){xt=Pe;let H=L[I];typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",inline:"nearest"})}xe(J)}let $=Pe&&Me.find(L=>L.id===Pe)||Me[Me.length-1];if(!$){Te.replaceChildren(),ue=null,me(!1);return}let h=$.artifactType==="markdown"?$.file:void 0;if(me(!!h),r){let L=h?fo(h):$.artifactType==="markdown"?"MD":$.component??"Component",I=($.title||"Document").trim(),H=h?Ln(h.path):I.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${H} \xB7 ${L}`}else P.textContent=h?Ln(h.path):s;ue?(ue.el.parentElement!==Te&&Te.replaceChildren(ue.el),ue.update($)):(ue=ja($,{config:e,resolveViewMode:We}),Te.replaceChildren(ue.el)),Te.classList.toggle("persona-artifact-content-flush",!!Te.querySelector(".persona-code-pre"))},pt=()=>{let z=Me.length>0;if(v.classList.toggle("persona-hidden",!z),w){let h=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;z&&h&&Ke?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},mt=()=>{qt=!1,Kt(),pt()};return{element:v,backdrop:w,update(z){let C=z.selectedId??z.artifacts[z.artifacts.length-1]?.id??null,$=C!==Pe;Me=z.artifacts,Pe=C,Me.length>0&&(Ke=!0),qt=!0,It&&mt(),$&&qe()},setMobileOpen(z){Ke=z,!z&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):pt()},setExpanded(z){z!==Wt&&(Wt=z,ze());let C=ae(z?"minimize":"maximize",16,"currentColor",2);C&&he.replaceChildren(C);let $=z?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",$),he.title=$},setExpandToggleVisible(z){he.classList.toggle("persona-hidden",!z)},setCopyButtonVisible(z){r||ne.classList.toggle("persona-hidden",!z)},setCustomActions(z){Z=z,Re()},setTabFade(z){let C=d(z);C.start===c&&C.end===u||(c=C.start,u=C.end,xe(J))},setRenderTabBar(z){z!==fe&&(fe=z,Be="",Kt())},setVisible(z){z!==It&&(It=z,z&&qt&&mt())}}}function Yt(e){return e?.features?.artifacts?.enabled===!0}function ju(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function ib(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Vu=["panel","seamless","detached"];function Ol(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Vu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function _l(e){return!e||!Yt(e)?!1:Ol(e)==="detached"}function Ws(e,t){if(!Yt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ib(e),ju(e,t);return}let n=t.features?.artifacts?.layout,o=Ol(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ju(e,t)}function Hs(e,t){for(let l of Vu)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Yt(t))return;let n=t.features?.artifacts?.layout,o=Ol(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function qu(e,t){return!t||!Yt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var lb=new Set(["__proto__","prototype","constructor"]),cb=new Set(["collapsed","card","panel","inline"]),Ku=new Set(["markdown","component"]),db=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Uo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mi=e=>!lb.has(e),$l=e=>typeof e=="string"&&cb.has(e),zo=e=>Object.keys(e).length>0;function In(e,t,n,o){e.push({path:t,code:n,message:o})}var pb="Ignored because this key is not part of the persisted preference schema.",gi="Ignored an unsupported value.",ub="Expected collapsed, panel, or inline.",fb='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gu={kind:"mode",message:gi},Ar={kind:"string",message:"Expected a CSS length string."},qn={kind:"boolean"},gb={paneWidth:Ar,paneMaxWidth:Ar,paneMinWidth:Ar,expandedPanelWidth:Ar,resizableMinWidth:Ar,resizableMaxWidth:Ar,expandLauncherPanelWhenOpen:qn,resizable:qn},mb={kind:"object",message:"Expected a preference object.",children:{showToolCalls:qn,showReasoning:qn,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:gi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:gi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:gi},expandable:qn,grouped:qn}},reasoningDisplay:{kind:"object",children:{expandable:qn,activePreview:qn}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gu,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gu,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Ku,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Ku}}},filePreview:{kind:"object",children:{enabled:qn}},layout:{kind:"object",children:gb}}}}};function Qu(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:In(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:In(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:In(o,n,"invalid_value",t.message);case"mode":return $l(e)?gn(e):In(o,n,"invalid_value",t.message);case"modeMap":{if(!Uo(e))return In(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let p=r?a:rr(a);mi(a)&&(r?r.has(a):db.test(p))?$l(l)?s[p]=gn(l):In(o,`${n}.${a}`,"invalid_value",ub):In(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":fb)}return zo(s)?s:void 0}case"object":{if(t.bareMode&&$l(e))return gn(e);if(!Uo(e))return In(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!mi(l)||!r.includes(l))&&In(o,s(l),"unknown_key",pb);let a={};for(let l of r){let p=t.children[l],d=Qu(e[l],p,s(l),o);if(p.deprecated&&e[l]!==void 0&&In(o,s(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,u=a[c];a[c]=Uo(u)&&Uo(d)?{...u,...d}:d}return zo(a)?a:void 0}}}function hb(e){let t=[];return{preferences:(e===null?void 0:Qu(e,mb,"",t))??{},issues:t}}function Sr(e){if(Array.isArray(e))return e.map(Sr);if(!Uo(e))return e;let t={};for(let[n,o]of Object.entries(e))mi(n)&&o!==void 0&&(t[n]=Sr(o));return t}function Xu(e,t){let n=Sr(e);for(let[o,r]of Object.entries(t)){if(!mi(o)||r===void 0)continue;let s=n[o];n[o]=Uo(s)&&Uo(r)?Xu(s,r):Sr(r)}return n}function yb(e){let t={},n;for(let r of e){let s=hb(r).preferences;n=Ju(n,s.artifacts?.display),t=Xu(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function bb(e,t){if(t===void 0)return e===void 0?void 0:Sr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...zo(r)?{byMediaType:r}:{}};return zo(s)?s:void 0}function Ju(e,t){if(t===void 0)return e===void 0?void 0:Sr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=bb(n.files,t.files),a={...o?{default:o}:{},...zo(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return zo(a)?a:void 0}function vb(e={},t){let n=yb(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Ju(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ul(e){let t=e.preferences;return!t||!zo(t)?e:{...e,features:vb(e.features??{},[t])}}function wb(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function xb(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Cb(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Ab(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function zl(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Yu(e,t,n,o,r,s){let a=wb(r,200),l=Ab(t,n,o,200);l=Math.max(a,l);let p=xb(s);return p!==null&&(l=Math.min(l,p)),Cb(e,a,l)}var Zu={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},jl=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=Zu[a]??Zu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),d=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let v=y("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,p.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let x=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${t.id}-${a}-${v.name}`;let P=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=v.label,x.appendChild(P);let F=v.type??"text",k;F==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=F),k.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",k.id=`${t.id}-${a}-${v.name}`,k.name=v.name,k.placeholder=v.placeholder??"",v.required&&(k.required=!0),x.appendChild(k),c.appendChild(x)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async v=>{v.preventDefault();let x=n.formEndpoint??"/form",P=new FormData(c),F={};P.forEach((k,T)=>{F[T]=k}),F.type=a,g.disabled=!0,w.textContent="Submitting\u2026";try{let k=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(F)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let T=await k.json();w.textContent=T.message??"Thanks! We'll be in touch soon.",T.success&&T.nextPrompt&&await o.sendMessage(String(T.nextPrompt))}catch(k){w.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Vl=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ql=new Vl;var ef=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sb=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),tf=(e,t,n)=>{if(!ef(e)||!ef(t)||Sb.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=tf(e[r],t[r],s)}return o};function nf(e,t){let n=tf(e,t,"");return Ha(n)}var of=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var Tb=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Mb=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Gl=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Tb(e),n=Mb(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Kl=e=>typeof e=="string"?e:e==null?"":String(e),Bs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Kl(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Kl(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Kl(n.text)}}},rf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ql=e=>{let t=new Set(rf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(rf(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let p={action:l,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var Eb=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},kb=e=>e.map(t=>({...t,streaming:!1})),Lb=e=>e.map(t=>({...t,status:"complete"})),sf=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Eb(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?kb(n.messages):void 0,artifacts:n.artifacts?Lb(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as hS,STR as yS,OBJ as bS}from"partial-json";function af(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Vn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function lf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Xl(e){let t=lf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function cf(e){let t=lf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Pb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function df(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=Pb}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,g.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,g.appendChild(x),w.appendChild(g);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let F=[];for(let j=1;j<=5;j++){let A=document.createElement("button");A.type="button",A.className="persona-feedback-rating-btn persona-feedback-star-btn",A.setAttribute("role","radio"),A.setAttribute("aria-checked","false"),A.setAttribute("aria-label",`${j} star${j>1?"s":""}: ${d[j-1]}`),A.title=d[j-1],A.dataset.rating=String(j),A.innerHTML=`
|
|
39
|
+
`,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},l=Rt(s),u=n.querySelector("[data-role='launcher-title']");if(u){let k=a.title??"Chat Assistant";u.textContent=k,u.setAttribute("title",k)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let k=a.subtitle??"Here to help you get answers fast";d.textContent=k,d.setAttribute("title",k)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let k=a.agentIconSize??"40px";if(f.style.height=k,f.style.width=k,a.agentIconBackgroundColor?(f.style.backgroundColor=a.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",a.agentIconName){let P=parseFloat(k)||24,H=ae(a.agentIconName,P*.6,"var(--persona-text-inverse, #ffffff)",2);H?(f.appendChild(H),f.style.display=""):(f.textContent=a.agentIconText??"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=a.agentIconText??"\u{1F4AC}",f.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let k=a.agentIconSize??"40px";w.style.height=k,w.style.width=k,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let k=a.callToActionIconSize??"32px";g.style.height=k,g.style.width=k,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let P=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,P=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",a.callToActionIconName){let H=parseFloat(k)||24,F=Math.max(H-P,8),N=ae(a.callToActionIconName,F,"currentColor",2);N?g.appendChild(N):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let v=a.position&&ln[a.position]?ln[a.position]:ln["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${C} ${v}`,l||(n.style.zIndex=String(a.zIndex??Nt));let B="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??B,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:S,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},Qb="teaser-dismissed",Df=new Set,Bf=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${Qb}`},Jb=(e,t)=>{if(Df.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},Zb=(e,t)=>{if(Df.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},ev=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,tv=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Rt(e??{})?null:t},Ff=(e,t)=>{let n=b("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,l=null,u=null,d=!1,c=!1,f=!1,w=!1,g=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,v=()=>{u!==null&&(clearTimeout(u),u=null)},C=()=>{!s||!d||(d=!1,s.hidden=!0)},T=Y=>{v(),f=!0,C(),Zb(Bf(o),Y&&g())},B=Y=>{!r||f||T(Y==="user"&&d)},S=()=>{u=null,!(!s||f||w)&&(c=!0,d=!0,s.hidden=!1,!(ev()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},k=()=>{!r||!s||f||c||w||Jb(Bf(o),g())||(v(),u=setTimeout(S,Math.max(0,r.delayMs??0)))},P=()=>{T(g()),t()},H=Y=>{Y.stopPropagation(),T(g())},N=vc(e,()=>{B("user"),t()}),z=()=>{v(),l?.removeEventListener("click",P),a?.removeEventListener("click",H),s?.remove(),s=null,l=null,a=null,d=!1},j=()=>{l=Ee("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",P),a=Ee("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",H),s=Ee("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,N.element)},te=()=>{let Y=o.launcher?.position??"bottom-right",ue=ln[Y]??ln["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",N.element.style.position="";return}n.className=Pn("persona-launcher-surface",ue),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??Nt),N.element.style.position="static"},A=Y=>{let ue=tv(Y);if(r=ue,!ue){z();return}s||j(),l.textContent=ue.text,a.hidden=ue.dismissible===!1,a.setAttribute("aria-label",ue.dismissLabel??"Dismiss message"),k()},G=Y=>{o=Y,N.update(Y),A(Y),te()},Q=(Y,ue="user")=>{w=Y,Y&&B(ue)},ie=()=>{z(),N.destroy(),n.remove()};return n.appendChild(N.element),e&&(A(e),te()),{element:n,launcher:N,get teaser(){return s?{element:s,show:S,dismiss:T}:null},setPanelOpen:Q,update:G,destroy:ie}};var Of=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Wf(e),s=Hf(e,t),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},u={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:u,composer:d,replaceHeader:w=>(u.element.replaceWith(w.header),u.element=w.header,u.iconHolder=w.iconHolder,u.headerTitle=w.headerTitle,u.headerSubtitle=w.headerSubtitle,u.closeButton=w.closeButton,u.closeButtonWrapper=w.closeButtonWrapper,u.clearChatButton=w.clearChatButton,u.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},wc=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>vc(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Ff(e,n);return{instance:r,element:r.element}};var nv=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},ov=(e,t,n)=>`${nv(e)}plugin:${t}:${n}`,Nf=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>ov(e(),r,a);return{get:a=>{let l=s(a),u=o();if(u)try{return u.getItem(l)}catch{n=!0}return t.get(l)??null},set:(a,l)=>{let u=s(a),d=o();if(d)try{d.setItem(u,l);return}catch{n=!0}t.set(u,l)},remove:a=>{let l=s(a);t.delete(l);let u=o();if(u)try{u.removeItem(l)}catch{n=!0}}}}};var $r=new Set,rv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
|
|
40
|
+
`):""},_f=(e,t)=>{let n=$r.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},xc=(e,t)=>{let n=e.reasoning,o=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&$r.has(e.id),l=n.status!=="complete",u=sv(e,r.previewMaxLines??3),d=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",g=t?.reasoning??{},v=String(n.startedAt??Date.now()),C=()=>{let ie=b("span","");return ie.setAttribute("data-tool-elapsed",v),ie.textContent=ja(n),ie},T=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:w,previewText:u,isActive:l,config:t??{},elapsed:ja(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(f.textContent=T,c.appendChild(f)):T instanceof HTMLElement?c.appendChild(T):(f.textContent=w,c.appendChild(f));let B=b("span","persona-text-xs persona-text-persona-primary");B.textContent=lu(n),c.appendChild(B);let S=r.loadingAnimation??"none",k=g.activeTextTemplate,P=g.completeTextTemplate,H=l?k:P,F=T instanceof HTMLElement,N=(ie,Y)=>{f.textContent="";let ue=Va(ie,""),X=0;for(let ge of ue){let Z=ge.styles.length>0?(()=>{let pe=b("span",ge.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(pe),pe})():f;if(ge.isDuration&&l)Z.appendChild(C());else{let pe=ge.isDuration?ja(n):ge.text;Y?X=Ao(Z,pe,X):Z.appendChild(document.createTextNode(pe))}}};if(!F&&H)if(B.style.display="none",f.style.display="",l&&S!=="none"){let ie=g.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),S==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),N(H,!1)):(f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),N(H,!0))}else N(H,!1);else if(!F&&l&&S!=="none"){f.style.display="";let ie=g.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),S==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`);else{f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${ie}ms`),S==="shimmer-color"&&(g.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Y=f.textContent||w;f.textContent="",Ao(f,Y,0)}n.status==="complete"&&(f.style.display="none")}else F||(n.status==="complete"?f.style.display="none":f.style.display="");let z=null;if(s){z=b("div","persona-flex persona-items-center");let Y=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show";let ue=b("div","persona-flex persona-items-center persona-ml-auto");ue.append(z),d.append(c,ue)}else d.append(c);let j=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","reasoning"),j.style.display="none",j.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&u){let ie=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:u,isActive:l,config:t??{}});rv(j,ie)||(j.textContent=u),j.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,j),o;let te=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");te.style.display=a?"":"none";let A=n.chunks.join(""),G=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=A||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),te.appendChild(G),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Y=ae(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show"}te.style.display=a?"":"none",j.style.display=a?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(d,j,te),o};var Ur=new Set,av=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),iv=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
|
|
41
|
+
`);let r=wo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
42
|
+
`):""},Cc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},lv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=iv(e,o?.previewMaxLines??3),a=n?cu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",u=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&u.activeTextTemplate?d=$l(n,u.activeTextTemplate,d):!l&&u.completeTextTemplate&&(d=$l(n,u.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},$f=(e,t,n)=>{let o=Ur.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Ac=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ur.has(e.id),{summary:u,previewText:d,isActive:c}=lv(e,t),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let w=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let A=b("span","");return A.setAttribute("data-tool-elapsed",v),A.textContent=Ms(n),A},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:u,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ms(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,w.appendChild(g)):T instanceof HTMLElement?w.appendChild(T):(g.textContent=u,w.appendChild(g));let B=s.loadingAnimation??"none",S=o.activeTextTemplate,k=o.completeTextTemplate,P=c?S:k,H=T instanceof HTMLElement,F=(A,G)=>{g.textContent="";let Q=n.name?.trim()||"tool",ie=Va(A,Q),Y=0;for(let ue of ie){let X=ue.styles.length>0?(()=>{let ge=b("span",ue.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(ge),ge})():g;if(ue.isDuration&&c)X.appendChild(C());else{let ge=ue.isDuration?Ms(n):ue.text;G?Y=Ao(X,ge,Y):X.appendChild(document.createTextNode(ge))}}};if(!H)if(c&&B!=="none"){let A=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),P&&F(P,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),P)F(P,!0);else{let G=g.textContent||u;g.textContent="",Ao(g,G,0)}}else P&&F(P,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(N),f.append(w,Q)}else f.append(w);let z=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let A=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});av(z,A)||(z.textContent=d),z.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(f,z),r;let j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(j.style.display=l?"":"none",o.contentBackgroundColor&&(j.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(j.style.color=o.contentTextColor),o.contentPaddingX&&(j.style.paddingLeft=o.contentPaddingX,j.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(j.style.paddingTop=o.contentPaddingY,j.style.paddingBottom=o.contentPaddingY),n.name){let A=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?A.style.color=o.contentTextColor:o.headerTextColor&&(A.style.color=o.headerTextColor),A.textContent=n.name,j.appendChild(A)}if(n.args!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.args),A.append(G,Q),j.appendChild(A)}if(n.chunks&&n.chunks.length){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=n.chunks.join(""),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&n.result!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.result),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&typeof n.duration=="number"){let A=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(A.style.color=o.contentTextColor),A.textContent=`Duration: ${n.duration}ms`,j.appendChild(A)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),N){N.innerHTML="";let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show"}j.style.display=l?"":"none",z.style.display=l?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(f,z,j),r};var er=new Map,Wi=e=>{let n=(e.startsWith(Yn)?e.slice(Yn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Uf=e=>e?.approval!==!1?e?.approval:void 0,zf=(e,t)=>{let n=Uf(t)?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},jf=(e,t,n)=>{let o=Uf(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Vf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=zf(e,n);jf(o,s,n),r.style.display=s?"":"none"};var Ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let u=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ae(u,20,d,2);c&&l.appendChild(c);let f=b("div","persona-flex-1 persona-min-w-0"),w=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",w.appendChild(g),!r){let N=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");N.setAttribute("data-approval-status",n.status),n.status==="approved"?(N.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",N.style.color="var(--persona-palette-colors-success-700, #15803d)",N.textContent="Approved"):n.status==="denied"?(N.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",N.style.color="var(--persona-palette-colors-error-700, #b91c1c)",N.textContent="Denied"):n.status==="timeout"&&(N.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",N.style.color="var(--persona-palette-colors-warning-700, #b45309)",N.textContent="Timeout"),w.appendChild(N)}f.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Yn)?ws(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,S=T||(B?n.description:`The assistant wants to use \u201C${C??Wi(n.toolName)}\u201D.`),k=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=S,f.appendChild(k),n.reason){let N=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");N.setAttribute("data-approval-reason","true"),o?.reasonColor?N.style.color=o.reasonColor:o?.descriptionColor&&(N.style.color=o.descriptionColor);let z=b("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,N.appendChild(z),N.appendChild(document.createTextNode(n.reason)),f.appendChild(N)}let P=o?.detailsDisplay??"collapsed",H=!!n.description&&!B,F=H||!!n.parameters;if(P!=="hidden"&&F){let N=zf(e.id,t),z=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span");j.setAttribute("data-approval-details-label","true");let te=b("span","persona-inline-flex persona-items-center");te.setAttribute("data-approval-details-chevron","true"),z.append(j,te),jf(z,N,t),f.appendChild(z);let A=b("div");if(A.setAttribute("data-approval-details","true"),A.style.display=N?"":"none",H){let G=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,A.appendChild(G)}if(n.parameters){let G=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=wo(n.parameters),A.appendChild(G)}f.appendChild(A)}if(r){let N=b("div","persona-flex persona-gap-2 persona-mt-2");N.setAttribute("data-approval-buttons","true");let z=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let j=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);j&&(j.style.marginRight="4px",z.appendChild(j));let te=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(te);let A=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");A.type="button",A.style.backgroundColor=o?.denyButtonColor??"transparent",A.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",A.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,A.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",A.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");A.appendChild(Q),N.append(z,A),f.appendChild(N)}return a.append(l,f),s.appendChild(a),s};var cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},tr=(e,t)=>{qf(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},dv=e=>e?.approval!==!1?e?.approval:void 0,pv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},Sc=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uv=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Yn)?ws(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Wi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let u=document.createElement("strong");if(u.textContent=a,n.appendChild(u),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},fv=e=>{let t=b("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?Wi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},gv=(e,t,n,o,r,s,a)=>{let l=b("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let u=o?.detailsDisplay??"collapsed",d=!!n.description&&u!=="hidden",c=n.parameters!=null&&u!=="hidden",f=d||c,w=f&&pv(t.id,o),g=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=b("button","persona-approval-head");C.type="button",f?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:g)):C.setAttribute("data-static","true");let T=b("span","persona-approval-logo"),B=ae("shield-check",16,"currentColor",2);B&&T.appendChild(B),C.appendChild(T);let S=uv(n,o);if(f){let z=b("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let j=ae("chevron-down",14,"currentColor",2);j&&z.appendChild(j),S.append(" "),S.appendChild(z)}C.appendChild(S),l.appendChild(C);let k=b("div","persona-approval-body");if(f){let z=b("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!w,d){let j=b("p","persona-approval-desc");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,z.appendChild(j)}if(c){let j=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(j.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.textContent=wo(n.parameters),z.appendChild(j)}k.appendChild(z)}if(n.reason){let z=b("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span","persona-approval-reason-label");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(j,document.createTextNode(n.reason)),k.appendChild(z)}let P=b("div","persona-approval-actions"),H=null,F=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},N=b("button","persona-approval-deny");if(N.type="button",N.setAttribute("data-action","deny"),o?.denyButtonColor&&(N.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(N.style.color=o.denyButtonTextColor),N.append(o?.denyLabel??"Deny"),a){let z=b("div","persona-approval-split"),j=b("button","persona-approval-primary");j.type="button",j.setAttribute("data-action","always"),F(j),j.append(o?.approveLabel??"Always allow",Sc("\u23CE"));let te=b("button","persona-approval-caret");te.type="button",te.setAttribute("data-action","toggle-menu"),te.setAttribute("aria-label","More options"),F(te);let A=ae("chevron-down",15,"currentColor",2);A&&te.appendChild(A),z.append(j,te),P.append(z,N),N.append(Sc("Esc"));let G=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Sc("\u2318\u23CE")),G.appendChild(Q),H=Pp({anchor:z,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,H),Q.addEventListener("click",()=>{tr(e,t.id),r()})}else{let z=b("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),F(z),z.append(o?.approveLabel??"Allow"),P.append(z,N)}return k.appendChild(P),l.appendChild(k),l.addEventListener("click",z=>{let j=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!j)return;let te=j.getAttribute("data-action");if(te==="toggle-params"){let A=l.querySelector('[data-role="params"]');if(A){let G=A.hidden;A.hidden=!G,C.setAttribute("aria-expanded",G?"true":"false"),C.setAttribute("aria-label",G?v:g),er.set(t.id,G)}return}if(te==="toggle-menu"){H?.toggle();return}if(te==="always"){tr(e,t.id),r({remember:!0});return}if(te==="allow"){tr(e,t.id),r();return}if(te==="deny"){tr(e,t.id),s();return}}),l},Kf=()=>{let e=cv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let u=dv(a);if(l.status!=="pending"){if(tr(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return fv(l)}qf(e,o.id);let d=u?.enableAlwaysAllow===!0,c=gv(e,o,l,u,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=w=>{Ip(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),tr(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])tr(e,o);e.latestPendingApprovalId=null}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hv=new Set(["step_start","execution_start"]),yv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bv=new Set(["step_complete","agent_turn_complete"]),vv=new Set(["flow_complete","agent_complete"]),Gf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Xf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,nr=(e,t)=>{let n=e[t];return Xf(n)?n:void 0};function Tc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Hi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function wv(e,t){return typeof t.type=="string"?t.type:e}function xv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Cv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Yf(e){let t=nr(e,"result"),n=[nr(e,"tokens"),nr(e,"totalTokens"),t?nr(t,"tokens"):void 0,nr(e,"usage"),t?nr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(e.outputTokens)??cn(e.completionTokens)??(t?cn(t.outputTokens)??cn(t.completionTokens):void 0)}function Av(e){let t=nr(e,"result");return cn(e.executionTime)??cn(e.executionTimeMs)??cn(e.execution_time)??cn(e.duration)??(t?cn(t.executionTime)??cn(t.executionTimeMs):void 0)}function Sv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Sv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Hi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Xf(n)){Gf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=wv(t,n),r=this.now();if(mv.has(o)){this.startRun(r);return}if(hv.has(o)){this.run||this.startRun(r);return}if(yv.has(o)){if(!Cv(o,n))return;let s=xv(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Tc(a.visibleCharCount),u=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Hi(l,u),outputTokens:l,durationMs:u,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(bv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,u=s.exactOutputTokens+Tc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Hi(u,d),outputTokens:u,durationMs:d,source:l?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n),l=a??s.exactOutputTokens+Tc(s.visibleCharCount),u=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Hi(l,d),outputTokens:l,durationMs:d,source:u},this.run=null;return}if(Gf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Av(n)??o-t.startedAt}};function zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Tv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Mv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],kv=100;function Lv(e,t){let n={...Tv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Mv}function Pv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Iv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Wv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Rv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Hv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Bv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Dv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Fv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),u=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=o,l.appendChild(u),l}}function Mc(e,t,n,o,r,s,a,l){let u=r.has(e.id),d=b("div","persona-border-b persona-border-persona-divider persona-text-xs");zr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:u,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(f()),d;function f(){let w=b("div",""),g=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ae(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let T=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";T.textContent=B==="relative"?Pv(e.timestamp,n):Iv(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let k=Lv(e.type,o.badgeColors),P=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=e.type;let H=o.descriptionFields??Ev,F=Wv(e.payload,H),N=null;F&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=F);let z=b("div","persona-flex-1 persona-min-w-0"),j=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),te=ae("clipboard","12px","currentColor",1.5);return te&&j.appendChild(te),j.addEventListener("click",async A=>{A.stopPropagation(),await Rv(Hv(e)),j.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&j.appendChild(G),setTimeout(()=>{j.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&j.appendChild(Q)},1500)}),g.appendChild(v),g.appendChild(T),S&&g.appendChild(S),g.appendChild(P),N&&g.appendChild(N),g.appendChild(z),g.appendChild(j),w.appendChild(g),u&&w.appendChild(Fv(e,a,l)),w}}function Qf(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,u=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",f=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return g();function g(){let v=f.classNames,C=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");zr(C,v?.panel);let T=[],B="",S="",k=null,P=[],H={},F=0,N=ui(),z=0,j=0,te=!1,A=null,G=!1,Q=0,ie=new Set,Y=new Map,ue="",X="",ge=null,Z,pe,ee,me,we=null,he=null,ke=null;function Ne(){let $=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(zr(K,v?.headerBar),a){he=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",we=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),we.textContent="-- tok/s",ke=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ke.style.display="none",ke.style.pointerEvents="none";let xt=he,dn=ke,ra=()=>{if(!dn.textContent)return;let pn=xt.getBoundingClientRect(),it=$.getBoundingClientRect();dn.style.left=`${pn.left-it.left}px`,dn.style.top=`${pn.bottom-it.top+4}px`,dn.style.display="block"},oe=()=>{dn.style.display="none"};he.addEventListener("mouseenter",ra),he.addEventListener("mouseleave",oe),he.appendChild(we)}let ce=b("div","persona-flex-1");Z=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let je=b("option","");je.value="",je.textContent="All events (0)",Z.appendChild(je),pe=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),pe.type="button",pe.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&pe.appendChild(Pe);let Ve=b("span","persona-event-copy-all persona-text-xs");Ve.textContent="Copy All",pe.appendChild(Ve),he&&K.appendChild(he),K.appendChild(ce),K.appendChild(Z),K.appendChild(pe);let $e=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");zr($e,v?.searchBar);let Re=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),Ce=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Re&&Ce.appendChild(Re),ee=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),zr(ee,v?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",me=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),$e.appendChild(Ce),$e.appendChild(ee),$e.appendChild(me),$.appendChild(K),$.appendChild($e),ke&&$.appendChild(ke),$}let Ue,Qe=s.find($=>$.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Ue=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:K=>{B=K,Le(),Te()},onSearchChange:K=>{S=K,Le(),Te()}})??Ne():Ue=Ne();let Oe=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function _e(){if(!a||!we||!he)return;let $=a(),K=Bv($);we.textContent=K;let ce=Dv($);ke&&(ke.textContent=ce,ce||(ke.style.display="none")),he.setAttribute("aria-label",ce?`Throughput: ${K}, ${ce}`:`Throughput: ${K}`)}let Ae=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Se=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Se.style.height="100%";let ze=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");zr(ze,v?.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Gt=ae(d,"14px","currentColor",2);Gt&&ze.appendChild(Gt);let gt=b("span","");gt.textContent=c,ze.appendChild(gt);let Ht=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ht.style.display="none",Ae.appendChild(Se),Ae.appendChild(Ht),Ae.appendChild(ze),C.setAttribute("tabindex","0"),C.appendChild(Ue),C.appendChild(Oe),C.appendChild(Ae);function xn(){let $=t.getAll(),K={};for(let $e of $)K[$e.type]=(K[$e.type]||0)+1;let ce=Object.keys(K).sort(),je=ce.length!==P.length||!ce.every(($e,Re)=>$e===P[Re]),de=!je&&ce.some($e=>K[$e]!==H[$e]),Pe=$.length!==Object.values(H).reduce(($e,Re)=>$e+Re,0);if(!je&&!de&&!Pe||(P=ce,H=K,!Z))return;let Ve=Z.value;if(Z.options[0].textContent=`All events (${$.length})`,je){for(;Z.options.length>1;)Z.remove(1);for(let $e of ce){let Re=b("option","");Re.value=$e,Re.textContent=`${$e} (${K[$e]||0})`,Z.appendChild(Re)}Ve&&ce.includes(Ve)?Z.value=Ve:Ve&&(Z.value="",B="")}else for(let $e=1;$e<Z.options.length;$e++){let Re=Z.options[$e];Re.textContent=`${Re.value} (${K[Re.value]||0})`}}function Cn(){let $=t.getAll();if(B&&($=$.filter(K=>K.type===B)),S){let K=S.toLowerCase();$=$.filter(ce=>ce.type.toLowerCase().includes(K)||ce.payload.toLowerCase().includes(K))}return $}function et(){return B!==""||S!==""}function Le(){F=0,z=0,N.resume(),ze.style.display="none"}function ye($){ie.has($)?ie.delete($):ie.add($),ge=$;let K=Se.scrollTop,ce=N.isFollowing();G=!0,N.pause(),Te(),Se.scrollTop=K,ce&&N.resume(),G=!1}function tt(){return eo(Se,50)}function Te(){j=Date.now(),te=!1,_e(),xn();let $=t.getEvictedCount();$>0?(Oe.textContent=`${$.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",T=Cn();let K=T.length,ce=t.getSize()>0;K===0&&ce&&et()?(Ht.textContent=S?`No events matching '${S}'`:"No events matching filter",Ht.style.display="",Se.style.display="none"):(Ht.style.display="none",Se.style.display=""),pe&&(pe.title=et()?`Copy Filtered (${K})`:"Copy All"),u&&!N.isFollowing()&&K>F&&(z+=K-F,gt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",ze.style.display=""),F=K;let je=t.getAll(),de=je.length>0?je[0].timestamp:0,Pe=new Set(T.map(Re=>Re.id));for(let Re of ie)Pe.has(Re)||ie.delete(Re);let Ve=B!==ue||S!==X,$e=Y.size===0&&T.length>0;if(Ve||$e||T.length===0){Se.innerHTML="",Y.clear();let Re=document.createDocumentFragment();for(let Ce=0;Ce<T.length;Ce++){let nt=Mc(T[Ce],Ce,de,f,ie,ye,s,r);Y.set(T[Ce].id,nt),Re.appendChild(nt)}Se.appendChild(Re),ue=B,X=S,ge=null}else{if(ge!==null){let Ce=Y.get(ge);if(Ce&&Ce.parentNode===Se){let nt=T.findIndex(xt=>xt.id===ge);if(nt>=0){let xt=Mc(T[nt],nt,de,f,ie,ye,s,r);Se.insertBefore(xt,Ce),Ce.remove(),Y.set(ge,xt)}}ge=null}let Re=new Set(T.map(Ce=>Ce.id));for(let[Ce,nt]of Y)Re.has(Ce)||(nt.remove(),Y.delete(Ce));for(let Ce=0;Ce<T.length;Ce++){let nt=T[Ce];if(!Y.has(nt.id)){let xt=Mc(nt,Ce,de,f,ie,ye,s,r);Y.set(nt.id,xt),Se.appendChild(xt)}}}N.isFollowing()&&(Se.scrollTop=Se.scrollHeight)}function ve(){if(Date.now()-j>=kv){A!==null&&(cancelAnimationFrame(A),A=null),Te();return}te||(te=!0,A=requestAnimationFrame(()=>{A=null,Te()}))}let re=($,K)=>{if(!pe)return;pe.innerHTML="";let ce=ae($,"12px","currentColor",1.5);ce&&pe.appendChild(ce);let je=b("span","persona-text-xs");je.textContent="Copy All",pe.appendChild(je),setTimeout(()=>{pe.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&pe.appendChild(de);let Pe=b("span","persona-text-xs");Pe.textContent="Copy All",pe.appendChild(Pe),pe.disabled=!1},K)},xe=async()=>{if(pe){pe.disabled=!0;try{let $;et()?$=T:n?($=await n(),$.length===0&&($=t.getAll())):$=t.getAll();let K=$.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),re("check",1500)}catch{re("x",1500)}}},An=()=>{Z&&(B=Z.value,Le(),Te())},ne=()=>{!ee||!me||(me.style.display=ee.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{S=ee.value,Le(),Te()},150))},M=()=>{!ee||!me||(ee.value="",S="",me.style.display="none",k&&clearTimeout(k),Le(),Te())},I=()=>{if(G)return;let $=Se.scrollTop,{action:K,nextLastScrollTop:ce}=fi({following:N.isFollowing(),currentScrollTop:$,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,K==="resume"?(N.resume(),z=0,ze.style.display="none"):K==="pause"&&(N.pause(),u&&(gt.textContent=c,ze.style.display=""))},h=$=>{let K=gi({following:N.isFollowing(),deltaY:$.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});K==="pause"?(N.pause(),u&&(gt.textContent=c,ze.style.display="")):K==="resume"&&(N.resume(),z=0,ze.style.display="none")},W=()=>{u&&(Se.scrollTop=Se.scrollHeight,N.resume(),z=0,ze.style.display="none")},L=$=>{let K=$.target;if(!K||K.closest("button"))return;let ce=K.closest("[data-event-id]");if(!ce)return;let je=ce.getAttribute("data-event-id");je&&ye(je)},R=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),ee?.focus(),ee?.select();return}$.key==="Escape"&&(ee&&document.activeElement===ee?(M(),ee.blur(),C.focus()):o&&o())};pe&&pe.addEventListener("click",xe),Z&&Z.addEventListener("change",An),ee&&ee.addEventListener("input",ne),me&&me.addEventListener("click",M),Se.addEventListener("scroll",I),Se.addEventListener("wheel",h,{passive:!0}),Se.addEventListener("click",L),ze.addEventListener("click",W),C.addEventListener("keydown",R);function q(){k&&clearTimeout(k),A!==null&&(cancelAnimationFrame(A),A=null),te=!1,Y.clear(),pe&&pe.removeEventListener("click",xe),Z&&Z.removeEventListener("change",An),ee&&ee.removeEventListener("input",ne),me&&me.removeEventListener("click",M),Se.removeEventListener("scroll",I),Se.removeEventListener("wheel",h),Se.removeEventListener("click",L),ze.removeEventListener("click",W),C.removeEventListener("keydown",R)}return{element:C,update:ve,destroy:q}}}function Jf(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},u=f=>{let w=f;return s.findIndex(g=>g===w||g.contains(w))},d=f=>{let w=u(f.target);if(w<0)return;let g=w;if(f.key===r)g=Math.min(w+1,s.length-1);else if(f.key===o)g=Math.max(w-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==w&&t.onSelect(g)},c=f=>{let w=u(f.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(f,w){if(s=f,f.forEach((g,v)=>{g.setAttribute("role","tab");let C=v===w;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||w<0&&v===0?0:-1}),a){let g=(w>=0?f[w]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Zf(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),u=n?.tabFadeSize?.trim(),d=ne=>({start:ne===!1?!1:typeof ne=="object"&&ne?ne.start!==!1:!0,end:ne===!1?!1:typeof ne=="object"&&ne?ne.end!==!1:!0}),{start:c,end:f}=d(n?.tabFade),w=typeof document<"u"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),G?.hide()};w&&w.addEventListener("click",()=>{g(),t.onDismiss?.()});let v=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let T=b("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let B=Wt({icon:"x",label:a});B.addEventListener("click",()=>{g(),t.onDismiss?.()});let S="rendered",k=ii({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ne=>{S=ne==="source"?"source":"rendered",re()}}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=n?.documentToolbarShowCopyLabel===!0,F=n?.documentToolbarShowCopyChevron===!0,N=n?.documentToolbarCopyMenuItems,z=!!(F&&N&&N.length>0),j=null,te,A=null,G=null;if(r&&(H||F)&&!z){if(te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F){let ne=ae("chevron-down",14,"currentColor",2);ne&&te.appendChild(ne)}}else r&&z?(j=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=Wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),j.append(te,A)):r?te=Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(te=Wt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&te.classList.add("persona-hidden"));let Q=r?Wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wt({icon:"refresh-cw",label:"Refresh"}),ie=r?Wt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Wt({icon:"x",label:a}),Y=Wt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Y.classList.add("persona-hidden");let ue=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),X=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ne=Ae.find(W=>W.id===Se)??Ae[Ae.length-1],M=ne?.id??null,I=ne?.artifactType==="markdown"?ne.markdown??"":"",h=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:I,jsonPayload:h,id:M}},Z=async()=>{let ne=Ae.find(M=>M.id===Se)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(Ns(ne))}catch{}};if(te.addEventListener("click",async()=>{let ne=n?.onDocumentToolbarCopyMenuSelect;if(ne&&z){let{markdown:M,jsonPayload:I,id:h}=ge();try{await ne({actionId:"primary",artifactId:h,markdown:M,jsonPayload:I})}catch{}return}await Z()}),A&&N?.length){let ne=()=>v.closest("[data-persona-root]")??document.body,M=()=>{G=Dr({items:N.map(I=>({id:I.id,label:I.label})),onSelect:async I=>{let{markdown:h,jsonPayload:W,id:L}=ge(),R=n?.onDocumentToolbarCopyMenuSelect;try{R?await R({actionId:I,artifactId:L,markdown:h,jsonPayload:W}):I==="markdown"||I==="md"?await navigator.clipboard.writeText(h):I==="json"||I==="source"?await navigator.clipboard.writeText(W):await navigator.clipboard.writeText(h||W)}catch{}},anchor:j??A,position:"bottom-right",portal:ne()})};v.isConnected?M():requestAnimationFrame(M),A.addEventListener("click",I=>{I.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),ie.addEventListener("click",()=>{g(),t.onDismiss?.()});let pe=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),j?P.append(j,Q,ie):P.append(te,Q,ie),P.insertBefore(ue,ie),P.insertBefore(Y,ie),C.append(k.element,pe,P);else{let ne=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ne.append(te,ue,Y,B),C.appendChild(T),C.appendChild(ne)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ee=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");u&&ee.style.setProperty("--persona-artifact-tab-fade-size",u);let me=e.features?.artifacts?.renderTabBar,we=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=Jf(ee,{onSelect:ne=>t.onSelect(Ae[ne].id)}),ke=ne=>{let M=ne.scrollWidth-ne.clientWidth,I=M>1,h=Math.abs(ne.scrollLeft);ne.classList.toggle("persona-artifact-tab-fade-start",c&&I&&h>1),ne.classList.toggle("persona-artifact-tab-fade-end",f&&I&&h<M-1)},Ne=0,Ue=()=>{if(Ne)return;let ne=()=>{Ne=0,ke(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ne):setTimeout(ne,0)};ee.addEventListener("scroll",()=>Ue(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(ee)).observe(ee);let Qe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Oe=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Oe):setTimeout(Oe,0)};if(l){for(let ne of[ee,we])ne.style.paddingLeft=l,ne.style.paddingRight=l;Qe.style.padding=l}v.appendChild(C),v.appendChild(ee),v.appendChild(we),v.appendChild(Qe);let Ae=[],Se=null,ze=!1,Gt=!1,gt=!0,Ht=!1,xn=null,Cn="",et=null,Le=!1,ye=ne=>ne.artifactType==="markdown"&&!!ne.file||r?S:"rendered",tt=ne=>{r||(ne&&!Le?(C.insertBefore(k.element,T),Le=!0):!ne&&Le&&(k.element.remove(),Le=!1))},Te=()=>Se&&Ae.find(ne=>ne.id===Se)||Ae[Ae.length-1],ve=()=>{let ne=Fs(Te());if(!ne){ue.replaceChildren();return}let M=X.filter(I=>I.visible===void 0||I.visible(ne)).map(I=>Fr(I,{documentChrome:r,onClick:()=>{let h=Fs(Te());if(h)try{Promise.resolve(I.onClick(h)).catch(()=>{})}catch{}}}));ue.replaceChildren(...M)},re=()=>{ve();let ne=r&&Ae.length<=1,M=!!me;if(ee.classList.toggle("persona-hidden",ne||M),we.classList.toggle("persona-hidden",ne||!M),M&&me){let W=Ae.map(L=>L.id).join("|")+" "+(Se??"");if(W!==Cn){Cn=W;let L=me({records:Ae,selectedId:Se,onSelect:t.onSelect});we.firstElementChild!==L&&we.replaceChildren(L)}}else{he.beforeRender(),ee.replaceChildren();let W=[],L=-1;for(let[R,q]of Ae.entries()){let $=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");$.type="button";let K=q.artifactType==="markdown"?q.file:void 0,ce=K?Bn(K.path):q.title||q.id.slice(0,8),je=K?.path||q.title||ce;$.textContent=ce,$.title=je,$.setAttribute("aria-label",je),q.id===Se&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=R),$.addEventListener("click",()=>t.onSelect(q.id)),ee.appendChild($),W.push($)}if(he.render(W,L),L>=0&&Se!==xn){xn=Se;let R=W[L];typeof R.scrollIntoView=="function"&&R.scrollIntoView({block:"nearest",inline:"nearest"})}ke(ee)}let I=Se&&Ae.find(W=>W.id===Se)||Ae[Ae.length-1];if(!I){Qe.replaceChildren(),et=null,tt(!1);return}let h=I.artifactType==="markdown"?I.file:void 0;if(tt(!!h&&Yo(h)!=="other"),r){let W=h?Co(h):I.artifactType==="markdown"?"MD":I.component??"Component",L=(I.title||"Document").trim(),R=h?Bn(h.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${R} \xB7 ${W}`}else T.textContent=h?Bn(h.path):s;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(I)):(et=di(I,{config:e,resolveViewMode:ye}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ne=Ae.length>0;if(v.classList.toggle("persona-hidden",!ne),w){let h=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ne&&h&&ze?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},An=()=>{Ht=!1,re(),xe()};return{element:v,backdrop:w,update(ne){let M=ne.selectedId??ne.artifacts[ne.artifacts.length-1]?.id??null,I=M!==Se;Ae=ne.artifacts,Se=M,Ae.length>0&&(ze=!0),Ht=!0,gt&&An(),I&&Oe()},setMobileOpen(ne){ze=ne,!ne&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ne){ne!==Gt&&(Gt=ne,_e());let M=ae(ne?"minimize":"maximize",16,"currentColor",2);M&&Y.replaceChildren(M);let I=ne?"Collapse artifacts panel":"Expand artifacts panel";Y.setAttribute("aria-label",I),Y.title=I},setExpandToggleVisible(ne){Y.classList.toggle("persona-hidden",!ne)},setCopyButtonVisible(ne){r||te.classList.toggle("persona-hidden",!ne)},setCustomActions(ne){X=ne,ve()},setTabFade(ne){let M=d(ne);M.start===c&&M.end===f||(c=M.start,f=M.end,ke(ee))},setRenderTabBar(ne){ne!==me&&(me=ne,Cn="",re())},setVisible(ne){ne!==gt&&(gt=ne,ne&&Ht&&An())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function eg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Ov(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var tg=["panel","seamless","detached"];function Ec(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&tg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function kc(e){return!e||!Jt(e)?!1:Ec(e)==="detached"}function ea(e,t){if(!Jt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Ov(e),eg(e,t);return}let n=t.features?.artifacts?.layout,o=Ec(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let u=n?.documentToolbarToggleActiveBorderColor?.trim();u?e.style.setProperty("--persona-artifact-doc-toggle-active-border",u):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),eg(e,t)}function ta(e,t){for(let l of tg)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=Ec(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ng(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Nv=new Set(["__proto__","prototype","constructor"]),_v=new Set(["collapsed","card","panel","inline"]),og=new Set(["markdown","component"]),$v=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Di=e=>!Nv.has(e),Lc=e=>typeof e=="string"&&_v.has(e),rr=e=>Object.keys(e).length>0;function Fn(e,t,n,o){e.push({path:t,code:n,message:o})}var Uv="Ignored because this key is not part of the persisted preference schema.",Bi="Ignored an unsupported value.",zv="Expected collapsed, panel, or inline.",jv='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',rg={kind:"mode",message:Bi},jr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},Vv={paneWidth:jr,paneMaxWidth:jr,paneMinWidth:jr,expandedPanelWidth:jr,resizableMinWidth:jr,resizableMaxWidth:jr,expandLauncherPanelWhenOpen:to,resizable:to},qv={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Bi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Bi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Bi},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:rg,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:rg,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:og,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:og}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:Vv}}}}};function sg(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Fn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Fn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Fn(o,n,"invalid_value",t.message);case"mode":return Lc(e)?yn(e):Fn(o,n,"invalid_value",t.message);case"modeMap":{if(!or(e))return Fn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let u=r?a:Ar(a);Di(a)&&(r?r.has(a):$v.test(u))?Lc(l)?s[u]=yn(l):Fn(o,`${n}.${a}`,"invalid_value",zv):Fn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":jv)}return rr(s)?s:void 0}case"object":{if(t.bareMode&&Lc(e))return yn(e);if(!or(e))return Fn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Di(l)||!r.includes(l))&&Fn(o,s(l),"unknown_key",Uv);let a={};for(let l of r){let u=t.children[l],d=sg(e[l],u,s(l),o);if(u.deprecated&&e[l]!==void 0&&Fn(o,s(l),"deprecated_key",u.deprecated),d===void 0)continue;let c=u.alias??l,f=a[c];a[c]=or(f)&&or(d)?{...f,...d}:d}return rr(a)?a:void 0}}}function Kv(e){let t=[];return{preferences:(e===null?void 0:sg(e,qv,"",t))??{},issues:t}}function Vr(e){if(Array.isArray(e))return e.map(Vr);if(!or(e))return e;let t={};for(let[n,o]of Object.entries(e))Di(n)&&o!==void 0&&(t[n]=Vr(o));return t}function ag(e,t){let n=Vr(e);for(let[o,r]of Object.entries(t)){if(!Di(o)||r===void 0)continue;let s=n[o];n[o]=or(s)&&or(r)?ag(s,r):Vr(r)}return n}function Gv(e){let t={},n;for(let r of e){let s=Kv(r).preferences;n=ig(n,s.artifacts?.display),t=ag(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Yv(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...rr(r)?{byMediaType:r}:{}};return rr(s)?s:void 0}function ig(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Yv(n.files,t.files),a={...o?{default:o}:{},...rr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return rr(a)?a:void 0}function Xv(e={},t){let n=Gv(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=ig(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Pc(e){let t=e.preferences;return!t||!rr(t)?e:{...e,features:Xv(e.features??{},[t])}}function Qv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Jv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Zv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ew(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ic(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function lg(e,t,n,o,r,s){let a=Qv(r,200),l=ew(t,n,o,200);l=Math.max(a,l);let u=Jv(s);return u!==null&&(l=Math.min(l,u)),Zv(e,a,l)}var cg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Wc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=cg[a]??cg.init;s.classList.add("persona-form-card","persona-space-y-4");let u=b("div","persona-space-y-1"),d=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,u.appendChild(d),l.description){let v=b("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,u.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${v.name}`;let T=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=v.label,C.appendChild(T);let B=v.type??"text",S;B==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=B),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${a}-${v.name}`,S.name=v.name,S.placeholder=v.placeholder??"",v.required&&(S.required=!0),C.appendChild(S),c.appendChild(C)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(w),f.appendChild(g),c.appendChild(f),s.replaceChildren(u,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",T=new FormData(c),B={};T.forEach((S,k)=>{B[k]=S}),B.type=a,g.disabled=!0,w.textContent="Submitting\u2026";try{let S=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let k=await S.json();w.textContent=k.message??"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(S){w.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Rc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Hc=new Rc;var dg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tw=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),pg=(e,t,n)=>{if(!dg(e)||!dg(t)||tw.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=pg(e[r],t[r],s)}return o};function ug(e,t){let n=pg(e,t,"");return ei(n)}var fg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var nw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ow=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Dc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=nw(e),n=ow(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Bc=e=>typeof e=="string"?e:e==null?"":String(e),na={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Bc(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Bc(n.text)}}},gg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fc=e=>{let t=new Set(gg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let u={action:l,message:s.message};e.emit("action:detected",u);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",u)},f=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var rw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},sw=e=>e.map(t=>({...t,streaming:!1})),aw=e=>e.map(t=>({...t,status:"complete"})),mg=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?rw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?sw(n.messages):void 0,artifacts:n.artifacts?aw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as rM,STR as sM,OBJ as aM}from"partial-json";function hg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function yg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Oc(e){let t=yg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function bg(e){let t=yg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vg(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,ratingLabels:d=iw}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let f=null,w=document.createElement("div");w.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,g.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),w.appendChild(g);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let F=1;F<=5;F++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${F} star${F>1?"s":""}: ${d[F-1]}`),N.title=d[F-1],N.dataset.rating=String(F),N.innerHTML=`
|
|
43
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
44
44
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
45
45
|
</svg>
|
|
46
|
-
`,A.addEventListener("click",()=>{u=j,F.forEach((V,K)=>{let ne=K<j;V.classList.toggle("selected",ne),V.setAttribute("aria-checked",K===j-1?"true":"false")})}),F.push(A),P.appendChild(A)}w.appendChild(P);let k=null;if(p){let j=document.createElement("div");j.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),j.appendChild(k),w.appendChild(j)}let T=document.createElement("div");T.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=l,M.addEventListener("click",()=>{n?.(),c.remove()});let U=document.createElement("button");return U.type="button",U.className="persona-feedback-btn persona-feedback-btn-submit",U.textContent=a,U.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let j=k?.value.trim()||void 0;await t(u,j),c.remove()}catch(j){U.disabled=!1,U.textContent=a,console.error("[CSAT Feedback] Failed to submit:",j)}}),T.appendChild(M),T.appendChild(U),w.appendChild(T),c.appendChild(w),c}function pf(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,v.appendChild(x);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=r,v.appendChild(P),g.appendChild(v);let F=document.createElement("div");F.className="persona-feedback-rating persona-feedback-rating-nps",F.setAttribute("role","radiogroup"),F.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let T=document.createElement("span");T.className="persona-feedback-label-low",T.textContent=d;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=c,k.appendChild(T),k.appendChild(M);let U=document.createElement("div");U.className="persona-feedback-numbers";let j=[];for(let D=0;D<=10;D++){let _=document.createElement("button");_.type="button",_.className="persona-feedback-rating-btn persona-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${D} out of 10`),_.textContent=String(D),_.dataset.rating=String(D),D<=6?_.classList.add("persona-feedback-detractor"):D<=8?_.classList.add("persona-feedback-passive"):_.classList.add("persona-feedback-promoter"),_.addEventListener("click",()=>{w=D,j.forEach((Y,ge)=>{Y.classList.toggle("selected",ge===D),Y.setAttribute("aria-checked",ge===D?"true":"false")})}),j.push(_),U.appendChild(_)}F.appendChild(k),F.appendChild(U),g.appendChild(F);let A=null;if(p){let D=document.createElement("div");D.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),D.appendChild(A),g.appendChild(D)}let V=document.createElement("div");V.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=l,K.addEventListener("click",()=>{n?.(),u.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=a,ne.addEventListener("click",async()=>{if(w===null){U.classList.add("persona-feedback-shake"),setTimeout(()=>U.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let D=A?.value.trim()||void 0;await t(w,D),u.remove()}catch(D){ne.disabled=!1,ne.textContent=a,console.error("[NPS Feedback] Failed to submit:",D)}}),V.appendChild(K),V.appendChild(ne),g.appendChild(V),u.appendChild(g),u}var Tr="persona-chat-history",Ib=30*1e3,Rb=641,Wb={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Hb(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=Wb[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function hi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Bb(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Db(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Jl=e=>!e||typeof e!="object"?{}:{...e},uf=e=>e.map(t=>({...t,streaming:!1})),ff=(e,t,n)=>{let o=e?.markdown?ma(e.markdown):null,r=ha(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=_n()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Dd(a):a,u=o(c);d=r&&p?r(u):u}else d=ao(a);return d}};function gf(e){let t=y("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=y("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var Fb=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Nb=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Fb(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),mf=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=Ha(t),r=o.features;o=Ul(o);let s=ql.getForInstance(o.plugins),{plugin:a,teardown:l}=Fu();o.components&&Vn.registerAll(o.components);let p=of(),c=o.persistState===!1?null:o.storageAdapter??sf(),u={},w=null,g=!1,v=i=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(i);if(f&&typeof f=="object"&&"state"in f){let{state:m,open:b}=f;return b&&(g=!0),m}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return i};if(c?.load)try{let i=c.load();if(i&&typeof i.then=="function")w=i.then(f=>v(f??{messages:[],metadata:{}}));else{let m=v(i??{messages:[],metadata:{}});m.metadata&&(u=Jl(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=v({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let x=()=>u,P=i=>{u=i({...u})??{},Pi()},F=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gl],k=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick],T=Ql({parsers:F,handlers:k,getSessionMetadata:x,updateSessionMetadata:P,emit:p.emit,documentRef:typeof document<"u"?document:null});T.syncFromMetadata();let M=o.launcher?.enabled??!0,U=o.launcher?.autoExpand??!1,j=o.autoFocusInput??!1,A=U,V=M,K=o.layout?.header?.layout,ne=!1,D=()=>Es(o),_=()=>M||D(),Y=D()?!1:M?U:!0,ge=!1,he=null,ce=()=>{ge=!0,he&&clearTimeout(he),he=setTimeout(()=>{ge&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ge=!1)},1e4)},Z=ff(o,T,ce),de=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,ie=o.features?.showEventStreamToggle??!1,J=o.features?.scrollToBottom??{},fe=o.features?.scrollBehavior??{},ye=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,xe=ie?new Is(ye):null,ve=o.features?.eventStream?.maxEvents??2e3,Ae=ie?new Ps(ve,xe):null,Te=ie?new Rs:null,qe=null,ze=!1,Me=null,Pe=0;xe?.open().then(()=>Ae?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ke={onCopy:i=>{p.emit("message:copy",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),N?.isClientTokenMode()&&N.submitMessageFeedback(i.messageId,i.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(i)}},Wt=o.statusIndicator??{},It=i=>i==="idle"?Wt.idleText??Lt.idle:i==="connecting"?Wt.connectingText??Lt.connecting:i==="connected"?Wt.connectedText??Lt.connected:i==="error"?Wt.errorText??Lt.error:i==="paused"?Wt.pausedText??Lt.paused:i==="resuming"?Wt.resumingText??Lt.resuming:Lt[i];function qt(i,f,m,b){if(b==="idle"&&m.idleLink){i.textContent="";let S=document.createElement("a");S.href=m.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=f,S.style.color="inherit",S.style.textDecoration="none",i.appendChild(S)}else i.textContent=f}let xt=Tu({config:o,showClose:_()}),{wrapper:Be,panel:ue,pillRoot:Xe}=xt.shell,We=xt.panelElements,{container:me,body:le,messagesWrapper:Re,starterSuggestions:Kt,transcriptSuggestions:pt,suggestions:mt,textarea:z,sendButton:C,sendButtonWrapper:$,composerForm:h,statusText:L,introTitle:I,introSubtitle:H,closeButton:B,iconHolder:R,headerTitle:Q,headerSubtitle:se,header:Ee,footer:we,actionsRow:nt,rightActions:tt}=We,_e=We.leftActions,Je=We.setSendButtonMode,q=We.micButton,$e=We.micButtonWrapper,De=We.attachmentButton,Ht=We.attachmentButtonWrapper,vt=We.attachmentInput,Gt=We.attachmentPreviewsContainer;me.classList.add("persona-relative"),le.classList.add("persona-relative");let Fs=12,Kn=()=>J.label??"",Ef=()=>J.iconName??"arrow-down",kf=()=>J.enabled!==!1,ln=()=>fe.mode??"anchor-top",Gn=()=>ln()==="follow"||ln()==="anchor-top"&&Or,rc=()=>fe.anchorTopOffset??16,Lf=()=>fe.restorePosition??"bottom",sc=()=>fe.pauseOnInteraction===!0,ac=()=>fe.showActivityWhilePinned!==!1,ic=()=>fe.announce===!0,Tt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Tt.type="button",Tt.style.display="none",Tt.setAttribute("data-persona-scroll-to-bottom","true");let Er=y("span","persona-flex persona-items-center"),bi=y("span",""),bo=y("span","");bo.setAttribute("data-persona-scroll-to-bottom-count",""),bo.style.display="none",Tt.append(Er,bi,bo),me.appendChild(Tt);let Qn=y("div","persona-stream-anchor-spacer");Qn.setAttribute("aria-hidden","true"),Qn.setAttribute("data-persona-anchor-spacer",""),Qn.style.flexShrink="0",Qn.style.pointerEvents="none",Qn.style.height="0px",le.appendChild(Qn);let vo=y("div","persona-sr-only");vo.setAttribute("aria-live","polite"),vo.setAttribute("aria-atomic","true"),vo.setAttribute("role","status"),vo.setAttribute("data-persona-live-region",""),Object.assign(vo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),me.appendChild(vo);let kr=null,Ns=null,lc=i=>{!ic()||!i||(Ns=i,kr===null&&(kr=setTimeout(()=>{kr=null,Ns&&ic()&&(vo.textContent=Ns),Ns=null},400)))},jo=()=>{let f=we.style.display==="none"?0:we.offsetHeight;Tt.style.bottom=`${f+Fs}px`};jo();let cc=()=>{let i=!!Kn();Tt.setAttribute("aria-label",Kn()||"Jump to latest"),Tt.title=Kn(),Tt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Er.innerHTML="";let f=ae(Ef(),"14px","currentColor",2);f?(Er.appendChild(f),Er.style.display=""):Er.style.display="none",bi.textContent=Kn(),bi.style.display=i?"":"none"};cc();let Ct=null,tn=null,dc=null,pc=s.find(i=>i.renderHeader);if(pc?.renderHeader){let i=pc.renderHeader({config:o,defaultRenderer:()=>{let f=No({config:o,showClose:_()});return ks(me,f,o),f.header},onClose:()=>it(!1,"user")});if(i){let f=me.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(i),Ee=i,xt.header.element=i)}}let vi=()=>{if(!Ae)return;if(ze=!0,!qe&&Ae&&(qe=$u({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>Lr(),config:o,plugins:s,getThroughput:()=>Te?.getMetric()??{status:"idle"}})),qe&&(le.style.display="none",we.parentNode?.insertBefore(qe.element,we),qe.update()),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(m=>m&&Ye.classList.add(m))}let i=()=>{if(!ze)return;let f=Date.now();f-Pe>=200&&(qe?.update(),Pe=f),Me=requestAnimationFrame(i)};Pe=0,Me=requestAnimationFrame(i),on(),p.emit("eventStream:opened",{timestamp:Date.now()})},Lr=()=>{if(ze){if(ze=!1,qe&&qe.element.remove(),le.style.display="",Ye){Ye.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(f=>f&&Ye.classList.remove(f))}Me!==null&&(cancelAnimationFrame(Me),Me=null),on(),p.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(ie){let i=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Ye=y("button",f),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Jt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&Ye.appendChild(m);let b=We.clearChatButtonWrapper,S=We.closeButtonWrapper,E=b||S;E&&E.parentNode===Ee?Ee.insertBefore(Ye,E):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{ze?Lr():vi()})}let Pf=i=>{let f=o.attachments;if(!f?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let S=i.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(m,S):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let S=y("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(f.allowedTypes??zn).join(","),S.multiple=(f.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),i.appendChild(S)}},uc=s.find(i=>i.renderComposer);if(uc?.renderComposer){let i=o.composer,f=uc.renderComposer({config:o,defaultRenderer:()=>ci({config:o}).footer,onSubmit:m=>{if(!N||N.isStreaming())return;let b=m.trim(),S=Ct?.hasAttachments()??!1;if(!b&&!S)return;ed();let E;S&&(E=[],E.push(...Ct.getContentParts()),b&&E.push(dr(b))),N.sendMessage(b,{contentParts:E}),S&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{vt?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{dc?.()}:void 0});f&&(xt.replaceComposer(f),we=xt.composer.footer)}let If=i=>{let f=(...pe)=>{for(let re of pe){let be=i.querySelector(re);if(be)return be}return null},m=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),S=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),X=i.querySelector("[data-persona-composer-status]");m&&(h=m),b&&(z=b),S&&(C=S),E&&(q=E,$e=E.parentElement),X&&(L=X);let O=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(mt=O);let G=f("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(De=G,Ht=G.parentElement),vt=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Gt=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ee=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ee&&(nt=ee),_e=f(".persona-widget-composer__left-actions")};Pf(we),If(we);let Tn=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Tn&&(Re.style.maxWidth=Tn,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",Kt.style.maxWidth=Tn,pt.style.maxWidth=Tn,pt.style.marginLeft="auto",pt.style.marginRight="auto",pt.style.width="100%"),Tn&&h&&!D()&&(h.style.maxWidth=Tn,h.style.marginLeft="auto",h.style.marginRight="auto"),Tn&&mt&&!D()&&(mt.style.maxWidth=Tn,mt.style.marginLeft="auto",mt.style.marginRight="auto"),Tn&&Gt&&!D()&&(Gt.style.maxWidth=Tn,Gt.style.marginLeft="auto",Gt.style.marginRight="auto"),o.attachments?.enabled&&vt&&Gt){Ct=gs.fromConfig(o.attachments),Ct.setPreviewsContainer(Gt),vt.addEventListener("change",m=>{let b=m.target;Ct?.handleFileSelect(b.files),b.value=""});let i=o.attachments.dropOverlay,f=gf(i);me.appendChild(f)}let Rf=()=>tn?.prefetch();if(o.contextMentions?.enabled&&z&&(tn=Ip({config:o,textarea:z,anchor:h??z,getMessages:()=>N.getMessages(),liveRegionHost:me}),tn)){let i=z;i.parentElement?.insertBefore(tn.contextRow,i);let f=tn.affordanceButtons;for(let m=f.length-1;m>=0;m--){let b=f[m];_e?_e.insertBefore(b,_e.firstChild):h?.appendChild(b)}}(()=>{let i=o.layout?.slots??{},f=b=>{switch(b){case"body-top":return me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Re;case"footer-top":return mt;case"composer":return h;case"footer-bottom":return L;default:return null}},m=(b,S)=>{switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")Ee.insertBefore(S,Ee.firstChild);else if(b==="header-right")Ee.appendChild(S);else{let E=Ee.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(S,E.nextSibling):Ee.appendChild(S)}break;case"body-top":{let E=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");E?E.replaceWith(S):le.insertBefore(S,le.firstChild);break}case"body-bottom":le.appendChild(S);break;case"footer-top":mt.replaceWith(S);break;case"footer-bottom":L.replaceWith(S);break;default:break}};for(let[b,S]of Object.entries(i))if(S)try{let E=S({config:o,defaultContent:()=>f(b)});E&&m(b,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,E)}})();let fc=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let b=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let E=m.getAttribute("data-bubble-type");if(E==="reasoning")wr.has(S)?wr.delete(S):wr.add(S),Pu(S,b);else if(E==="tool")xr.has(S)?xr.delete(S):xr.add(S),Iu(S,b,o);else if(E==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Oo.get(S)??O;Oo.set(S,!G),Bu(S,b,o)}So.delete(S)};Re.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),fc(i))}),Re.addEventListener("keydown",i=>{let f=i.target;(i.key==="Enter"||i.key===" ")&&f.closest('button[data-expand-header="true"]')&&(i.preventDefault(),fc(i))}),Re.addEventListener("copy",i=>{let{clipboardData:f}=i;if(!f)return;let m=Re.getRootNode(),b=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),E=su(S);!E||E===S||(f.setData("text/plain",E),i.preventDefault())});let wi=new Map,gc=null,mc="idle",Wf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Hf=(i,f)=>{let{icon:m,label:b}=Wf[f];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",f==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",f!=="idle"),i.classList.toggle("persona-message-action-loading",f==="loading");let S=ae(m,14,"currentColor",2);S&&(i.innerHTML="",i.appendChild(S))},hc=()=>{Re.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let b=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Hf(f,b&&b===gc?mc:"idle")})};Re.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let E=m.getAttribute("data-action");if(E==="copy"){let O=N.getMessages().find(G=>G.id===S);if(O&&Ke.onCopy){let G=O.content||"";navigator.clipboard.writeText(G).then(()=>{m.classList.add("persona-message-action-success");let ee=ae("check",14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let pe=ae("copy",14,"currentColor",2);pe&&(m.innerHTML="",m.appendChild(pe))},2e3)}).catch(ee=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ee)}),Ke.onCopy(O)}}else if(E==="read-aloud")N.toggleReadAloud(S);else if(E==="upvote"||E==="downvote"){let O=(wi.get(S)??null)===E,G=E==="upvote"?"thumbs-up":"thumbs-down";if(O){wi.delete(S),m.classList.remove("persona-message-action-active");let ee=ae(G,14,"currentColor",2);ee&&(m.innerHTML="",m.appendChild(ee))}else{let ee=E==="upvote"?"downvote":"upvote",pe=b.querySelector(`[data-action="${ee}"]`);if(pe){pe.classList.remove("persona-message-action-active");let Ze=ae(ee==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ze&&(pe.innerHTML="",pe.appendChild(Ze))}wi.set(S,E),m.classList.add("persona-message-action-active");let re=ae(G,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(re)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ue=N.getMessages().find(lt=>lt.id===S);Ue&&Ke.onFeedback&&Ke.onFeedback({type:E,messageId:Ue.id,message:Ue})}}}),Re.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let E=m.getAttribute("data-approval-action");if(!E)return;let X=E==="approve"?"approved":"denied",G=N.getMessages().find(pe=>pe.id===S);if(!G?.approval)return;let ee=b.querySelector("[data-approval-buttons]");ee&&ee.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?N.resolveWebMcpApproval(S,X):N.resolveApproval(G.approval,X)});let Ge=null,Pr=null,Ir=()=>{},Rr="none",Os=null,yn={artifacts:[],selectedId:null},Rn=!1,bn=!1,Wr=!1,Vo=!1,yc=()=>Vo||yn.artifacts.some(i=>io(o.features?.artifacts,i)==="panel"),_s=()=>yn.artifacts.length>0&&!Rn&&yc(),st={current:null},xi=(i,f)=>{let m=N.getArtifactById(f),b=m?.markdown,S=m?.title||"artifact",E=m?.file,X=m?.artifactType??"markdown";if(!b){let ee=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ee){let re=N.getMessages().find(be=>be.id===ee);if(re?.rawContent)try{let be=JSON.parse(re.rawContent);b=be?.props?.markdown,S=be?.props?.title||S,be?.props?.file&&typeof be.props.file=="object"&&(E=be.props.file),!m&&typeof be?.props?.artifactType=="string"&&(X=be.props.artifactType)}catch{}}}return{markdown:b,title:S,file:E,artifactType:X}};Re.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-download-artifact");if(!b||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:b})===!0)return;let{markdown:E,title:X,file:O}=xi(m,b);if(!E)return;let{filename:G,mime:ee,content:pe}=$p({title:X,markdown:E,file:O}),re=new Blob([pe],{type:ee}),be=URL.createObjectURL(re),Ue=document.createElement("a");Ue.href=be,Ue.download=G,Ue.click(),URL.revokeObjectURL(be)}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-artifact-custom-action");if(!b)return;let S=m.closest("[data-artifact-inline]"),E=S?null:m.closest("[data-open-artifact]"),X=S?S.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,G=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(lt=>lt.id===b);if(!G)return;let{markdown:ee,title:pe,file:re,artifactType:be}=xi(m,X??""),Ue={artifactId:X,title:pe,artifactType:be,markdown:ee,file:re};try{Promise.resolve(G.onClick(Ue)).catch(()=>{})}catch{}}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-copy-artifact");if(!b)return;let S=N.getArtifactById(b),E="";if(S)E=xs(S);else{let{markdown:X,file:O,artifactType:G}=xi(m,b);G==="markdown"&&(E=xs({id:b,artifactType:"markdown",status:"complete",markdown:X??"",...O?{file:O}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let X=ae("check",16,"currentColor",2);X&&(m.replaceChildren(X),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&m.replaceChildren(O)},1500))}).catch(()=>{})}),Re.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let b=m.getAttribute("data-expand-artifact-inline");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(Rn=!1,Vo=!0,bn=!0,Wr=!0,N.selectArtifact(b),Wn())}),Re.addEventListener("click",i=>{let f=i.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let m=f.closest("[data-open-artifact]");if(!m)return;let b=m.getAttribute("data-open-artifact");!b||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:b})===!0||(i.preventDefault(),i.stopPropagation(),Rn=!1,Vo=!0,N.selectArtifact(b),Wn())}),Re.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let f=i.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),f.click())});let qo=We.composerOverlay,Ko=(i,f,m)=>{let b=f.trim();if(!b||!st.current)return;let S=i.getAttribute("data-tool-call-id")??"",E=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:m.structured,values:m.values??(m.source==="multi"?b.split(", "):[b]),isFreeText:E,source:m.source},bubbles:!0,composed:!0})),lr(qo,S);let X=st.current.getMessages().find(O=>O.toolCall?.id===S);X?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(X,m.structured??b):st.current.sendMessage(b)},wo=i=>{let f=st.current;if(!f)return;let m=i.getAttribute("data-tool-call-id")??"",b=f.getMessages().find(S=>S.toolCall?.id===m);b&&f.persistAskUserQuestionProgress(b,{answers:va(i,b),currentIndex:mn(i)})},bc=i=>Object.entries(i).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),Ci=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=mn(i),m=ir(i);if(f>=m-1)return;let b=st.current?.getMessages().find(S=>S.toolCall?.id===i.getAttribute("data-tool-call-id"));b&&(xa(i,b,o,f+1),wo(i))};qo.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),S==="dismiss"){let E=b.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),lr(qo,E);let X=st.current?.getMessages().find(O=>O.toolCall?.id===E);X?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(X),st.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(S==="pick"){let E=m.getAttribute("data-option-label");if(!E)return;let X=b.getAttribute("data-multi-select")==="true",O=lo(b);if(O&&X){let G=Ho(b)[mn(b)],ee=new Set(Array.isArray(G)?G:[]);ee.has(E)?ee.delete(E):ee.add(E),co(b,Array.from(ee)),wo(b);return}if(O){co(b,E),wo(b),Ci(b);return}if(X){let G=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",G?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!G);let ee=b.querySelector('[data-ask-user-action="submit-multi"]');ee&&(ee.disabled=nl(b).length===0);return}Ko(b,E,{source:"pick",values:[E]});return}if(S==="submit-multi"){let E=nl(b);if(E.length===0)return;Ko(b,E.join(", "),{source:"multi",values:E});return}if(S==="open-free-text"){let E=b.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){b.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let X=b.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(lo(b)){co(b,X.trim()),wo(b),Ci(b);return}Ko(b,X,{source:"free-text"});return}if(S==="next"||S==="back"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(re=>re.toolCall?.id===E);if(!X)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let re=Ho(b)[mn(b)];(typeof re!="string"||re!==G)&&co(b,G)}let ee=S==="next"?1:-1,pe=mn(b)+ee;xa(b,X,o,pe),wo(b);return}if(S==="submit-all"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(re=>re.toolCall?.id===E);if(!X)return;let G=b.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&co(b,G);let ee=va(b,X);st.current.persistAskUserQuestionProgress(X,{answers:ee,currentIndex:mn(b)});let pe=bc(ee);Ko(b,pe||"(submitted)",{source:"submit-all",structured:ee});return}if(S==="skip"){if(!st.current)return;let E=b.getAttribute("data-tool-call-id")??"",X=st.current.getMessages().find(be=>be.toolCall?.id===E);if(!X)return;let O=lo(b),G=mn(b),ee=ir(b),pe=G>=ee-1;if(!O){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),lr(qo,E),X.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(X),st.current.resolveAskUserQuestion(X,"(dismissed)"));return}co(b,"");let re=b.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),pe){let be=va(b,X),Ue=bc(be);Ko(b,Ue||"(skipped)",{source:"submit-all",structured:be});return}xa(b,X,o,G+1),wo(b);return}}),qo.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let b=m.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let S=m.value;if(S.trim()){if(lo(b)){co(b,S.trim()),wo(b),Ci(b);return}Ko(b,S,{source:"free-text"})}});let vc=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let f=i.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let m=qo.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),E=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",vc);let Xn=null,ht=null,Hr=null,$s=null,Ai=()=>{},wc=!1,Us="",zs="";function Si(){$s?.(),$s=null}let xc=()=>{if(!Xn||!ht)return;let i=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,m=f.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let b=Xn.firstElementChild;if(!b||b===ht)return;let S=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${S}px`,ht.style.zIndex="5";let E=zl(Xn,f),X=b.offsetWidth+E/2-S/2;ht.style.left=`${Math.max(0,X)}px`},js=()=>{},Bf=()=>{let i=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!f||i.innerWidth>m?!1:M||Dt(o)},Vs=()=>!Yt(o)||!_s()||e.classList.contains("persona-artifact-narrow-host")||Bf()||(e.ownerDocument.defaultView??window).innerWidth<Rb?"none":_l(o)?"detached":"welded",Wn=()=>{if(!Ge||!Yt(o))return;Ws(e,o),Hs(e,o),js();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=i);let m=_s();Ge.setVisible(m),Ge.update(yn),Rn?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),Ge.backdrop?.classList.add("persona-hidden"),bn=!1,Wr=!1):yn.artifacts.length>0&&yc()?(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)):(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),Ge.backdrop?.classList.add("persona-hidden"),bn=!1,Wr=!1);let b=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ge.setExpandToggleVisible(b),Ge.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ge.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ge.setTabFade(o.features?.artifacts?.layout?.tabFade),Ge.setRenderTabBar(o.features?.artifacts?.renderTabBar),!b&&!Wr&&(bn=!1),bn!==wc){let E=Ge.element;bn?(Us=E.style.width,zs=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(Us&&(E.style.width=Us),zs&&(E.style.maxWidth=zs),Us="",zs=""),wc=bn}e.classList.toggle("persona-artifact-expanded",bn),Ge.setExpanded(bn);let S=Vs();S!==Rr&&(Rr=S,Ir()),Ai()};if(Yt(o)){ue.style.position="relative";let i=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(me),Ge=zu(o,{onSelect:m=>st.current?.selectArtifact(m),onDismiss:()=>{Rn=!0,Wn()},onToggleExpand:()=>{let m=!bn,b=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:b,expanded:m})!==!0&&(bn=m,m||(Wr=!1),Wn())}}),Ge.element.classList.add("persona-hidden"),Xn=f,f.appendChild(i),f.appendChild(Ge.element),Ge.backdrop&&ue.appendChild(Ge.backdrop),ue.appendChild(f),Ai=()=>{if(!Xn||!Ge)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Hr?.(),Hr=null,Si(),ht&&(ht.remove(),ht=null),Ge.element.style.removeProperty("width"),Ge.element.style.removeProperty("maxWidth");return}if(!ht){let b=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");b.setAttribute("role","separator"),b.setAttribute("aria-orientation","vertical"),b.setAttribute("aria-label","Resize artifacts panel"),b.tabIndex=0;let S=e.ownerDocument,E=S.defaultView??window,X=O=>{if(!Ge||O.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;O.preventDefault(),Si();let G=O.clientX,ee=Ge.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,re=Ue=>{let lt=Xn.getBoundingClientRect().width,Ze=e.classList.contains("persona-artifact-welded-split"),rn=zl(Xn,E),At=Ze?0:b.getBoundingClientRect().width||6,Et=ee-(Ue.clientX-G),W=Yu(Et,lt,rn,At,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ge.element.style.width=`${W}px`,Ge.element.style.maxWidth="none",xc()},be=()=>{S.removeEventListener("pointermove",re),S.removeEventListener("pointerup",be),S.removeEventListener("pointercancel",be),$s=null;try{b.releasePointerCapture(O.pointerId)}catch{}};$s=be,S.addEventListener("pointermove",re),S.addEventListener("pointerup",be),S.addEventListener("pointercancel",be);try{b.setPointerCapture(O.pointerId)}catch{}};b.addEventListener("pointerdown",X),ht=b,Xn.insertBefore(b,Ge.element),Hr=()=>{b.removeEventListener("pointerdown",X)}}if(ht){let b=_s();ht.classList.toggle("persona-hidden",!b),xc()}},js=()=>{if(!M||!Ge||(o.launcher?.sidebarMode??!1)||Dt(o)&&hn(o).reveal==="emerge")return;let b=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(S&&b.innerWidth<=E||!qu(o,M))return;let X=o.launcher?.width??o.launcherWidth??jn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(ue.style.width=O,ue.style.maxWidth=O):(ue.style.width=X,ue.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Pr=new ResizeObserver(()=>{Wn()}),Pr.observe(ue))}else ue.appendChild(me);D()&&Xe&&(We.peekBanner&&Xe.appendChild(We.peekBanner),Xe.appendChild(we)),e.appendChild(Be),Xe&&e.appendChild(Xe);let qs=()=>{if(D()){ue.style.width="100%",ue.style.maxWidth="100%";let St=o.launcher?.composerBar??{},en=Be.dataset.state==="expanded",ca=St.expandedSize??"anchored";if(!(en&&ca!=="fullscreen")){me.style.background="",me.style.border="",me.style.borderRadius="",me.style.overflow="",me.style.boxShadow="";return}let Zr=o.theme?.components?.panel,da=gr(o),tr=(Fn,Ro)=>Fn==null||Fn===""?Ro:Xt(da,Fn)??Fn,pa="1px solid var(--persona-border)",Vi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";me.style.background="var(--persona-surface, #ffffff)",me.style.border=tr(Zr?.border,pa),me.style.borderRadius=tr(Zr?.borderRadius,Io),me.style.boxShadow=tr(Zr?.shadow,Vi),me.style.overflow="hidden";return}let i=Dt(o),f=o.launcher?.sidebarMode??!1,m=i||f||(o.launcher?.fullHeight??!1),b=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,X=gr(o),O=(St,en)=>St==null||St===""?en:Xt(X,St)??St,G=e.ownerDocument.defaultView??window,ee=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,re=G.innerWidth<=pe,be=ee&&re&&M,Ue=i&&ee&&re,lt=o.launcher?.position??"bottom-left",Ze=lt==="bottom-left"||lt==="top-left",rn=o.launcher?.zIndex??Vt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Et="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=S&&!be&&!Ue;ke?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=ke?At:f||be?"none":At,Se=ke?Et:be?"none":f?Ze?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":b?"none":Et;i&&!be&&!ke&&(Se="none",Fe="none");let wt=ke?W:f||be?"0":W,ct=O(E?.border,Fe),Bt=O(E?.shadow,Se),dt=O(E?.borderRadius,wt),Zt=Vs(),kt=Zt==="detached",Le=Zt==="welded";e.classList.toggle("persona-artifact-detached-split",kt),e.classList.toggle("persona-artifact-welded-split",Le);let Ne="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",bt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(o)&&_l(o)&&b&&!i;e.classList.toggle("persona-artifact-chat-flush",bt);let at=kt||bt?"none":Bt,ut=kt?At:Le?"none":ct,Qe=kt?W:dt;bt&&(ut="none",Qe="0");let He=E?.borderRadius!=null&&E.borderRadius!=="",gt=bt&&!He?"0":dt,Ut=le.scrollTop;e.style.cssText="",Be.style.cssText="",ue.style.cssText="",me.style.cssText="",le.style.cssText="",we.style.cssText="",ze&&(le.style.display="none"),(m||b)&&(e.style.minWidth="0");let fn=()=>{if(Ut<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===Ut)return;let en=le.scrollHeight-le.clientHeight;en<=0||(le.scrollTop=Math.min(Ut,en))})};if(be){Be.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Be.style.cssText=`
|
|
46
|
+
`,N.addEventListener("click",()=>{f=F,B.forEach((z,j)=>{let te=j<F;z.classList.toggle("selected",te),z.setAttribute("aria-checked",j===F-1?"true":"false")})}),B.push(N),T.appendChild(N)}w.appendChild(T);let S=null;if(u){let F=document.createElement("div");F.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),F.appendChild(S),w.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=l,P.addEventListener("click",()=>{n?.(),c.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=S?.value.trim()||void 0;await t(f,F),c.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",F)}}),k.appendChild(P),k.appendChild(H),w.appendChild(k),c.appendChild(w),c}function wg(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let w=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,v.appendChild(T),g.appendChild(v);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=d;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,S.appendChild(k),S.appendChild(P);let H=document.createElement("div");H.className="persona-feedback-numbers";let F=[];for(let A=0;A<=10;A++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${A} out of 10`),G.textContent=String(A),G.dataset.rating=String(A),A<=6?G.classList.add("persona-feedback-detractor"):A<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{w=A,F.forEach((Q,ie)=>{Q.classList.toggle("selected",ie===A),Q.setAttribute("aria-checked",ie===A?"true":"false")})}),F.push(G),H.appendChild(G)}B.appendChild(S),B.appendChild(H),g.appendChild(B);let N=null;if(u){let A=document.createElement("div");A.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),A.appendChild(N),g.appendChild(A)}let z=document.createElement("div");z.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),f.remove()});let te=document.createElement("button");return te.type="button",te.className="persona-feedback-btn persona-feedback-btn-submit",te.textContent=a,te.addEventListener("click",async()=>{if(w===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}te.disabled=!0,te.textContent="Submitting...";try{let A=N?.value.trim()||void 0;await t(w,A),f.remove()}catch(A){te.disabled=!1,te.textContent=a,console.error("[NPS Feedback] Failed to submit:",A)}}),z.appendChild(j),z.appendChild(te),g.appendChild(z),f.appendChild(g),f}var qr="persona-chat-history",lw=30*1e3,cw=641,dw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function pw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=dw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Fi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function uw(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nc=e=>!e||typeof e!="object"?{}:{...e},xg=e=>e.map(t=>({...t,streaming:!1})),Cg=(e,t,n)=>{let o=e?.markdown?Ba(e.markdown):null,r=Da(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let u=Gn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Bp(a):a,f=o(c);d=r&&u?r(f):f}else d=mo(a);return d}};function Ag(e){let t=b("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var gw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},mw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:gw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Sg=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ei(t),r=o.features;o=Pc(o);let s=Hc.getForInstance(o.plugins),a=!1,l=Nf(()=>o),{plugin:u,teardown:d}=Kf();o.components&&Zn.registerAll(o.components);let c=fg(),w=o.persistState===!1?null:o.storageAdapter??mg(),g={},v=null,C=!1,T=i=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(i);if(p&&typeof p=="object"&&"state"in p){let{state:m,open:y}=p;return y&&(C=!0),m}return p}catch(p){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return i};if(w?.load)try{let i=w.load();if(i&&typeof i.then=="function")v=i.then(p=>T(p??{messages:[],metadata:{}}));else{let m=T(i??{messages:[],metadata:{}});m.metadata&&(g=Nc(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let B=()=>g,S=i=>{g=i({...g})??{},nl()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick],H=Fc({parsers:k,handlers:P,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null});H.syncFromMetadata();let F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,j=N,te=F,A=o.layout?.header?.layout,G=!1,Q=()=>Vs(o),ie=()=>F||Q(),Y=Q()?!1:F?N:!0,ue=!1,X=null,ge=()=>{ue=!0,X&&clearTimeout(X),X=setTimeout(()=>{ue&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ue=!1)},1e4)},Z=Cg(o,H,ge),pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,we=o.features?.scrollToBottom??{},he=o.features?.scrollBehavior??{},Ne=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ue=me?new Js(Ne):null,Qe=o.features?.eventStream?.maxEvents??2e3,Oe=me?new Qs(Qe,Ue):null,_e=me?new Zs:null,Ae=null,Se=!1,ze=null,Gt=0;Ue?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",p)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",p)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},xn=i=>i==="idle"?Ht.idleText??It.idle:i==="connecting"?Ht.connectingText??It.connecting:i==="connected"?Ht.connectedText??It.connected:i==="error"?Ht.errorText??It.error:i==="paused"?Ht.pausedText??It.paused:i==="resuming"?Ht.resumingText??It.resuming:It[i];function Cn(i,p,m,y){if(y==="idle"&&m.idleLink){i.textContent="";let x=document.createElement("a");x.href=m.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=p,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=p}let et=Of({config:o,showClose:ie()}),{wrapper:Le,panel:ye,pillRoot:tt}=et.shell,Te=et.panelElements,{container:ve,body:re,messagesWrapper:xe,starterSuggestions:An,transcriptSuggestions:ne,suggestions:M,textarea:I,sendButton:h,sendButtonWrapper:W,composerForm:L,statusText:R,welcomeHost:q,welcomeIconHolder:$,greetingHost:K,introTitle:ce,introSubtitle:je,closeButton:de,iconHolder:Pe,headerTitle:Ve,headerSubtitle:$e,header:Re,footer:Ce,actionsRow:nt,rightActions:xt}=Te,dn=Te.leftActions,ra=Te.setSendButtonMode,oe=Te.micButton,pn=Te.micButtonWrapper,it=Te.attachmentButton,un=Te.attachmentButtonWrapper,St=Te.attachmentInput,Sn=Te.attachmentPreviewsContainer;ve.classList.add("persona-relative"),re.classList.add("persona-relative");let Dg=12,Gr=()=>we.label??"",Fg=()=>we.iconName??"arrow-down",Og=()=>we.enabled!==!1,nn=()=>he.mode??"anchor-top",no=()=>nn()==="follow"||nn()==="anchor-top"&&rs,Yr=()=>he.anchorTopOffset??16,Ng=()=>he.restorePosition??"bottom",qc=()=>he.pauseOnInteraction===!0,Kc=()=>he.showActivityWhilePinned!==!1,Gc=()=>he.announce===!0,Ni=()=>he.scrollbar??"on-scroll",Et=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let Xr=b("span","persona-flex persona-items-center"),_i=b("span",""),Mo=b("span","");Mo.setAttribute("data-persona-scroll-to-bottom-count",""),Mo.style.display="none",Et.append(Xr,_i,Mo),ve.appendChild(Et);let fn=b("div","persona-stream-anchor-spacer");fn.setAttribute("aria-hidden","true"),fn.setAttribute("data-persona-anchor-spacer",""),fn.style.flexShrink="0",fn.style.pointerEvents="none",fn.style.height="0px",fn.style.display="none",re.appendChild(fn);let Eo=b("div","persona-sr-only");Eo.setAttribute("aria-live","polite"),Eo.setAttribute("aria-atomic","true"),Eo.setAttribute("role","status"),Eo.setAttribute("data-persona-live-region",""),Object.assign(Eo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ve.appendChild(Eo);let Qr=null,sa=null,Yc=i=>{!Gc()||!i||(sa=i,Qr===null&&(Qr=setTimeout(()=>{Qr=null,sa&&Gc()&&(Eo.textContent=sa),sa=null},400)))},ko=()=>{let p=Ce.style.display==="none"?0:Ce.offsetHeight;Et.style.bottom=`${p+Dg}px`};ko();let Xc=()=>{let i=!!Gr();Et.setAttribute("aria-label",Gr()||"Jump to latest"),Et.title=Gr(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Xr.innerHTML="";let p=ae(Fg(),"14px","currentColor",2);p?(Xr.appendChild(p),Xr.style.display=""):Xr.style.display="none",_i.textContent=Gr(),_i.style.display=i?"":"none"};Xc();let yt=null,Yt=null,Qc=null,Jc=s.find(i=>i.renderHeader);if(Jc?.renderHeader){let i=Jc.renderHeader({config:o,defaultRenderer:()=>{let p=Jo({config:o,showClose:ie()});return Ks(ve,p,o),p.header},onClose:()=>lt(!1,"user")});if(i){let p=ve.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(i),Re=i,et.header.element=i)}}let $i=()=>{if(!Oe)return;if(Se=!0,!Ae&&Oe&&(Ae=Qf({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Jr(),config:o,plugins:s,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",Ce.parentNode?.insertBefore(Ae.element,Ce),Ae.update()),Je){Je.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let p=o.features?.eventStream?.classNames?.toggleButtonActive;p&&p.split(/\s+/).forEach(m=>m&&Je.classList.add(m))}let i=()=>{if(!Se)return;let p=Date.now();p-Gt>=200&&(Ae?.update(),Gt=p),ze=requestAnimationFrame(i)};Gt=0,ze=requestAnimationFrame(i),$t(),c.emit("eventStream:opened",{timestamp:Date.now()})},Jr=()=>{if(Se){if(Se=!1,Ae&&Ae.element.remove(),re.style.display="",Je){Je.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(p=>p&&Je.classList.remove(p))}ze!==null&&(cancelAnimationFrame(ze),ze=null),$t(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Je=null;if(me){let i=o.features?.eventStream?.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Je=b("button",p),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&Je.appendChild(m);let y=Te.clearChatButtonWrapper,x=Te.closeButtonWrapper,E=y||x;E&&E.parentNode===Re?Re.insertBefore(Je,E):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}let Zc=i=>{let p=o.attachments;if(!p?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(m,x):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=b("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(p.allowedTypes??Qn).join(","),x.multiple=(p.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",p.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ui=s.find(i=>i.renderComposer),zi=!1,ed=i=>{if(!Ui?.renderComposer)return null;let p=o.composer,m=a?_.isStreaming():!1;return Ui.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Dm(),storage:l(Ui.id),onSubmit:y=>{if(!_||_.isStreaming())return;let x=y.trim(),E=yt?.hasAttachments()??!1;if(!x&&!E)return;tp();let U;E&&(U=[],U.push(...yt.getContentParts()),x&&U.push(Lr(x))),_.sendMessage(x,{contentParts:U}),E&&yt.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{St?.click()},models:p?.models,selectedModelId:p?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Qc?.()}:void 0})},td=ed(()=>Gs({config:o}).footer);td&&(et.replaceComposer(td),Ce=et.composer.footer,zi=!0);let nd=i=>{let p=(...fe)=>{for(let le of fe){let be=i.querySelector(le);if(be)return be}return null},m=i.querySelector("[data-persona-composer-form]"),y=i.querySelector("[data-persona-composer-input]"),x=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),U=i.querySelector("[data-persona-composer-status]");m&&(L=m),y&&(I=y),x&&(h=x),E&&(oe=E,pn=E.parentElement),U&&(R=U);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(M=O);let V=p("[data-persona-composer-attachment-button]",".persona-attachment-button");V&&(it=V,un=V.parentElement),St=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Sn=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let J=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");J&&(nt=J),dn=p(".persona-widget-composer__left-actions")};Zc(Ce),nd(Ce);let Zr=xo(o,Q());Zr&&(xe.style.maxWidth=Zr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=Zr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",An.style.maxWidth=Zr,ne.style.maxWidth=Zr,ne.style.marginLeft="auto",ne.style.marginRight="auto",ne.style.width="100%");let od=()=>{let i=xo(o,Q());if(!(!i||Q()))for(let p of[L,M,Sn,R])p&&(p.style.maxWidth=i,p.style.marginLeft="auto",p.style.marginRight="auto")};od();let rd=()=>{!o.attachments?.enabled||!St||!Sn||(yt?yt.remountPreviews(Sn):(yt=Rs.fromConfig(o.attachments),yt.setPreviewsContainer(Sn)),St.addEventListener("change",i=>{let p=i.target;yt?.handleFileSelect(p.files),p.value=""}),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(Ag(o.attachments.dropOverlay)))};rd();let _g=()=>Yt?.prefetch(),sd=()=>{if(!(!o.contextMentions?.enabled||!I)&&(Yt=Pu({config:o,textarea:I,anchor:L??I,getMessages:()=>_.getMessages(),liveRegionHost:ve}),Yt)){let i=I;i.parentElement?.insertBefore(Yt.contextRow,i);let p=Yt.affordanceButtons;for(let m=p.length-1;m>=0;m--){let y=p[m];dn?dn.insertBefore(y,dn.firstChild):L?.appendChild(y)}}};sd(),(()=>{let i=o.layout?.slots??{},p=y=>{switch(y){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return M;case"composer":return L;case"footer-bottom":return R;default:return null}},m=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")Re.insertBefore(x,Re.firstChild);else if(y==="header-right")Re.appendChild(x);else{let E=Re.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(x,E.nextSibling):Re.appendChild(x)}break;case"body-top":{let E=re.querySelector("[data-persona-intro-card]");E?E.replaceWith(x):re.insertBefore(x,re.firstChild);break}case"body-bottom":re.appendChild(x);break;case"footer-top":M.replaceWith(x);break;case"footer-bottom":R.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let E=x({config:o,defaultContent:()=>p(y)});E&&m(y,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,E)}})();let ad=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let y=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-bubble-type");if(E==="reasoning")$r.has(x)?$r.delete(x):$r.add(x),_f(x,y);else if(E==="tool")Ur.has(x)?Ur.delete(x):Ur.add(x),$f(x,y,o);else if(E==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=er.get(x)??O;er.set(x,!V),Vf(x,y,o)}Bo.delete(x)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("keydown",i=>{let p=i.target;(i.key==="Enter"||i.key===" ")&&p.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("copy",i=>{let{clipboardData:p}=i;if(!p)return;let m=xe.getRootNode(),y=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),E=rf(x);!E||E===x||(p.setData("text/plain",E),i.preventDefault())});let ji=new Map,id=null,ld="idle",$g={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ug=(i,p)=>{let{icon:m,label:y}=$g[p];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",p==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",p!=="idle"),i.classList.toggle("persona-message-action-loading",p==="loading");let x=ae(m,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},cd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{let y=p.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Ug(p,y&&y===id?ld:"idle")})};xe.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest("[data-actions-for]");if(!y)return;let x=y.getAttribute("data-actions-for");if(!x)return;let E=m.getAttribute("data-action");if(E==="copy"){let O=_.getMessages().find(V=>V.id===x);if(O&>.onCopy){let V=O.content||"";navigator.clipboard.writeText(V).then(()=>{m.classList.add("persona-message-action-success");let J=ae("check",14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let fe=ae("copy",14,"currentColor",2);fe&&(m.innerHTML="",m.appendChild(fe))},2e3)}).catch(J=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",J)}),gt.onCopy(O)}}else if(E==="read-aloud")_.toggleReadAloud(x);else if(E==="upvote"||E==="downvote"){let O=(ji.get(x)??null)===E,V=E==="upvote"?"thumbs-up":"thumbs-down";if(O){ji.delete(x),m.classList.remove("persona-message-action-active");let J=ae(V,14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J))}else{let J=E==="upvote"?"downvote":"upvote",fe=y.querySelector(`[data-action="${J}"]`);if(fe){fe.classList.remove("persona-message-action-active");let ct=ae(J==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(fe.innerHTML="",fe.appendChild(ct))}ji.set(x,E),m.classList.add("persona-message-action-active");let le=ae(V,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(le)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ge=_.getMessages().find(mt=>mt.id===x);Ge&>.onFeedback&>.onFeedback({type:E,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest(".persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-approval-action");if(!E)return;let U=E==="approve"?"approved":"denied",V=_.getMessages().find(fe=>fe.id===x);if(!V?.approval)return;let J=y.querySelector("[data-approval-buttons]");J&&J.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,U):_.resolveApproval(V.approval,U)});let Ye=null,es=null,Lo=()=>{},ts="none",aa=null,Tn={artifacts:[],selectedId:null},On=!1,Mn=!1,ns=!1,sr=!1,dd=()=>sr||Tn.artifacts.some(i=>ho(o.features?.artifacts,i)==="panel"),ia=()=>Tn.artifacts.length>0&&!On&&dd(),st={current:null},Vi=(i,p)=>{let m=_.getArtifactById(p),y=m?.markdown,x=m?.title||"artifact",E=m?.file,U=m?.artifactType??"markdown";if(!y){let J=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(J){let le=_.getMessages().find(be=>be.id===J);if(le?.rawContent)try{let be=JSON.parse(le.rawContent);y=be?.props?.markdown,x=be?.props?.title||x,be?.props?.file&&typeof be.props.file=="object"&&(E=be.props.file),!m&&typeof be?.props?.artifactType=="string"&&(U=be.props.artifactType)}catch{}}}return{markdown:y,title:x,file:E,artifactType:U}};xe.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:E,title:U,file:O}=Vi(m,y);if(!E)return;let{filename:V,mime:J,content:fe}=_u({title:U,markdown:E,file:O}),le=new Blob([fe],{type:J}),be=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=be,Ge.download=V,Ge.click(),URL.revokeObjectURL(be)}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-artifact-custom-action");if(!y)return;let x=m.closest("[data-artifact-inline]"),E=x?null:m.closest("[data-open-artifact]"),U=x?x.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,V=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(mt=>mt.id===y);if(!V)return;let{markdown:J,title:fe,file:le,artifactType:be}=Vi(m,U??""),Ge={artifactId:U,title:fe,artifactType:be,markdown:J,file:le};try{Promise.resolve(V.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-copy-artifact");if(!y)return;let x=_.getArtifactById(y),E="";if(x)E=Ns(x);else{let{markdown:U,file:O,artifactType:V}=Vi(m,y);V==="markdown"&&(E=Ns({id:y,artifactType:"markdown",status:"complete",markdown:U??"",...O?{file:O}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let U=ae("check",16,"currentColor",2);U&&(m.replaceChildren(U),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&m.replaceChildren(O)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(On=!1,sr=!0,Mn=!0,ns=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("click",i=>{let p=i.target;if(p.closest("[data-download-artifact]")||p.closest("[data-artifact-custom-action]"))return;let m=p.closest("[data-open-artifact]");if(!m)return;let y=m.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),On=!1,sr=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let p=i.target;!p.hasAttribute("data-open-artifact")&&!p.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),p.click())});let ar=Te.composerOverlay,ir=(i,p,m)=>{let y=p.trim();if(!y||!st.current)return;let x=i.getAttribute("data-tool-call-id")??"",E=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:y,answers:m.structured,values:m.values??(m.source==="multi"?y.split(", "):[y]),isFreeText:E,source:m.source},bubbles:!0,composed:!0})),Er(ar,x);let U=st.current.getMessages().find(O=>O.toolCall?.id===x);U?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(U,m.structured??y):st.current.sendMessage(y)},Po=i=>{let p=st.current;if(!p)return;let m=i.getAttribute("data-tool-call-id")??"",y=p.getMessages().find(x=>x.toolCall?.id===m);y&&p.persistAskUserQuestionProgress(y,{answers:Na(i,y),currentIndex:bn(i)})},pd=i=>Object.entries(i).map(([p,m])=>`${p}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),qi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let p=bn(i),m=Mr(i);if(p>=m-1)return;let y=st.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&($a(i,y,o,p+1),Po(i))};ar.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;let x=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let E=y.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E);let U=st.current?.getMessages().find(O=>O.toolCall?.id===E);U?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(U),st.current?.resolveAskUserQuestion(U,"(dismissed)"));return}if(x==="pick"){let E=m.getAttribute("data-option-label");if(!E)return;let U=y.getAttribute("data-multi-select")==="true",O=yo(y);if(O&&U){let V=Ko(y)[bn(y)],J=new Set(Array.isArray(V)?V:[]);J.has(E)?J.delete(E):J.add(E),bo(y,Array.from(J)),Po(y);return}if(O){bo(y,E),Po(y),qi(y);return}if(U){let V=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",V?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!V);let J=y.querySelector('[data-ask-user-action="submit-multi"]');J&&(J.disabled=Nl(y).length===0);return}ir(y,E,{source:"pick",values:[E]});return}if(x==="submit-multi"){let E=Nl(y);if(E.length===0)return;ir(y,E.join(", "),{source:"multi",values:E});return}if(x==="open-free-text"){let E=y.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let U=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!U.trim())return;if(yo(y)){bo(y,U.trim()),Po(y),qi(y);return}ir(y,U,{source:"free-text"});return}if(x==="next"||x==="back"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let le=Ko(y)[bn(y)];(typeof le!="string"||le!==V)&&bo(y,V)}let J=x==="next"?1:-1,fe=bn(y)+J;$a(y,U,o,fe),Po(y);return}if(x==="submit-all"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&bo(y,V);let J=Na(y,U);st.current.persistAskUserQuestionProgress(U,{answers:J,currentIndex:bn(y)});let fe=pd(J);ir(y,fe||"(submitted)",{source:"submit-all",structured:J});return}if(x==="skip"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(be=>be.toolCall?.id===E);if(!U)return;let O=yo(y),V=bn(y),J=Mr(y),fe=V>=J-1;if(!O){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E),U.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(U),st.current.resolveAskUserQuestion(U,"(dismissed)"));return}bo(y,"");let le=y.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),fe){let be=Na(y,U),Ge=pd(be);ir(y,Ge||"(skipped)",{source:"submit-all",structured:be});return}$a(y,U,o,V+1),Po(y);return}}),ar.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let x=m.value;if(x.trim()){if(yo(y)){bo(y,x.trim()),Po(y),qi(y);return}ir(y,x,{source:"free-text"})}});let ud=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let p=i.target;if(p?.tagName==="INPUT"||p?.tagName==="TEXTAREA"||p?.isContentEditable)return;let m=ar.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),E=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",ud);let oo=null,bt=null,os=null,la=null,Ki=()=>{},fd=!1,ca="",da="";function Gi(){la?.(),la=null}let gd=()=>{if(!oo||!bt)return;let i=e.classList.contains("persona-artifact-welded-split"),p=e.ownerDocument.defaultView??window,m=p.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let y=oo.firstElementChild;if(!y||y===bt)return;let x=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${x}px`,bt.style.zIndex="5";let E=Ic(oo,p),U=y.offsetWidth+E/2-x/2;bt.style.left=`${Math.max(0,U)}px`},pa=()=>{},zg=()=>{let i=e.ownerDocument.defaultView??window,p=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!p||i.innerWidth>m?!1:F||Rt(o)},ua=()=>!Jt(o)||!ia()||e.classList.contains("persona-artifact-narrow-host")||zg()||(e.ownerDocument.defaultView??window).innerWidth<cw?"none":kc(o)?"detached":"welded",Nn=()=>{if(!Ye||!Jt(o))return;ea(e,o),ta(e,o),pa();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,p=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=i);let m=ia();Ye.setVisible(m),Ye.update(Tn),On?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1):Tn.artifacts.length>0&&dd()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(y),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!ns&&(Mn=!1),Mn!==fd){let E=Ye.element;Mn?(ca=E.style.width,da=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(ca&&(E.style.width=ca),da&&(E.style.maxWidth=da),ca="",da=""),fd=Mn}e.classList.toggle("persona-artifact-expanded",Mn),Ye.setExpanded(Mn);let x=ua();x!==ts&&(ts=x,Lo()),Ki()};if(Jt(o)){ye.style.position="relative";let i=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ve),Ye=Zf(o,{onSelect:m=>st.current?.selectArtifact(m),onDismiss:()=>{On=!0,Nn()},onToggleExpand:()=>{let m=!Mn,y=Tn.selectedId??Tn.artifacts[Tn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:y,expanded:m})!==!0&&(Mn=m,m||(ns=!1),Nn())}}),Ye.element.classList.add("persona-hidden"),oo=p,p.appendChild(i),p.appendChild(Ye.element),Ye.backdrop&&ye.appendChild(Ye.backdrop),ye.appendChild(p),Ki=()=>{if(!oo||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let y=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");y.setAttribute("role","separator"),y.setAttribute("aria-orientation","vertical"),y.setAttribute("aria-label","Resize artifacts panel"),y.tabIndex=0;let x=e.ownerDocument,E=x.defaultView??window,U=O=>{if(!Ye||O.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;O.preventDefault(),Gi();let V=O.clientX,J=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,le=Ge=>{let mt=oo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),sn=Ic(oo,E),At=ct?0:y.getBoundingClientRect().width||6,Lt=J-(Ge.clientX-V),D=lg(Lt,mt,sn,At,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${D}px`,Ye.element.style.maxWidth="none",gd()},be=()=>{x.removeEventListener("pointermove",le),x.removeEventListener("pointerup",be),x.removeEventListener("pointercancel",be),la=null;try{y.releasePointerCapture(O.pointerId)}catch{}};la=be,x.addEventListener("pointermove",le),x.addEventListener("pointerup",be),x.addEventListener("pointercancel",be);try{y.setPointerCapture(O.pointerId)}catch{}};y.addEventListener("pointerdown",U),bt=y,oo.insertBefore(y,Ye.element),os=()=>{y.removeEventListener("pointerdown",U)}}if(bt){let y=ia();bt.classList.toggle("persona-hidden",!y),gd()}},pa=()=>{if(!F||!Ye||(o.launcher?.sidebarMode??!1)||Rt(o)&&vn(o).reveal==="emerge")return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E||!ng(o,F))return;let U=o.launcher?.width??o.launcherWidth??Jn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ia()?(ye.style.width=O,ye.style.maxWidth=O):(ye.style.width=U,ye.style.maxWidth=U)},typeof ResizeObserver<"u"&&(es=new ResizeObserver(()=>{Nn()}),es.observe(ye))}else ye.appendChild(ve);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(Ce)),e.appendChild(Le),tt&&e.appendChild(tt);let Yi=()=>{if(Q()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},tn=Le.dataset.state==="expanded",Pa=Mt.expandedSize??"anchored";if(!(tn&&Pa!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let bs=o.theme?.components?.panel,Ia=Rr(o),vr=(qn,Vo)=>qn==null||qn===""?Vo:Qt(Ia,qn)??qn,Wa="1px solid var(--persona-border)",kl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",jo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=vr(bs?.border,Wa),ve.style.borderRadius=vr(bs?.borderRadius,jo),ve.style.boxShadow=vr(bs?.shadow,kl),ve.style.overflow="hidden";return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=i||p||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,U=Rr(o),O=(Mt,tn)=>Mt==null||Mt===""?tn:Qt(U,Mt)??Mt,V=e.ownerDocument.defaultView??window,J=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,le=V.innerWidth<=fe,be=J&&le&&F,Ge=i&&J&&le,mt=o.launcher?.position??"bottom-left",ct=mt==="bottom-left"||mt==="top-left",sn=o.launcher?.zIndex??Nt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",D="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=x&&!be&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let De=Ie?At:p||be?"none":At,Me=Ie?Lt:be?"none":p?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":y?"none":Lt;i&&!be&&!Ie&&(Me="none",De="none");let Ct=Ie?D:p||be?"0":D,dt=O(E?.border,De),Ft=O(E?.shadow,Me),pt=O(E?.borderRadius,Ct),en=ua(),Pt=en==="detached",We=en==="welded";e.classList.toggle("persona-artifact-detached-split",Pt),e.classList.toggle("persona-artifact-welded-split",We);let Fe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&kc(o)&&y&&!i;e.classList.toggle("persona-artifact-chat-flush",wt);let at=Pt||wt?"none":Ft,ut=Pt?At:We?"none":dt,Xe=Pt?D:pt;wt&&(ut="none",Xe="0");let He=E?.borderRadius!=null&&E.borderRadius!=="",ht=wt&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",ye.style.cssText="",ve.style.cssText="",re.style.cssText="",Ce.style.cssText="",Se&&(re.style.display="none"),(m||y)&&(e.style.minWidth="0");let hn=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let tn=re.scrollHeight-re.clientHeight;tn<=0||(re.scrollTop=Math.min(jt,tn))})};if(be){Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Le.style.cssText=`
|
|
47
47
|
position: fixed !important;
|
|
48
48
|
inset: 0 !important;
|
|
49
49
|
width: 100% !important;
|
|
@@ -53,9 +53,9 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
53
53
|
padding: 0 !important;
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
|
-
z-index: ${
|
|
56
|
+
z-index: ${sn} !important;
|
|
57
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
58
|
-
`,
|
|
58
|
+
`,ye.style.cssText=`
|
|
59
59
|
position: relative !important;
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
68
|
padding: 0 !important;
|
|
69
69
|
box-shadow: none !important;
|
|
70
70
|
border-radius: 0 !important;
|
|
71
|
-
`,
|
|
71
|
+
`,ve.style.cssText=`
|
|
72
72
|
display: flex !important;
|
|
73
73
|
flex-direction: column !important;
|
|
74
74
|
flex: 1 1 0% !important;
|
|
@@ -79,33 +79,33 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
79
79
|
overflow: hidden !important;
|
|
80
80
|
border-radius: 0 !important;
|
|
81
81
|
border: none !important;
|
|
82
|
-
`,
|
|
82
|
+
`,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ce.style.flexShrink="0",G=!0,hn();return}let La=o?.launcher?.width??o?.launcherWidth??Jn;if(!p&&!i)y&&m?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=La,ye.style.maxWidth=La);else if(i)if(vn(o).reveal==="emerge"&&!x){let tn=vn(o).width;ye.style.width=tn,ye.style.maxWidth=tn}else ye.style.width="100%",ye.style.maxWidth="100%";if(pa(),ye.style.boxShadow=at,ye.style.borderRadius=ht,Pt?ye.style.border="none":We&&(ye.style.border=dt),ve.style.border=ut,ve.style.borderRadius=Xe,ve.style.boxShadow=Pt&&!wt?Fe:"",wt&&(ve.style.background="transparent",re.style.background="transparent",Ce.style.background="transparent",Ce.style.borderTop="none"),We){let Mt=o.features?.artifacts?.layout;aa=Mt?.unifiedSplitOuterRadius?.trim()||Mt?.paneBorderRadius?.trim()||pt}else aa=null;if(i&&!be&&!Ie&&!Pt&&!We&&E?.border===void 0&&(ve.style.border="none",vn(o).side==="right"?ve.style.borderLeft="1px solid var(--persona-border)":ve.style.borderRight="1px solid var(--persona-border)"),i&&!be&&We&&E?.border===void 0&&(vn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",y&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",y&&(Le.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",Pt||(ye.style.overflow="hidden"),ve.style.display="flex",ve.style.flexDirection="column",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.maxHeight="100%",ve.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",Ce.style.flexShrink="0"),y&&(Ie||Pt||wt)&&!i&&(wt||(Le.style.padding="var(--persona-panel-inset)"),Le.style.background="var(--persona-panel-canvas-bg)"),Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!y&&!i&&(ln[mt]??ln["bottom-right"]).split(" ").forEach(tn=>Le.classList.add(tn)),p){let Mt=o.launcher?.sidebarWidth??"420px";x?Le.style.cssText=`
|
|
83
83
|
position: fixed !important;
|
|
84
84
|
top: var(--persona-panel-inset) !important;
|
|
85
85
|
bottom: var(--persona-panel-inset) !important;
|
|
86
|
-
width: ${
|
|
86
|
+
width: ${Mt} !important;
|
|
87
87
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
88
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
89
89
|
margin: 0 !important;
|
|
90
90
|
padding: 0 !important;
|
|
91
91
|
display: flex !important;
|
|
92
92
|
flex-direction: column !important;
|
|
93
|
-
z-index: ${
|
|
94
|
-
${
|
|
95
|
-
`:
|
|
93
|
+
z-index: ${sn} !important;
|
|
94
|
+
${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
+
`:Le.style.cssText=`
|
|
96
96
|
position: fixed !important;
|
|
97
97
|
top: 0 !important;
|
|
98
98
|
bottom: 0 !important;
|
|
99
|
-
width: ${
|
|
99
|
+
width: ${Mt} !important;
|
|
100
100
|
height: 100vh !important;
|
|
101
101
|
max-height: 100vh !important;
|
|
102
102
|
margin: 0 !important;
|
|
103
103
|
padding: 0 !important;
|
|
104
104
|
display: flex !important;
|
|
105
105
|
flex-direction: column !important;
|
|
106
|
-
z-index: ${
|
|
107
|
-
${
|
|
108
|
-
`,
|
|
106
|
+
z-index: ${sn} !important;
|
|
107
|
+
${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
|
+
`,ye.style.cssText=`
|
|
109
109
|
position: relative !important;
|
|
110
110
|
display: flex !important;
|
|
111
111
|
flex-direction: column !important;
|
|
@@ -117,9 +117,9 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
117
117
|
margin: 0 !important;
|
|
118
118
|
padding: 0 !important;
|
|
119
119
|
box-shadow: ${at} !important;
|
|
120
|
-
border-radius: ${
|
|
121
|
-
${
|
|
122
|
-
`,
|
|
120
|
+
border-radius: ${ht} !important;
|
|
121
|
+
${Pt?"border: none !important;":We?`border: ${dt} !important;`:""}
|
|
122
|
+
`,ye.style.setProperty("width","100%","important"),ye.style.setProperty("max-width","100%","important"),ve.style.cssText=`
|
|
123
123
|
display: flex !important;
|
|
124
124
|
flex-direction: column !important;
|
|
125
125
|
flex: 1 1 0% !important;
|
|
@@ -128,16 +128,16 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
min-height: 0 !important;
|
|
129
129
|
max-height: 100% !important;
|
|
130
130
|
overflow: hidden !important;
|
|
131
|
-
border-radius: ${
|
|
131
|
+
border-radius: ${Xe} !important;
|
|
132
132
|
border: ${ut} !important;
|
|
133
|
-
${
|
|
134
|
-
${
|
|
135
|
-
`,
|
|
133
|
+
${Pt&&!wt?`box-shadow: ${Fe} !important;`:""}
|
|
134
|
+
${wt?"background: transparent !important;":""}
|
|
135
|
+
`,Ce.style.cssText=`
|
|
136
136
|
flex-shrink: 0 !important;
|
|
137
137
|
border-top: none !important;
|
|
138
138
|
padding: 8px 16px 12px 16px !important;
|
|
139
|
-
${
|
|
140
|
-
`}if(!b&&!i){let St="max-height: -moz-available !important; max-height: stretch !important;",en=f?"":"padding-top: 1.25em !important;",ca=f?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;Be.style.cssText+=St+en+ca}fn()};qs(),ys(e,o),Ws(e,o),Hs(e,o),Ir=()=>{qs(),ys(e,o),Ws(e,o),Hs(e,o),Os?e.style.setProperty("--persona-artifact-welded-outer-radius",Os):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Oe=[];Oe.push(()=>{document.removeEventListener("keydown",vc)}),Oe.push(()=>{kr!==null&&clearTimeout(kr)});let Mn=null,En=null;Oe.push(()=>{Mn?.(),Mn=null,En?.(),En=null}),Pr&&Oe.push(()=>{Pr?.disconnect(),Pr=null}),Oe.push(()=>{Hr?.(),Hr=null,Si(),ht&&(ht.remove(),ht=null),Ge?.element.style.removeProperty("width"),Ge?.element.style.removeProperty("maxWidth")}),ie&&Oe.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),qe?.destroy(),qe=null,Ae?.destroy(),Ae=null,xe=null});let xo=null,Cc=()=>{xo&&(xo(),xo=null),o.colorScheme==="auto"&&(xo=Fa(()=>{ys(e,o)}))};Cc(),Oe.push(()=>{xo&&(xo(),xo=null)}),Oe.push(l);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let i=vr(Ks.type,Ks.plugins);i&&(Ya(i,e),Oe.push(()=>bu(e)))}let Br=Za(mt),Ac=Za(Kt),Sc=Za(pt),Dr=[Br,Ac,Sc];Oe.push(()=>{Dr.forEach(i=>i.destroy())});let Co=null,N,Ao=null,Tc=!1,Mc=0,Ec=null,kc=i=>i.reduce((f,m)=>m.role==="user"?f+1:f,0),Lc=i=>{for(let f=i.length-1;f>=0;f--)if(ss(i[f]))return i[f].id??null;return null},Pc=!1,Df=()=>{Pc||o.debug!==!0||(Pc=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but copy.showWelcomeCard is false, so no starters render. Use "auto" or "composer".'))},Ic=!1,Rc=!1,Wc=(i,f)=>{Ic||o.debug!==!0||!f.enabled||f.expose||Tc||Rc&&(N.isStreaming()||i.some(ss)||(Ic=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Fr=i=>{if(!N)return;let f=i??N.getMessages(),m=ee=>{ee.render([],N,z,f)},b=ee=>{Dr.forEach(pe=>{pe!==ee&&m(pe)})};Ao&&(kc(f)>Mc||Lc(f)!==Ec)&&(Ao=null);let S=po(o);Wc(f,S);let E=S.enabled?ip(f):null,X=Ao??E,O=Ao?"host":"agent";if(X){let ee=o.suggestions?.followUps,pe=ee?.placement??(ee?"auto":"composer"),be=(pe==="auto"?D()?"composer":"after-message":pe)==="after-message"?Sc:Br;b(be),be.render(X,N,z,f,o.suggestionChipsConfig,{source:O,surface:"followUp",variant:ee?.variant??"chip",behavior:ee?.behavior??"send",overflow:ee?.overflow??"scroll",maxItems:ee?.maxItems??4,config:o,plugins:s});return}if(f.some(ee=>ee.role==="user")){Dr.forEach(m);return}let G=o.suggestions?.starters;if(G){let ee=o.copy?.showWelcomeCard!==!1,pe=G.placement??"auto",re=pe==="auto"?ee?"welcome":"composer":pe;if(re==="welcome"&&!ee){Df(),Dr.forEach(m);return}let be=re==="welcome"?Ac:Br;b(be),be.render(G.items??o.suggestionChips,N,z,f,o.suggestionChipsConfig,{surface:"starter",variant:G.variant??"card",behavior:G.behavior??"send",overflow:G.overflow??"wrap",maxItems:G.maxItems??4,config:o,plugins:s});return}b(Br),Br.render(o.suggestionChips,N,z,f,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},Hc=()=>{Ao&&(Ao=null,Fr())},Ff=i=>{let f=Array.isArray(i)?[...i]:[];if(!f.length){Hc();return}let m=N?N.getMessages():[];Ao=f,Tc=!0,Mc=kc(m),Ec=Lc(m),Fr(m)},vn=!1,So=lu(),Go=new Map,To=new Map,Jn=new Map,Ti=0,Nf=_n()!==null,nn=qa(),cn=0,Yn=null,dn=!1,Gs=!1,Zn=0,wn=null,Mo=null,Mi=!1,Qs=!1,Nr=null,Or=!0,Xs=!1,Js=null,Ys=!1,Eo=()=>{Ys=!0},Ei=null,Of=4,Zs=24,_f=80,ki=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Bc=o.voiceRecognition?.autoResume??!1,Hn=i=>{p.emit("voice:state",{active:Ve.active,source:i,timestamp:Date.now()})},xn=()=>{P(i=>({...i,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},$f=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Jl(u.voiceState),f=!!i.active,m=Number(i.timestamp??0);Ve.manuallyDeactivated=!!i.manuallyDeactivated,f&&Date.now()-m<Ib&&setTimeout(()=>{Ve.active||(Ve.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("restore"),N.isVoiceActive()&&Zo()}):ra("restore"))},1e3)},Uf=()=>N?uf(N.getMessages()).filter(i=>!i.__skipPersist):[],ea=null,Dc=(i,f)=>{typeof console<"u"&&console.error(i,f)},Li=(i,f)=>{let m=()=>{try{let X=i();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(O=>{Dc(f,O)})}catch(X){return Dc(f,X),null}},b=ea,S=b?b.then(()=>m()??void 0):m();if(!S)return;let E=S.finally(()=>{ea===E&&(ea=null)});ea=E};function Pi(i){if(!c?.save)return;let m={messages:i?uf(i):N?Uf():[],metadata:u,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};Li(()=>c.save(m),"[AgentWidget] Failed to persist state:")}let Qo=null,Fc=()=>Be.querySelector("#persona-scroll-container")||le,_r=()=>{Qo!==null&&(cancelAnimationFrame(Qo),Qo=null),dn=!1},Nc=()=>{Yn!==null&&(cancelAnimationFrame(Yn),Yn=null),Gs=!1,_r()},zf=()=>vn&&Ri()&&(ln()!=="anchor-top"||ac()),Ii=()=>{let i=Kn()||"Jump to latest",f=zf();Tt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Zn>0?(bo.textContent=String(Zn),bo.style.display="",Tt.setAttribute("aria-label",`${i} (${Zn} new)`)):(bo.textContent="",bo.style.display="none",Tt.setAttribute("aria-label",f?`${i} (response streaming below)`:i))},Oc=()=>{Zn!==0&&(Zn=0,Ii())},Ri=()=>Gn()?!nn.isFollowing():!ho(le,Zs),on=()=>{if(!kf()||ze){Tt.parentNode&&Tt.remove(),Tt.style.display="none";return}Tt.parentNode!==me&&me.appendChild(Tt),jo();let f=Pn(le)>0&&Ri();f?Ii():Oc(),Tt.style.display=f?"":"none"},$r=()=>{nn.pause()&&(Nc(),on())},eo=()=>{nn.resume(),Oc(),on()},to=(i=!1)=>{Gn()&&nn.isFollowing()&&(!i&&!vn||(Yn!==null&&(cancelAnimationFrame(Yn),Yn=null),Gs=!0,Yn=requestAnimationFrame(()=>{Yn=null,Gs=!1,nn.isFollowing()&&jf(Fc(),i?220:140)})))},_c=(i,f,m,b=()=>!0)=>{let S=i.scrollTop,E=f(),X=E-S;if(_r(),Math.abs(X)<1){dn=!0,i.scrollTop=E,cn=i.scrollTop,dn=!1;return}let O=performance.now();dn=!0;let G=pe=>1-Math.pow(1-pe,3),ee=pe=>{if(!b()){_r();return}let re=f();re!==E&&(E=re,X=E-S);let be=pe-O,Ue=Math.min(be/m,1),lt=G(Ue),Ze=S+X*lt;i.scrollTop=Ze,cn=i.scrollTop,Ue<1?Qo=requestAnimationFrame(ee):(i.scrollTop=E,cn=i.scrollTop,Qo=null,dn=!1)};Qo=requestAnimationFrame(ee)},jf=(i,f=500)=>{let m=Pn(i)-i.scrollTop;if(Math.abs(m)<1){cn=i.scrollTop;return}if(Math.abs(m)>=_f){_r(),dn=!0,i.scrollTop=Pn(i),cn=i.scrollTop,dn=!1;return}_c(i,()=>Pn(i),f,()=>nn.isFollowing())},$c=()=>{let i=Fc();dn=!0,i.scrollTop=Pn(i),cn=i.scrollTop,dn=!1,on()},Uc=i=>{let f=0,m=i;for(;m&&m!==le;)f+=m.offsetTop,m=m.offsetParent;return f},Vf=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},ta=()=>fu(Vf(),le),zc=()=>{if(Lf()!=="last-user-turn")return!1;let i=N?.getMessages()??[];if(i.length<2)return!1;let f=[...i].reverse().find(E=>E.role==="user");if(!f)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=le.querySelector(`[data-message-id="${m}"]`);if(!b)return!1;let S=Math.min(Math.max(0,Uc(b)-rc()),Pn(le));return dn=!0,le.scrollTop=S,cn=le.scrollTop,dn=!1,ln()==="follow"&&!ho(le,Zs)&&nn.pause(),on(),!0},jc=i=>{Qn.style.height=`${Math.max(0,Math.round(i))}px`,wn&&(wn.spacerHeight=Math.max(0,i))},Ur=()=>{Mo!==null&&(cancelAnimationFrame(Mo),Mo=null),_r(),wn=null,Qn.style.height="0px"},Vc=i=>{Mo!==null&&cancelAnimationFrame(Mo),Mo=requestAnimationFrame(()=>{Mo=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=le.querySelector(`[data-message-id="${f}"]`);if(!m)return;let b=Uc(m),S=wn?.spacerHeight??0,E=le.scrollHeight-S,{targetScrollTop:X,spacerHeight:O}=gu({anchorOffsetTop:b,topOffset:rc(),viewportHeight:le.clientHeight,contentHeight:E});wn={initialSpacerHeight:O,contentHeightAtAnchor:E,spacerHeight:O},jc(O),_c(le,()=>X,220)})},qf=()=>{if(Gn()){if(!nn.isFollowing()||ho(le,1))return;to(!vn);return}if(wn&&wn.initialSpacerHeight>0){let i=le.scrollHeight-wn.spacerHeight,f=mu({initialSpacerHeight:wn.initialSpacerHeight,contentHeightAtAnchor:wn.contentHeightAtAnchor,currentContentHeight:i});f!==wn.spacerHeight&&jc(f)}on()},Kf=i=>{let f=ln();f==="follow"?(eo(),to(!0)):f==="anchor-top"&&(Or=!1,Xs=!0,Ys=!1,Js=i,Vc(i))},Gf=()=>{if(ln()==="anchor-top"){if(Xs){Or=!1;return}Or=!0,Ur(),eo(),to(!0)}},Qf=i=>{if(ln()!=="anchor-top"||!Xs||Ys||ta())return;let f=Nr===null;for(let m of i){if(!f){m.id===Nr&&(f=!0);continue}if(uu(m)){if(m.id===Js)return;Js=m.id,Vc(m.id);return}}},Xf=i=>{let f=new Map;i.forEach(m=>{let b=ki.get(m.id);f.set(m.id,{streaming:m.streaming,role:m.role}),!b&&m.role==="assistant"&&(p.emit("assistant:message",m),!Qs&&(ln()!=="anchor-top"||ac())&&Ri()&&(Zn+=1,Ii(),on(),lc(Zn===1?"1 new message below.":`${Zn} new messages below.`))),m.role==="assistant"&&b?.streaming&&m.streaming===!1&&p.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(b?m.approval.status!=="pending"&&p.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):p.emit("approval:requested",{approval:m.approval,message:m}))}),ki.clear(),f.forEach((m,b)=>{ki.set(b,m)})},na=(i,f)=>{let m=f==="user"?"user":"assistant",b=o.layout?.messages?.[m],S=b?.width??"content",E=b?.maxWidth??(S==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${f}`,`persona-message-width-${S}`),i.classList.toggle("persona-justify-end",f==="user"),i.setAttribute("data-message-role",f),i.setAttribute("data-message-width",S),i.style.setProperty("--persona-message-row-max-width",E)},ko=(i,f)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),na(m,f),m},Jf=(i,f,m)=>{let b=document.createElement("div"),E=(()=>{let W=s.find(ke=>ke.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(W,ke)=>ke==null?!1:typeof ke=="string"?(W.textContent=ke,!0):(W.appendChild(ke),!0),O=new Set,G=new Map,ee=new Set,pe=s.some(W=>W.renderAskUserQuestion),re=[],be=[],Ue=o.enableComponentStreaming!==!1,lt=o.approval!==!1,Ze=[];if(f.forEach(W=>{O.add(W.id),G.set(W.id,W.role);let ke=pe&&Wo(W),Fe=lt&&W.variant==="approval"&&!!W.approval,Se=!ke&&W.role==="assistant"&&!W.variant&&Ue&&Xl(W);!Fe&&Jn.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id)),!Se&&To.has(W.id)&&(i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),To.delete(W.id));let wt=Wo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",ct=iu(W,Ti)+wt,Bt=ke||Fe||Se?null:cu(So,W.id,ct);if(Bt){b.appendChild(Bt.cloneNode(!0)),Wo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}let dt=null,Zt=s.find(Ne=>!!(W.variant==="reasoning"&&Ne.renderReasoning||W.variant==="tool"&&Ne.renderToolCall||!W.variant&&Ne.renderMessage)),kt=o.layout?.messages;if(Wo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Go.delete(W.id),i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(ss(W)&&po(o).enabled)return;if(Wo(W)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=s.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Ne&&st.current){let _t=Go.get(W.id),$t=_t!==ct,bt=null;if($t){let{payload:Qe,complete:He}=ar(W),gt=W.id,Ut=()=>st.current?.getMessages().find(fn=>fn.id===gt);bt=Ne.renderAskUserQuestion({message:W,payload:Qe,complete:He,resolve:fn=>{let Yr=Ut();Yr&&st.current?.resolveAskUserQuestion(Yr,fn)},dismiss:()=>{let fn=Ut();fn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(fn),st.current?.resolveAskUserQuestion(fn,"(dismissed)"))},config:o})}let at=_t!=null;if($t&&bt===null&&!at){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}let ut=ko(W.id,W.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),b.appendChild(ut),re.push({messageId:W.id,fingerprint:ct,bubble:bt});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(ee.add(W.toolCall.id),wa(W,o,We.composerOverlay));return}}else if(Fe){let Ne=s.find(at=>typeof at.renderApproval=="function")??a,$t=Jn.get(W.id)!==ct,bt=null;if($t&&Ne?.renderApproval){let at=W.id,ut=(Qe,He)=>{let gt=st.current?.getMessages().find(Ut=>Ut.id===at);gt?.approval&&(gt.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(gt.id,Qe):st.current?.resolveApproval(gt.approval,Qe,He))};bt=Ne.renderApproval({message:W,defaultRenderer:()=>ui(W,o),config:o,approve:Qe=>ut("approved",Qe),deny:Qe=>ut("denied",Qe)})}if($t&&bt===null)i.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Jn.delete(W.id),dt=ui(W,o);else{let at=ko(W.id,W.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),b.appendChild(at),Ze.push({messageId:W.id,fingerprint:ct,bubble:bt});return}}else if(Zt)if(W.variant==="reasoning"&&W.reasoning&&Zt.renderReasoning){if(!de)return;dt=Zt.renderReasoning({message:W,defaultRenderer:()=>Wl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Zt.renderToolCall){if(!te)return;dt=Zt.renderToolCall({message:W,defaultRenderer:()=>Bl(W,o),config:o})}else Zt.renderMessage&&(dt=Zt.renderMessage({message:W,defaultRenderer:()=>{let Ne=Rl(W,m,kt,o.messageActions,Ke,{loadingIndicatorRenderer:E,widgetConfig:o});return W.role!=="user"&&jl(Ne,W,o,N),Ne},config:o}));if(!dt&&Se){let Ne=cf(W);if(Ne){let _t=To.get(W.id),$t=_t!==ct,bt=o.wrapComponentDirectiveInBubble!==!1&&Vn.getOptions(Ne.component)?.bubbleChrome!==!1,at=null;if($t){let ut=af(Ne,{config:o,message:W,transform:m});if(ut&&Ne.component==="PersonaArtifactInline"){let Qe=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),He=Qe?.getAttribute("data-artifact-inline")??"",gt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,Ut=He?i.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${gt}"]`)??null:null;Qe&&Ut&&Ut!==Qe&&nu(Ut)&&(Qe===ut?ut=Ut:Qe.replaceWith(Ut))}if(ut)if(bt){let Qe=document.createElement("div");if(Qe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Qe.id=`bubble-${W.id}`,Qe.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Qe.appendChild(He)}Qe.appendChild(ut),at=Qe}else{let Qe=document.createElement("div");if(Qe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Qe.id=`bubble-${W.id}`,Qe.setAttribute("data-message-id",W.id),Qe.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=m({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Qe.appendChild(He)}Qe.appendChild(ut),at=Qe}}if(at||_t!=null){let ut=ko(W.id,W.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),b.appendChild(ut),be.push({messageId:W.id,fingerprint:ct,bubble:at});return}}}if(!dt)if(W.variant==="reasoning"&&W.reasoning){if(!de)return;dt=Wl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!te)return;dt=Bl(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;dt=ui(W,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&W.role==="user"?dt=Ne.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):Ne?.renderAssistantMessage&&W.role==="assistant"?dt=Ne.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):dt=Rl(W,m,Ne,o.messageActions,Ke,{loadingIndicatorRenderer:E,widgetConfig:o}),W.role!=="user"&&dt&&jl(dt,W,o,N)}let Le=ko(W.id,W.role);Le.appendChild(dt),du(So,W.id,ct,Le),b.appendChild(Le)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Fe=ke.getAttribute("data-persona-ask-sheet-for");Fe&&!ee.has(Fe)&&lr(We.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let W=[],ke=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&te){ke.push(Se);return}Se.variant==="reasoning"&&!de||((ke.length>1||Fe&&ke.length>0)&&W.push(ke),ke=[])}),(ke.length>1||Fe&&ke.length>0)&&W.push(ke),W.forEach(Se=>{let wt=Se.map(Ne=>Array.from(b.children).find(_t=>_t instanceof HTMLElement&&_t.getAttribute("data-wrapper-id")===Ne.id)).filter(Ne=>!!Ne);if(wt.length<(Fe?1:2))return;let ct=ko(`tool-group-${Se[0].id}`,"assistant");ct.setAttribute("data-persona-tool-group-row","true");let Bt=document.createElement("div");Bt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Bt.setAttribute("data-persona-tool-group","true");let dt=document.createElement("div");dt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",dt.id=`tool-group-summary-${Se[0].id}`;let Zt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,kt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:Zt,config:o});X(dt,kt)||(dt.textContent=Zt);let Le=document.createElement("div");Le.className="persona-tool-group-stack persona-flex persona-flex-col",Le.id=`tool-group-stack-${Se[0].id}`,Le.setAttribute("data-persona-tool-group-stack","true"),Bt.appendChild(dt),Fe||Bt.appendChild(Le),ct.appendChild(Bt),wt[0].before(ct),wt.forEach((Ne,_t)=>{if(Fe){Ne.remove();return}Ne.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),_t<wt.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Ne),Le.appendChild($t)})})}pu(So,O);let rn=f.some(W=>W.role==="assistant"&&W.streaming),At=f[f.length-1],Et=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(vn&&f.some(W=>W.role==="user")&&!rn&&!Et){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:Ls},ke=s.find(Se=>Se.renderLoadingIndicator),Fe=null;if(ke?.renderLoadingIndicator&&(Fe=ke.renderLoadingIndicator(W)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(W)),Fe===null&&(Fe=Ls()),Fe){let Se=document.createElement("div"),wt=o.loadingIndicator?.showBubble!==!1,ct=o.layout?.messages?.layout??"bubble";Se.className=wt?Il("assistant",ct).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Se.setAttribute("data-typing-indicator","true"),wt&&(Se.style.color="var(--persona-message-assistant-text, var(--persona-text))",ct!=="flat"&&(Se.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Se.appendChild(Fe);let Bt=ko("typing-indicator","assistant");Bt.appendChild(Se),b.appendChild(Bt)}}if(!vn&&f.length>0){let W=f[f.length-1],ke={config:o,lastMessage:W,messageCount:f.length},Fe=s.find(wt=>wt.renderIdleIndicator),Se=null;if(Fe?.renderIdleIndicator&&(Se=Fe.renderIdleIndicator(ke)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(ke)),Se){let wt=document.createElement("div"),ct=o.loadingIndicator?.showBubble!==!1;wt.className=ct?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),wt.setAttribute("data-idle-indicator","true"),wt.appendChild(Se);let Bt=ko("idle-indicator","assistant");Bt.appendChild(wt),b.appendChild(Bt)}}if(_d(b),Va(i,b),Gi(i),re.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of re){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),Go.set(W,ke)))}if(Go.size>0)for(let W of Go.keys())O.has(W)||Go.delete(W);if(be.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of be){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),To.set(W,ke)))}if(To.size>0)for(let W of To.keys())O.has(W)||To.delete(W);if(Ze.length>0)for(let{messageId:W,fingerprint:ke,bubble:Fe}of Ze){let Se=i.querySelector(`#wrapper-${W}`);Se&&(na(Se,G.get(W)??"assistant"),Fe!==null&&(Se.replaceChildren(Fe),Se.setAttribute("data-bubble-fp",ke),Jn.set(W,ke)))}if(Jn.size>0)for(let W of Jn.keys())O.has(W)||Jn.delete(W)},zr=(i,f,m)=>{Jf(i,f,m),hc()},jr=null,Yf=()=>{if(jr)return;let i=m=>{let b=m.composedPath();b.includes(Be)||Xe&&b.includes(Xe)||it(!1,"user")};jr=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},qc=()=>{if(!jr)return;(e.ownerDocument??document).removeEventListener("pointerdown",jr,!0),jr=null};Oe.push(()=>qc());let Vr=null,Zf=()=>{if(Vr)return;let i=m=>{m.key==="Escape"&&(m.isComposing||it(!1,"user"))};Vr=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Kc=()=>{if(!Vr)return;(e.ownerDocument??document).removeEventListener("keydown",Vr,!0),Vr=null};Oe.push(()=>Kc());let qr=!1,Gc=new Set,eg=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Xo=()=>{if(!D())return;let i=We.peekBanner,f=We.peekTextNode;if(!i||!f)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let m=N?.getMessages()??[],b;for(let At=m.length-1;At>=0;At--){let Et=m[At];if(Et.role==="assistant"&&Et.content){b=Et;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let S=b.content,E=!!b.streaming,X=eg(),O=Qa(X),G=O.type!=="none"?vr(O.type,X?.plugins):null,ee=G?.isAnimating?.(b)===!0,pe=G!==null&&(E||ee);pe&&G&&!Gc.has(G.name)&&(Ya(G,e),Gc.add(G.name));let re=pe&&G?.containerClass?G.containerClass:null,be=f.dataset.personaPeekStreamClass??null;be&&be!==re&&(f.classList.remove(be),delete f.dataset.personaPeekStreamClass),re&&be!==re&&(f.classList.add(re),f.dataset.personaPeekStreamClass=re),pe?(f.style.setProperty("--persona-stream-step",`${O.speed}ms`),f.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ue=pe?Xa(S,O.buffer,G,b,E):S;if(pe&&O.placeholder==="skeleton"&&E&&(!Ue||!Ue.trim())){let At=document.createElement("div"),Et=Ss();Et.classList.add("persona-pill-peek__skeleton"),At.appendChild(Et),Va(f,At)}else{let At=Math.max(0,Ue.length-100),Et=Ue.length>100?Ue.slice(-100):Ue,W=ao(Et);if(!pe||!G){let ke=Ue.length>100?`\u2026${Et}`:Et;f.textContent!==ke&&(f.textContent=ke)}else{let ke=W;(G.wrap==="char"||G.wrap==="word")&&(ke=As(W,G.wrap,`peek-${b.id}`,{skipTags:G.skipTags,startIndex:At}));let Fe=document.createElement("div");if(Fe.innerHTML=ke,G.useCaret&&Et.length>0){let Se=Ja(),wt=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ct=wt[wt.length-1];ct?.parentNode?ct.parentNode.insertBefore(Se,ct.nextSibling):Fe.appendChild(Se)}Va(f,Fe),G.onAfterRender?.({container:f,bubble:i,messageId:b.id,message:b,speed:O.speed,duration:O.duration})}}let rn=vn||qr;i.classList.toggle("persona-pill-peek--visible",rn)};if(D()){let i=We.peekBanner;if(i){let b=S=>{S.preventDefault(),S.stopPropagation(),it(!0,"user")};i.addEventListener("pointerdown",b),Oe.push(()=>{i.removeEventListener("pointerdown",b)})}let f=()=>{qr||(qr=!0,Xo())},m=()=>{qr&&(qr=!1,Xo())};ue.addEventListener("pointerenter",f),ue.addEventListener("pointerleave",m),Oe.push(()=>{ue.removeEventListener("pointerenter",f),ue.removeEventListener("pointerleave",m)}),Xe&&(Xe.addEventListener("pointerenter",f),Xe.addEventListener("pointerleave",m),Oe.push(()=>{Xe.removeEventListener("pointerenter",f),Xe.removeEventListener("pointerleave",m)}))}let tg=i=>{let f=o.launcher?.composerBar??{},m=f.expandedSize??"anchored",b=f.bottomOffset??"16px",S=f.collapsedMaxWidth,E=f.expandedMaxWidth??"880px",X=f.expandedTopOffset??"5vh",O=f.modalMaxWidth??"880px",G=f.modalMaxHeight??"min(90vh, 800px)",ee="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",re=Be.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",Xe){let be=Xe.style;be.bottom=b,be.width=S??""}if(i&&m!=="fullscreen"){if(m==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=O,re.maxWidth=ee,re.maxHeight=G,re.height=G;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${b} + ${pe})`,re.top=X,re.width=E,re.maxWidth=ee}},Kr=()=>{if(!_())return;if(D()){let ee=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=Y?"expanded":"collapsed";Be.dataset.state=pe,Be.dataset.expandedSize=ee,Xe&&(Xe.dataset.state=pe,Xe.dataset.expandedSize=ee),Be.style.removeProperty("display"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),tg(Y),me.style.display=Y?"flex":"none",qs(),Y?(Yf(),Zf()):(qc(),Kc()),Xo();return}let i=Dt(o),f=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,b=o.launcher?.mobileFullscreen??!0,S=f.innerWidth<=m,E=b&&S&&M,X=hn(o).reveal;Y?(Be.style.removeProperty("display"),Be.style.display=i?"flex":"",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0"),ue.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Qt&&(Qt.style.display="none")):(i?i&&(X==="overlay"||X==="push")&&!E?(Be.style.removeProperty("display"),Be.style.display="flex",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.setProperty("display","none","important"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.display="",Be.classList.add("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100"),ue.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=i?"none":"":Qt&&(Qt.style.display=i?"none":""))},it=(i,f="user")=>{if(!_()||Y===i)return;let m=Y;Y=i,Kr();let b=(()=>{let E=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,ee=X.innerWidth<=G,pe=Dt(o)&&O&&ee,re=D()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||O&&ee&&M||pe||re})();if(Y&&b){if(!Mn){let E=e.getRootNode(),X=E instanceof ShadowRoot?E.host:e.closest(".persona-host");X&&(Mn=Sl(X,o.launcher?.zIndex??Vt))}En||(En=Tl(e.ownerDocument))}else Y||(Mn?.(),Mn=null,En?.(),En=null);Y&&(Xr(),zc()||(ln()==="follow"?to(!0):$c()));let S={open:Y,source:f,timestamp:Date.now()};Y&&!m?p.emit("widget:opened",S):!Y&&m&&p.emit("widget:closed",S),p.emit("widget:state",{open:Y,launcherEnabled:M,voiceActive:Ve.active,streaming:N.isStreaming()})},Wi=i=>{Je(i?"stop":"send"),q&&(q.disabled=i),Dr.forEach(f=>{f.elements.forEach(m=>{m.toggleAttribute("data-disabled",i),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",i?"true":"false")}),f.buttons.forEach(m=>{m.disabled=i})}),we.dataset.personaComposerStreaming=i?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=i)})},Hi=()=>{Ve.active||z&&z.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Hi(),200)});let Qc=()=>{I.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",H.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",z.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=le.querySelector("[data-persona-intro-card]");if(i){let m=o.copy?.showWelcomeCard!==!1;i.style.display=m?"":"none",m?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!N?.isStreaming()&&(C.textContent=o.copy?.sendButtonLabel??"Send"),z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',z.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{P(f=>({...f,sessionId:i}))}});let Lo=null,ng=()=>{Lo==null&&(Lo=setInterval(()=>{let i=Re.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Lo),Lo=null;return}let f=Date.now();i.forEach(m=>{let b=Number(m.getAttribute("data-tool-elapsed"));b&&(m.textContent=Aa(f-b))})},100))},Bi=(i,f)=>{if(Object.is(i,f))return!0;if(i===null||f===null||typeof i!="object"||typeof f!="object")return!1;if(Array.isArray(i)||Array.isArray(f))return!Array.isArray(i)||!Array.isArray(f)||i.length!==f.length?!1:i.every((X,O)=>Bi(X,f[O]));let m=i,b=f,S=Object.keys(m),E=Object.keys(b);return S.length===E.length&&S.every(X=>Object.prototype.hasOwnProperty.call(b,X)&&Bi(m[X],b[X]))},Xc=i=>{let{content:f,rawContent:m,llmContent:b,...S}=i;return S},Di=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Xl(i),og=(i,f,m)=>{if(i.length!==f.length)return!1;let b=i[m.index],S=f[m.index];return!b||!S||b.id!==m.id||S.id!==m.id?!1:(!Object.is(b.content,S.content)||!Object.is(b.rawContent,S.rawContent)||!Object.is(b.llmContent,S.llmContent))&&Di(b)&&Di(S)&&Bi(Xc(b),Xc(S))},Jc=null,Jo=null,Po=null,Bn=null,oa=i=>{Jc=i;let f,m;Jo=null;for(let S=i.length-1;S>=0;S-=1){let E=i[S];if(!f&&E.role==="user"&&(f=E),!m&&E.role==="assistant"&&(m=E),!Jo&&Di(E)&&(Jo={index:S,id:E.id}),f&&m&&Jo)break}zr(Re,i,Z),bl(Re,yn.artifacts,{suppressTransition:vn}),ng(),Fr(i),to(!vn),Xf(i),i.length===0&&(Ur(),Or=!0,Xs=!1,Js=null,Ys=!1),!Mi||Qs?(Mi=!0,Nr=f?.id??null,Ei=m?.id??null):f&&f.id!==Nr?(Nr=f.id,Kf(f.id)):m&&m.id!==Ei&&Gf(),m&&(Ei=m.id),Qf(i);let b=Ve.lastUserMessageId;f&&f.id!==b&&(Ve.lastUserMessageId=f.id,p.emit("user:message",f)),Ve.lastUserMessageWasVoice=!!f?.viaVoice,Pi(i),Xo()},Fi=()=>{Bn!==null&&(cancelAnimationFrame(Bn),Bn=null);let i=Po;Po=null,i&&oa(i)},Yc=()=>{Bn!==null&&cancelAnimationFrame(Bn),Bn=null,Po=null},rg=i=>{let f=Po??Jc;if(vn&&f&&Jo&&og(f,i,Jo)){Po=i,Bn===null&&(Bn=requestAnimationFrame(()=>{Bn=null;let m=Po;Po=null,m&&oa(m)}));return}if(i.length===0){Yc(),oa(i);return}Fi(),oa(i)};N=new Ia(o,{onMessagesChanged(i){rg(i)},onStatusChanged(i){let f=o.statusIndicator??{};qt(L,(b=>b==="idle"?f.idleText??Lt.idle:b==="connecting"?f.connectingText??Lt.connecting:b==="connected"?f.connectedText??Lt.connected:b==="error"?f.errorText??Lt.error:b==="paused"?f.pausedText??Lt.paused:b==="resuming"?f.resumingText??Lt.resuming:Lt[b])(i),f,i)},onStreamingChanged(i){i||(N?.getMessages().length===0?Yc():Fi()),vn=i,Wi(i),N&&zr(Re,N.getMessages(),Z),i||(to(!0),Rc=!0,N&&Wc(N.getMessages(),po(o))),on(),lc(i?"Responding\u2026":"Response complete."),Xo()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Dn(),Zo();break;case"processing":Dn(),mg();break;case"speaking":Dn(),hg();break;default:i==="idle"&&N.isBargeInActive()?(Dn(),Zo(),q?.setAttribute("aria-label","End voice session")):(Ve.active=!1,Dn(),Hn("system"),xn());break}},onArtifactsState(i){yn=i,i.artifacts.length===0&&(Vo=!1),bl(Re,i.artifacts,{suppressTransition:vn}),Wn(),Pi()},onReconnect(i){let{executionId:f,lastEventId:m}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:f,after:m}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:f,after:m,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:f,after:m})}}),st.current=N,Oe.push(()=>N.cancel());let Ni=null;if(N.onReadAloudChange((i,f)=>{gc=i,mc=f,hc();let m=i??Ni;i&&(Ni=i);let b=m?N.getMessages().find(S=>S.id===m)??null:null;p.emit("message:read-aloud",{messageId:m,message:b,state:f,timestamp:Date.now()}),f==="idle"&&(Ni=null)}),Mi=!0,o.voiceRecognition?.provider?.type==="runtype")try{N.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&N.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ae||o.onSSEEvent)&&N.setSSEEventCallback((i,f)=>{o.onSSEEvent?.(i,f),Te?.processEvent(i,f),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(f)})});let Zc=()=>{o.resume&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(o.resume)};w?w.then(i=>{if(i){if(i.metadata&&(u=Jl(i.metadata),T.syncFromMetadata()),i.messages?.length){Qs=!0;try{N.hydrateMessages(i.messages)}finally{Qs=!1}}i.artifacts?.length&&N.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Zc()):Zc();let ed=()=>{!D()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||it(!0,"auto")},sg=(i,f)=>i?f?{refs:[...i.refs,...f.refs],finalize:async()=>{let[m,b]=await Promise.allSettled([i.finalize(),f.finalize()]),S=[];return m.status==="fulfilled"?S.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),Nb(S)}}:i:f,ag=()=>{let f=z.getInlineMessageFields?.();return f&&f.contentSegments.some(b=>b.kind==="mention")?f.contentSegments:void 0},Gr=!1,ig=async i=>{let f=z.value.trim(),m=Ct?.hasAttachments()??!1,b=f?await(tn?.takeInlineCommand(f)??Promise.resolve(null)):null;if(b?.kind==="action"){z.value="",z.style.height="auto",Qr(),tn?.clear();return}let S=tn?.collectForSubmit()??null,E=b?.kind==="server"?b.mentions:null,X=sg(S,E),O=b?.kind==="prompt"?b.sendText:f,G=!!S&&S.refs.length>0;if(!O&&!m&&!G&&!E)return;ed();let ee;m&&(ee=[],ee.push(...Ct.getContentParts()),O&&ee.push(dr(O)));let pe=b?.kind==="prompt"?void 0:ag();z.value="",z.style.height="auto",Qr(),N.sendMessage(O,{contentParts:ee,mentions:X??void 0,contentSegments:pe,viaVoice:i?.viaVoice}),m&&Ct.clearAttachments(),S&&tn?.clear()},Oi=async i=>{if(!Gr){Gr=!0;try{await ig(i)}finally{Gr=!1}}},td=i=>{if(i.preventDefault(),N.isStreaming()){N.cancel(),Te?.reset(),qe?.update();return}Gr||Oi()},lg=()=>o.features?.composerHistory!==!1,_i={...xl},$i=!1,Qr=()=>{_i={...xl}},cg=()=>N.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),dg=i=>{if(!z)return;$i=!0,z.value=i,z.dispatchEvent(new Event("input",{bubbles:!0})),$i=!1;let f=z.value.length;z.setSelectionRange(f,f)},pg=i=>{$i||(i.isComposing||tn?.handleInput(i.inputType??void 0),Qr())},ug=i=>{if(z&&!(!i.isComposing&&tn?.handleKeydown(i))){if(lg()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let f=z.selectionStart===0&&z.selectionEnd===0,m=au({direction:i.key==="ArrowUp"?"up":"down",history:cg(),currentValue:z.value,atStart:f,state:_i});if(_i=m.state,m.handled){i.preventDefault(),m.value!==void 0&&dg(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(N.isStreaming()){i.preventDefault();return}if(Gr){i.preventDefault();return}Qr(),i.preventDefault(),C.click()}}},nd=i=>{i.key!=="Escape"||i.isComposing||N.isStreaming()&&i.composedPath().includes(me)&&(N.cancel(),Te?.reset(),qe?.update(),Qr(),i.preventDefault(),i.stopImmediatePropagation())},fg=async i=>{if(o.attachments?.enabled!==!0||!Ct)return;let f=Hb(i.clipboardData);f.length!==0&&(i.preventDefault(),await Ct.handleFiles(f))},pn=null,kn=!1,Yo=null,yt=null,od=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ra=(i="user")=>{if(kn||N.isStreaming())return;let f=od();if(!f)return;pn=new f;let b=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let S=z.value;pn.onresult=E=>{let X="",O="";for(let ee=0;ee<E.results.length;ee++){let pe=E.results[ee],re=pe[0].transcript;pe.isFinal?X+=re+" ":O=re}let G=S+X+O;z.value=G,Yo&&clearTimeout(Yo),(X||O)&&(Yo=window.setTimeout(()=>{z.value.trim()&&pn&&kn&&(no(),Oi({viaVoice:!0}))},b))},pn.onerror=E=>{E.error!=="no-speech"&&no()},pn.onend=()=>{if(kn){let E=z.value.trim();E&&E!==S.trim()&&Oi({viaVoice:!0}),no()}};try{if(pn.start(),kn=!0,Ve.active=!0,i!=="system"&&(Ve.manuallyDeactivated=!1),Hn(i),xn(),q){let E=o.voiceRecognition??{};yt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let X=E.recordingBackgroundColor,O=E.recordingIconColor,G=E.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let ee=q.querySelector("svg");ee&&ee.setAttribute("stroke",O)}G&&(q.style.borderColor=G),q.setAttribute("aria-label","Stop voice recognition")}}catch{no("system")}},no=(i="user")=>{if(kn){if(kn=!1,Yo&&(clearTimeout(Yo),Yo=null),pn){try{pn.stop()}catch{}pn=null}if(Ve.active=!1,Hn(i),xn(),q){if(q.classList.remove("persona-voice-recording"),yt){q.style.backgroundColor=yt.backgroundColor,q.style.color=yt.color,q.style.borderColor=yt.borderColor;let f=q.querySelector("svg");f&&f.setAttribute("stroke",yt.color||"currentColor"),yt=null}q.setAttribute("aria-label","Start voice recognition")}}},gg=(i,f)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),b=i?.provider?.type==="runtype",S=i?.provider?.type==="custom";if(!(m||b||S))return null;let X=y("div","persona-send-button-wrapper"),O=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button";let G=i?.tooltipText??"Start voice recognition";O.setAttribute("aria-label",G);let ee=i?.iconName??"mic",pe=f?.size??"40px",re=i?.iconSize??pe,be=parseFloat(re)||24,Ue=i?.backgroundColor??f?.backgroundColor,lt=i?.iconColor??f?.textColor;O.style.width=re,O.style.height=re,O.style.minWidth=re,O.style.minHeight=re,O.style.fontSize="18px",O.style.lineHeight="1",lt?O.style.color=lt:O.style.color="var(--persona-text, #111827)";let rn=ae(ee,be,lt||"currentColor",1.5);rn?O.appendChild(rn):O.textContent="\u{1F3A4}",Ue?O.style.backgroundColor=Ue:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),X.appendChild(O);let At=i?.showTooltip??!1;return Ot({anchor:O,trigger:X,text:()=>O.getAttribute("aria-label")??G,enabled:At}),{micButton:O,micButtonWrapper:X}},Ui=()=>{if(!q||yt)return;let i=o.voiceRecognition??{};yt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},zi=(i,f)=>{if(!q)return;let m=q.querySelector("svg");m&&m.remove();let b=yt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=ae(i,b,f,1.5);S&&q.appendChild(S)},sa=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Zo=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=i.recordingBackgroundColor,m=i.recordingIconColor,b=i.recordingBorderColor;if(sa(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",q.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let S=q.querySelector("svg");S&&S.setAttribute("stroke",m)}b&&(q.style.borderColor=b),q.setAttribute("aria-label","Stop voice recognition")},mg=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=N.getVoiceInterruptionMode(),m=i.processingIconName??"loader",b=i.processingIconColor??yt?.color??"",S=i.processingBackgroundColor??yt?.backgroundColor??"",E=i.processingBorderColor??yt?.borderColor??"";sa(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=S,q.style.borderColor=E;let X=b||"currentColor";q.style.color=X,zi(m,X),q.setAttribute("aria-label","Processing voice input"),f==="none"&&(q.style.cursor="default")},hg=()=>{if(!q)return;Ui();let i=o.voiceRecognition??{},f=N.getVoiceInterruptionMode(),m=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",b=i.speakingIconName??m,S=i.speakingIconColor??(f==="barge-in"?i.recordingIconColor??yt?.color??"":yt?.color??""),E=i.speakingBackgroundColor??(f==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":yt?.backgroundColor??""),X=i.speakingBorderColor??(f==="barge-in"?i.recordingBorderColor??"":yt?.borderColor??"");sa(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=E,q.style.borderColor=X;let O=S||"currentColor";q.style.color=O,zi(b,O);let G=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",G),f==="none"&&(q.style.cursor="default"),f==="barge-in"&&q.classList.add("persona-voice-recording")},Dn=()=>{q&&(sa(),yt&&(q.style.backgroundColor=yt.backgroundColor??"",q.style.color=yt.color??"",q.style.borderColor=yt.borderColor??"",zi(yt.iconName,yt.color||"currentColor"),yt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},aa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=N.getVoiceStatus(),f=N.getVoiceInterruptionMode();if(f==="none"&&(i==="processing"||i==="speaking"))return;if(f==="cancel"&&(i==="processing"||i==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,xn(),Hn("user"),Dn()});return}N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Ve.manuallyDeactivated=!N.isVoiceActive(),xn(),Hn("user"),N.isVoiceActive()?Zo():Dn()});return}if(kn){let i=z.value.trim();Ve.manuallyDeactivated=!0,xn(),no("user"),i&&(z.value="",z.style.height="auto",N.sendMessage(i))}else Ve.manuallyDeactivated=!1,xn(),ra("user")};dc=aa,q&&(q.addEventListener("click",aa),Oe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()&&N.toggleVoice(),Dn()):no("system"),q&&q.removeEventListener("click",aa)}));let yg=p.on("assistant:complete",()=>{Bc&&(Ve.active||Ve.manuallyDeactivated||Bc==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{!Ve.active&&!Ve.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("auto"),N.isVoiceActive()&&Zo()}):ra("auto"))},600))});Oe.push(yg);let bg=p.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});Oe.push(bg);let rd=()=>{it(!Y,"user")},Ft=null,Qt=null;if(M&&!D()){let{instance:i,element:f}=kl({config:o,plugins:s,onToggle:rd});Ft=i,i||(Qt=f)}Ft?e.appendChild(Ft.element):Qt&&e.appendChild(Qt),Kr(),Fr(),Qc(),Wi(N.isStreaming()),zc()||(ln()==="follow"?to(!0):$c()),$f(),j&&(!M||D()?setTimeout(()=>Hi(),0):Y&&setTimeout(()=>Hi(),200));let Xr=()=>{if(D()){jo(),Kr();return}let i=Dt(o),f=o.launcher?.sidebarMode??!1,m=i||f||(o.launcher?.fullHeight??!1),b=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640,X=b.innerWidth<=E,O=S&&X&&M;try{if(O){Ir(),Rr=Vs();return}let G=!1;ne&&(ne=!1,Ir(),G=!0);let ee=Vs();if(!G&&ee!==Rr&&(Ir(),G=!0),Rr=ee,G&&Ai(),!M&&!i){ue.style.height="",ue.style.width="";return}if(!f&&!i){let re=o?.launcher?.width??o?.launcherWidth??jn;ue.style.width=re,ue.style.maxWidth=re}if(js(),!m){let pe=b.innerHeight,re=64,be=o.launcher?.heightOffset??0,Ue=Math.max(200,pe-re),lt=Math.min(640,Ue),Ze=Math.max(200,lt-be);ue.style.height=`${Ze}px`}}finally{if(jo(),Kr(),Y&&M){let ee=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),pe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,be=Dt(o)&&re&&ee,Ue=pe||re&&ee&&M||be;if(Ue&&!En){let lt=e.getRootNode(),Ze=lt instanceof ShadowRoot?lt.host:e.closest(".persona-host");Ze&&!Mn&&(Mn=Sl(Ze,o.launcher?.zIndex??Vt)),En=Tl(e.ownerDocument)}else Ue||(Mn?.(),Mn=null,En?.(),En=null)}}};Xr();let sd=e.ownerDocument.defaultView??window;if(sd.addEventListener("resize",Xr),Oe.push(()=>sd.removeEventListener("resize",Xr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{jo()});i.observe(we),Oe.push(()=>i.disconnect())}cn=le.scrollTop;let ad=Pn(le),id=()=>{let i=le.scrollTop,f=Pn(le),m=f<ad;if(ad=f,!Gn()){cn=i,on();return}let{action:b,nextLastScrollTop:S}=Ka({following:nn.isFollowing(),currentScrollTop:i,lastScrollTop:cn,nearBottom:ho(le,Zs),userScrollThreshold:Of,isAutoScrolling:dn||Gs||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=S,b==="resume"){ta()||eo();return}b==="pause"&&$r()};if(le.addEventListener("scroll",id,{passive:!0}),Oe.push(()=>le.removeEventListener("scroll",id)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{qf(),Gi(Re)});i.observe(Re),i.observe(le),Oe.push(()=>i.disconnect())}let ld=()=>{Gn()&&nn.isFollowing()&&ta()&&$r()},cd=le.ownerDocument;cd.addEventListener("selectionchange",ld),Oe.push(()=>{cd.removeEventListener("selectionchange",ld)});let vg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dd=i=>{vg.has(i.key)&&(Eo(),sc()&&Gn()&&nn.isFollowing()&&$r())},pd=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Eo(),sc()&&Gn()&&nn.isFollowing()&&$r())};le.addEventListener("keydown",dd),le.addEventListener("focusin",pd),Oe.push(()=>{le.removeEventListener("keydown",dd),le.removeEventListener("focusin",pd)});let ud=i=>{if(i.deltaY!==0&&Eo(),!Gn())return;let f=Ga({following:nn.isFollowing(),deltaY:i.deltaY,nearBottom:ho(le,Zs),resumeWhenNearBottom:!0});f==="pause"?$r():f==="resume"&&!ta()&&eo()};le.addEventListener("wheel",ud,{passive:!0}),le.addEventListener("touchmove",Eo,{passive:!0}),le.addEventListener("pointerdown",Eo,{passive:!0}),Oe.push(()=>{le.removeEventListener("touchmove",Eo),le.removeEventListener("pointerdown",Eo)}),Oe.push(()=>le.removeEventListener("wheel",ud)),Tt.addEventListener("click",()=>{Ur(),le.scrollTop=le.scrollHeight,cn=le.scrollTop,eo(),to(!0),on()}),Oe.push(()=>Tt.remove()),Oe.push(()=>{Nc(),Ur()});let fd=()=>{B&&(Co&&(B.removeEventListener("click",Co),Co=null),_()?(B.style.display="",Co=()=>{it(!1,"user")},B.addEventListener("click",Co)):B.style.display="none")};fd(),(()=>{let{clearChatButton:i}=We;i&&i.addEventListener("click",()=>{N.clearMessages(),So.clear(),eo(),lr(We.composerOverlay);try{localStorage.removeItem(Tr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Tr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),c?.clear&&Li(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ae?.clear(),Te?.reset(),qe?.update()})})(),h&&h.addEventListener("submit",td);let gd=[["keydown",ug],["input",pg],["paste",fg],["focus",Rf]],md=i=>{if(i)for(let[f,m]of gd)i.addEventListener(f,m)},hd=i=>{if(i)for(let[f,m]of gd)i.removeEventListener(f,m)};md(z),tn?.onComposerSwap((i,f)=>{hd(f),z=i,md(i)});let yd=e.ownerDocument??document;yd.addEventListener("keydown",nd,!0);let bd="persona-attachment-drop-active",Jr=0,ji=()=>{Jr=0,me.classList.remove(bd)},er=()=>o.attachments?.enabled===!0&&Ct!==null,vd=i=>{!hi(i.dataTransfer)||!er()||(Jr++,Jr===1&&me.classList.add(bd))},wd=i=>{!hi(i.dataTransfer)||!er()||(Jr--,Jr<=0&&ji())},xd=i=>{!hi(i.dataTransfer)||!er()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Cd=i=>{if(!hi(i.dataTransfer)||!er())return;i.preventDefault(),i.stopPropagation(),ji();let f=Array.from(i.dataTransfer.files??[]);f.length!==0&&Ct.handleFiles(f)},oo=!0;me.addEventListener("dragenter",vd,oo),me.addEventListener("dragleave",wd,oo),e.addEventListener("dragover",xd,oo),e.addEventListener("drop",Cd,oo);let ia=e.ownerDocument,Ad=i=>{er()&&i.preventDefault()},Sd=i=>{er()&&i.preventDefault()};ia.addEventListener("dragover",Ad),ia.addEventListener("drop",Sd),Oe.push(()=>{h&&h.removeEventListener("submit",td),hd(z),yd.removeEventListener("keydown",nd,!0),tn?.destroy()}),Oe.push(()=>{me.removeEventListener("dragenter",vd,oo),me.removeEventListener("dragleave",wd,oo),e.removeEventListener("dragover",xd,oo),e.removeEventListener("drop",Cd,oo),ia.removeEventListener("dragover",Ad),ia.removeEventListener("drop",Sd),ji()}),Oe.push(()=>{N.cancel()}),Ft?Oe.push(()=>{Ft?.destroy()}):Qt&&Oe.push(()=>{Qt?.remove()});let Mt={update(i){let f=o.toolCall,m=o.messageActions,b=o.layout?.messages,S=o.colorScheme,E=o.loadingIndicator,X=o.iterationDisplay,O=o.features?.showReasoning,G=o.features?.showToolCalls,ee=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=nf({...o,features:r},i),r=o.features,o=Ul(o),qs(),ys(e,o),Ws(e,o),Hs(e,o),Wn(),o.colorScheme!==S&&Cc();let be=ql.getForInstance(o.plugins);s.length=0,s.push(...be),M=o.launcher?.enabled??!0,U=o.launcher?.autoExpand??!1,de=o.features?.showReasoning??!0,te=o.features?.showToolCalls??!0,J=o.features?.scrollToBottom??{};let Ue=ln();fe=o.features?.scrollBehavior??{},Ue!==ln()&&(Ur(),eo()),cc(),on();let lt=ie;if(ie=o.features?.showEventStreamToggle??!1,ie&&!lt){if(Ae||(xe=new Is(ye),Ae=new Ps(ve,xe),Te=Te??new Rs,xe.open().then(()=>Ae?.restore()).catch(()=>{}),N.setSSEEventCallback((oe,je)=>{o.onSSEEvent?.(oe,je),Te?.processEvent(oe,je),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(je)})})),!Ye&&Ee){let oe=o.features?.eventStream?.classNames,je="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(oe?.toggleButton?" "+oe.toggleButton:"");Ye=y("button",je),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Jt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let ft=ae("activity","18px","currentColor",1.5);ft&&Ye.appendChild(ft);let et=We.clearChatButtonWrapper,ot=We.closeButtonWrapper,zt=et||ot;zt&&zt.parentNode===Ee?Ee.insertBefore(Ye,zt):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{ze?Lr():vi()})}}else!ie&<&&(Lr(),Ye&&(Ye.remove(),Ye=null),Ae?.clear(),xe?.destroy(),Ae=null,xe=null,Te?.reset(),Te=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Qt&&(Qt.remove(),Qt=null),o.launcher?.enabled!==!1&&!Ft&&!Qt){let{instance:oe,element:je}=kl({config:o,plugins:s,onToggle:rd});Ft=oe,oe||(Qt=je),e.appendChild(je)}Ft&&Ft.update(o),Q&&o.launcher?.title!==void 0&&(Q.textContent=o.launcher.title),se&&o.launcher?.subtitle!==void 0&&(se.textContent=o.launcher.subtitle);let Ze=o.layout?.header;if(Ze?.layout!==K&&Ee){let oe=Ze?ni(o,Ze,{showClose:_(),onClose:()=>it(!1,"user")}):No({config:o,showClose:_(),onClose:()=>it(!1,"user")});xt.replaceHeader(oe),Ee=xt.header.element,R=xt.header.iconHolder,Q=xt.header.headerTitle,se=xt.header.headerSubtitle,B=xt.header.closeButton,K=Ze?.layout}else if(Ze){if(R&&(R.style.display=Ze.showIcon===!1?"none":""),Q&&(Q.style.display=Ze.showTitle===!1?"none":""),se&&(se.style.display=Ze.showSubtitle===!1?"none":""),B){let oe=_()&&Ze.showCloseButton!==!1;B.style.display=oe?"":"none"}if(We.clearChatButtonWrapper){let oe=Ze.showClearChat;if(oe!==void 0){We.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:je}=We;je&&!je.classList.contains("persona-absolute")&&(oe?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=At?"":"none");let Et=o.layout?.showFooter!==!1;we&&(we.style.display=Et?"":"none"),jo(),on(),M!==V?M?it(U,"auto"):(Y=!0,Kr()):U!==A&&it(U,"auto"),A=U,V=M,Xr(),fd();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(f),Se=JSON.stringify(o.messageActions)!==JSON.stringify(m),wt=JSON.stringify(o.layout?.messages)!==JSON.stringify(b),ct=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,Bt=o.iterationDisplay!==X,dt=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ee)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Fe||Se||wt||ct||Bt||dt)&&N&&(Ti++,zr(Re,N.getMessages(),Z));let kt=o.features?.streamAnimation?.type;if(kt!==re&&kt&&kt!=="none"){let oe=vr(kt,o.features?.streamAnimation?.plugins);oe&&Ya(oe,e)}let Le=o.launcher??{},Ne=Le.headerIconHidden??!1,_t=o.layout?.header?.showIcon,$t=Ne||_t===!1,bt=Le.headerIconName,at=Le.headerIconSize??"48px";if(R){let oe=me.querySelector(".persona-border-b-persona-divider"),je=oe?.querySelector(".persona-flex-col");if($t)R.style.display="none",oe&&je&&!oe.contains(je)&&oe.insertBefore(je,oe.firstChild);else{if(R.style.display="",R.style.height=at,R.style.width=at,oe&&je&&(oe.contains(R)?R.nextSibling!==je&&(R.remove(),oe.insertBefore(R,je)):oe.insertBefore(R,je)),bt){let et=parseFloat(at)||24,ot=ae(bt,et*.6,"currentColor",1);ot?R.replaceChildren(ot):R.textContent=Le.agentIconText??"\u{1F4AC}"}else if(Le.iconUrl){let et=R.querySelector("img");if(et)et.src=Le.iconUrl,et.style.height=at,et.style.width=at;else{let ot=document.createElement("img");ot.src=Le.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=at,ot.style.width=at,R.replaceChildren(ot)}}else{let et=R.querySelector("svg"),ot=R.querySelector("img");(et||ot)&&R.replaceChildren(),R.textContent=Le.agentIconText??"\u{1F4AC}"}let ft=R.querySelector("img");ft&&(ft.style.height=at,ft.style.width=at)}}let ut=o.layout?.header?.showTitle,Qe=o.layout?.header?.showSubtitle;if(Q&&(Q.style.display=ut===!1?"none":""),se&&(se.style.display=Qe===!1?"none":""),B){let oe=_()&&o.layout?.header?.showCloseButton!==!1;B.style.display=oe?"":"none";let je=Le.closeButtonSize??"32px",ft=Le.closeButtonPlacement??"inline";B.style.height=je,B.style.width=je;let{closeButtonWrapper:et}=We,ot=ft==="top-right",zt=et?.classList.contains("persona-absolute");if(et&&ot!==zt)if(et.remove(),ot)et.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",me.style.position="relative",me.appendChild(et);else{let so=Le.clearChat?.placement??"inline",es=Le.clearChat?.enabled??!0;et.className=es&&so==="inline"?"":"persona-ml-auto";let Td=me.querySelector(".persona-border-b-persona-divider");Td&&Td.appendChild(et)}if(B.style.color=Le.closeButtonColor||Jt.actionIconColor,Le.closeButtonBackgroundColor?(B.style.backgroundColor=Le.closeButtonBackgroundColor,B.classList.remove("hover:persona-bg-gray-100")):(B.style.backgroundColor="",B.classList.add("hover:persona-bg-gray-100")),Le.closeButtonBorderWidth||Le.closeButtonBorderColor){let so=Le.closeButtonBorderWidth||"0px",es=Le.closeButtonBorderColor||"transparent";B.style.border=`${so} solid ${es}`,B.classList.remove("persona-border-none")}else B.style.border="",B.classList.add("persona-border-none");Le.closeButtonBorderRadius?(B.style.borderRadius=Le.closeButtonBorderRadius,B.classList.remove("persona-rounded-full")):(B.style.borderRadius="",B.classList.add("persona-rounded-full")),Le.closeButtonPaddingX?(B.style.paddingLeft=Le.closeButtonPaddingX,B.style.paddingRight=Le.closeButtonPaddingX):(B.style.paddingLeft="",B.style.paddingRight=""),Le.closeButtonPaddingY?(B.style.paddingTop=Le.closeButtonPaddingY,B.style.paddingBottom=Le.closeButtonPaddingY):(B.style.paddingTop="",B.style.paddingBottom="");let sn=Le.closeButtonIconName??"x",Cn=Le.closeButtonIconText??"\xD7";B.innerHTML="";let Nt=ae(sn,"28px","currentColor",1);Nt?(Nt.style.display="block",B.appendChild(Nt)):B.textContent=Cn;let jt=Le.closeButtonTooltipText??"Close chat",Nn=Le.closeButtonShowTooltip??!0;B.setAttribute("aria-label",jt),et&&Ot({anchor:B,trigger:et,text:()=>B?.getAttribute("aria-label")??jt,enabled:Nn})}let{clearChatButton:He,clearChatButtonWrapper:gt}=We;if(He){let oe=Le.clearChat??{},je=oe.enabled??!0,ft=o.layout?.header?.showClearChat,et=ft!==void 0?ft:je,ot=oe.placement??"inline";if(gt){gt.style.display=et?"":"none";let{closeButtonWrapper:zt}=We;!D()&&zt&&!zt.classList.contains("persona-absolute")&&(et?zt.classList.remove("persona-ml-auto"):zt.classList.add("persona-ml-auto"));let sn=ot==="top-right",Cn=gt.classList.contains("persona-absolute");if(!D()&&sn!==Cn&&et){if(gt.remove(),sn)gt.className="persona-absolute persona-top-4 persona-z-50",gt.style.right="48px",me.style.position="relative",me.appendChild(gt);else{gt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gt.style.right="";let jt=me.querySelector(".persona-border-b-persona-divider"),Nn=We.closeButtonWrapper;jt&&Nn&&Nn.parentElement===jt?jt.insertBefore(gt,Nn):jt&&jt.appendChild(gt)}let Nt=We.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(sn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(et){if(!D()){let so=oe.size??"32px";He.style.height=so,He.style.width=so}let zt=oe.iconName??"refresh-cw",sn=oe.iconColor??"";He.style.color=sn||Jt.actionIconColor,He.innerHTML="";let Cn=D()?"14px":"20px",Nt=ae(zt,Cn,"currentColor",1);if(Nt&&(Nt.style.display="block",He.appendChild(Nt)),oe.backgroundColor?(He.style.backgroundColor=oe.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let so=oe.borderWidth||"0px",es=oe.borderColor||"transparent";He.style.border=`${so} solid ${es}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");oe.borderRadius?(He.style.borderRadius=oe.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),oe.paddingX?(He.style.paddingLeft=oe.paddingX,He.style.paddingRight=oe.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),oe.paddingY?(He.style.paddingTop=oe.paddingY,He.style.paddingBottom=oe.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let jt=oe.tooltipText??"Clear chat",Nn=oe.showTooltip??!0;He.setAttribute("aria-label",jt),gt&&Ot({anchor:He,trigger:gt,text:()=>He?.getAttribute("aria-label")??jt,enabled:Nn})}}let Ut=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Gl],fn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick];T=Ql({parsers:Ut,handlers:fn,getSessionMetadata:x,updateSessionMetadata:P,emit:p.emit,documentRef:typeof document<"u"?document:null}),Z=ff(o,T,ce),N.updateConfig(o),zr(Re,N.getMessages(),Z),Fr(),Qc(),Wi(N.isStreaming());let Yr=o.voiceRecognition?.enabled===!0,la=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),St=o.voiceRecognition?.provider?.type==="runtype";if(Yr&&(la||St))if(!q||!$e){let oe=gg(o.voiceRecognition,o.sendButton);oe&&(q=oe.micButton,$e=oe.micButtonWrapper,tt.insertBefore($e,$),q.addEventListener("click",aa),q.disabled=N.isStreaming())}else{let oe=o.voiceRecognition??{},je=o.sendButton??{},ft=oe.iconName??"mic",et=je.size??"40px",ot=oe.iconSize??et,zt=parseFloat(ot)||24;q.style.width=ot,q.style.height=ot,q.style.minWidth=ot,q.style.minHeight=ot;let sn=oe.iconColor??je.textColor;q.innerHTML="";let Cn=ae(ft,zt,sn||"currentColor",1.5);Cn?q.appendChild(Cn):q.textContent="\u{1F3A4}";let Nt=oe.backgroundColor??je.backgroundColor;Nt?q.style.backgroundColor=Nt:q.style.backgroundColor="",sn?q.style.color=sn:q.style.color="var(--persona-text, #111827)",oe.borderWidth?(q.style.borderWidth=oe.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),oe.borderColor?q.style.borderColor=oe.borderColor:q.style.borderColor="",oe.paddingX?(q.style.paddingLeft=oe.paddingX,q.style.paddingRight=oe.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),oe.paddingY?(q.style.paddingTop=oe.paddingY,q.style.paddingBottom=oe.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let jt=oe.tooltipText??"Start voice recognition",Nn=oe.showTooltip??!1;q.setAttribute("aria-label",jt),$e&&Ot({anchor:q,trigger:$e,text:()=>q?.getAttribute("aria-label")??jt,enabled:Nn}),$e.style.display="",q.disabled=N.isStreaming()}else q&&$e&&($e.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()&&N.toggleVoice():kn&&no());if(o.attachments?.enabled===!0){if(!Ht||!De){let oe=o.attachments??{},ft=(o.sendButton??{}).size??"40px";Gt||(Gt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Gt.style.display="none",h.insertBefore(Gt,z)),vt||(vt=document.createElement("input"),vt.type="file",vt.accept=(oe.allowedTypes??zn).join(","),vt.multiple=(oe.maxFiles??4)>1,vt.style.display="none",vt.setAttribute("aria-label","Attach files"),h.insertBefore(vt,z)),Ht=y("div","persona-send-button-wrapper"),De=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),De.type="button",De.setAttribute("aria-label",oe.buttonTooltipText??"Attach file");let et=oe.buttonIconName??"paperclip",ot=ft,zt=parseFloat(ot)||40,sn=Math.round(zt*.6);De.style.width=ot,De.style.height=ot,De.style.minWidth=ot,De.style.minHeight=ot,De.style.fontSize="18px",De.style.lineHeight="1";let Cn=ae(et,sn,"currentColor",1.5);Cn?De.appendChild(Cn):De.textContent="\u{1F4CE}",De.addEventListener("click",jt=>{jt.preventDefault(),vt?.click()}),Ht.appendChild(De);let Nt=oe.buttonTooltipText??"Attach file";Ot({anchor:De,trigger:Ht,text:()=>De?.getAttribute("aria-label")??Nt}),_e?_e.append(Ht):h.appendChild(Ht),!Ct&&vt&&Gt&&(Ct=gs.fromConfig(oe),Ct.setPreviewsContainer(Gt),vt.addEventListener("change",async()=>{Ct&&vt?.files&&(await Ct.handleFileSelect(vt.files),vt.value="")}))}else{Ht.style.display="";let oe=o.attachments??{};vt&&(vt.accept=(oe.allowedTypes??zn).join(","),vt.multiple=(oe.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}if(me.querySelector(".persona-attachment-drop-overlay")?.remove(),me.appendChild(gf(o.attachments?.dropOverlay)),De){let oe=o.attachments??{},je=oe.buttonTooltipText??"Attach file";De.setAttribute("aria-label",je),De.textContent="";let ft=parseFloat(o.sendButton?.size??"40px")||40,et=ae(oe.buttonIconName??"paperclip",Math.round(ft*.6),"currentColor",1.5);et?De.appendChild(et):De.textContent="\u{1F4CE}",Ht&&Ot({anchor:De,trigger:Ht,text:()=>De?.getAttribute("aria-label")??je})}}else Ht&&(Ht.style.display="none"),Ct&&Ct.clearAttachments(),me.querySelector(".persona-attachment-drop-overlay")?.remove();let Rt=o.sendButton??{},Zr=Rt.useIcon??!1,da=Rt.iconText??"\u2191",tr=Rt.iconName,pa=Rt.tooltipText??"Send message",Vi=Rt.showTooltip??!1,Io=Rt.size??"40px",Fn=Rt.backgroundColor,Ro=Rt.textColor;if(Zr){if(C.style.width=Io,C.style.height=Io,C.style.minWidth=Io,C.style.minHeight=Io,C.style.fontSize="18px",C.style.lineHeight="1",Ro?C.style.color=Ro:C.style.color="var(--persona-button-primary-fg, #ffffff)",!N.isStreaming())if(C.innerHTML="",tr){let oe=parseFloat(Io)||24,je=Ro?.trim()||"currentColor",ft=ae(tr,oe,je,2);ft?C.appendChild(ft):C.textContent=da}else C.textContent=da;C.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Fn?(C.style.backgroundColor=Fn,C.classList.remove("persona-bg-persona-primary")):(C.style.backgroundColor="",C.classList.add("persona-bg-persona-primary"))}else C.textContent=o.copy?.sendButtonLabel??"Send",C.style.width="",C.style.height="",C.style.minWidth="",C.style.minHeight="",C.style.fontSize="",C.style.lineHeight="",C.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Fn?(C.style.backgroundColor=Fn,C.classList.remove("persona-bg-persona-accent")):C.classList.add("persona-bg-persona-accent"),Ro?C.style.color=Ro:C.classList.add("persona-text-white");Rt.borderWidth?(C.style.borderWidth=Rt.borderWidth,C.style.borderStyle="solid"):(C.style.borderWidth="",C.style.borderStyle=""),Rt.borderColor?C.style.borderColor=Rt.borderColor:C.style.borderColor="",Rt.paddingX?(C.style.paddingLeft=Rt.paddingX,C.style.paddingRight=Rt.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),Rt.paddingY?(C.style.paddingTop=Rt.paddingY,C.style.paddingBottom=Rt.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),N.isStreaming()||C.setAttribute("aria-label",pa),$&&Ot({anchor:C,trigger:$,text:()=>C.getAttribute("aria-label")??pa,enabled:Vi});let ua=o.layout?.contentMaxWidth??(D()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ua?(Re.style.maxWidth=ua,Re.style.marginLeft="auto",Re.style.marginRight="auto",Re.style.width="100%",h&&(h.style.maxWidth=ua,h.style.marginLeft="auto",h.style.marginRight="auto"),mt&&(mt.style.maxWidth=ua,mt.style.marginLeft="auto",mt.style.marginRight="auto")):(Re.style.maxWidth="",Re.style.marginLeft="",Re.style.marginRight="",Re.style.width="",h&&(h.style.maxWidth="",h.style.marginLeft="",h.style.marginRight=""),mt&&(mt.style.maxWidth="",mt.style.marginLeft="",mt.style.marginRight=""));let ro=o.statusIndicator??{},wg=ro.visible??!0;if(L.style.display=wg?"":"none",N){let oe=N.getStatus();qt(L,(ft=>ft==="idle"?ro.idleText??Lt.idle:ft==="connecting"?ro.connectingText??Lt.connecting:ft==="connected"?ro.connectedText??Lt.connected:ft==="error"?ro.errorText??Lt.error:Lt[ft])(oe),ro,oe)}L.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xg=ro.align==="left"?"persona-text-left":ro.align==="center"?"persona-text-center":"persona-text-right";L.classList.add(xg)},open(){_()&&it(!0,"api")},close(){_()&&it(!1,"api")},toggle(){_()&&it(!Y,"api")},reconnect(){N.reconnectNow()},clearChat(){Rn=!1,N.clearMessages(),So.clear(),eo();try{localStorage.removeItem(Tr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Tr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c?.clear&&Li(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},T.syncFromMetadata(),Ae?.clear(),Te?.reset(),qe?.update()},setMessage(i){return!z||N.isStreaming()?!1:(!Y&&_()&&it(!0,"system"),z.value=i,z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(N.isStreaming())return!1;let f=i?.trim()||z.value.trim();return f?(!Y&&_()&&it(!0,"system"),z.value="",z.style.height="auto",N.sendMessage(f),!0):!1},startVoiceRecognition(){return N.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()||(!Y&&_()&&it(!0,"system"),Ve.manuallyDeactivated=!1,xn(),N.toggleVoice().then(()=>{Ve.active=N.isVoiceActive(),Hn("user"),N.isVoiceActive()&&Zo()})),!0):kn?!0:od()?(!Y&&_()&&it(!0,"system"),Ve.manuallyDeactivated=!1,xn(),ra("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()?(N.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,xn(),Hn("user"),Dn()}),!0):!1:kn?(Ve.manuallyDeactivated=!0,xn(),no("user"),!0):!1},injectMessage(i){return!Y&&_()&&it(!0,"system"),N.injectMessage(i)},injectAssistantMessage(i){!Y&&_()&&it(!0,"system");let f=N.injectAssistantMessage(i);return ge&&(ge=!1,he&&(clearTimeout(he),he=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),f},injectUserMessage(i){return!Y&&_()&&it(!0,"system"),N.injectUserMessage(i)},injectSystemMessage(i){return!Y&&_()&&it(!0,"system"),N.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&_()&&it(!0,"system"),N.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&_()&&it(!0,"system"),N.injectComponentDirective(i)},injectTestMessage(i){!Y&&_()&&it(!0,"system"),N.injectTestEvent(i)},async connectStream(i,f){return N.connectStream(i,f)},__pushEventStreamEvent(i){Ae&&(Te?.processEvent(i.type,i.payload),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ie||!Ae||vi()},hideEventStream(){ze&&Lr()},isEventStreamVisible(){return ze},showArtifacts(){Yt(o)&&(Rn=!1,Vo=!0,Wn(),Ge?.setMobileOpen(!0))},hideArtifacts(){Yt(o)&&(Rn=!0,Wn())},upsertArtifact(i){return Yt(o)?(io(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Rn=!1,Vo=!0),N.upsertArtifact(i)):null},selectArtifact(i){Yt(o)&&N.selectArtifact(i)},clearArtifacts(){Yt(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return M&&!Y&&!D()||!z?!1:(z.focus(),!0)},async resolveApproval(i,f,m){let S=N.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===i);if(!S?.approval)throw new Error(`Approval not found: ${i}`);if(S.approval.toolType==="webmcp"){N.resolveWebMcpApproval(S.id,f);return}return N.resolveApproval(S.approval,f,m)},setFollowUpSuggestions(i){Ff(i)},clearFollowUpSuggestions(){Hc()},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){P(i)},on(i,f){return p.on(i,f)},off(i,f){p.off(i,f)},isOpen(){return _()&&Y},isVoiceActive(){return Ve.active},toggleReadAloud(i){N.toggleReadAloud(i)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(i){return N.getReadAloudState(i)},onReadAloudChange(i){return N.onReadAloudChange(i)},getState(){return{open:_()&&Y,launcherEnabled:M,voiceActive:Ve.active,streaming:N.isStreaming()}},showCSATFeedback(i){!Y&&_()&&it(!0,"system");let f=Re.querySelector(".persona-feedback-container");f&&f.remove();let m=df({onSubmit:async(b,S)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});Re.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&_()&&it(!0,"system");let f=Re.querySelector(".persona-feedback-container");f&&f.remove();let m=pf({onSubmit:async(b,S)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(b,S),i?.onSubmit?.(b,S)},onDismiss:i?.onDismiss,...i});Re.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,f){return N.submitCSATFeedback(i,f)},async submitNPSFeedback(i,f){return N.submitNPSFeedback(i,f)},destroy(){Fi(),Lo!=null&&(clearInterval(Lo),Lo=null),Oe.forEach(i=>i()),Be.remove(),Xe?.remove(),Ft?.destroy(),Qt?.remove(),Co&&B.removeEventListener("click",Co)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,f={controller:Mt,getMessages:Mt.getMessages,getStatus:Mt.getStatus,getMetadata:Mt.getPersistentMetadata,updateMetadata:Mt.updatePersistentMetadata,clearHistory:()=>Mt.clearChat(),setVoiceActive:m=>m?Mt.startVoiceRecognition():Mt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,Oe.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.focusInput()};if(window.addEventListener("persona:focusInput",f),Oe.push(()=>{window.removeEventListener("persona:focusInput",f)}),ie){let O=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===i)&&Mt.showEventStream()},G=ee=>{let pe=ee.detail;(!pe?.instanceId||pe.instanceId===i)&&Mt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",G),Oe.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",G)})}let m=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.showArtifacts()},b=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.hideArtifacts()},S=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||G?.artifact&&Mt.upsertArtifact(G.artifact)},E=O=>{let G=O.detail;G?.instanceId&&G.instanceId!==i||typeof G?.id=="string"&&Mt.selectArtifact(G.id)},X=O=>{let G=O.detail;(!G?.instanceId||G.instanceId===i)&&Mt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",X),Oe.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",X)})}let un=Bb(o.persistState);if(un&&_()){let i=Db(un.storage),f=`${un.keyPrefix}widget-open`,m=`${un.keyPrefix}widget-voice`,b=`${un.keyPrefix}widget-voice-mode`;if(i){let S=un.persist?.openState&&i.getItem(f)==="true",E=un.persist?.voiceState&&i.getItem(m)==="true",X=un.persist?.voiceState&&i.getItem(b)==="true";if(S&&setTimeout(()=>{Mt.open(),setTimeout(()=>{if(E||X)Mt.startVoiceRecognition();else if(un.persist?.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),un.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(f,"true")}),p.on("widget:closed",()=>{i.setItem(f,"false")})),un.persist?.voiceState&&(p.on("voice:state",O=>{i.setItem(m,O.active?"true":"false")}),p.on("user:message",O=>{i.setItem(b,O.viaVoice?"true":"false")})),un.clearOnChatClear){let O=()=>{i.removeItem(f),i.removeItem(m),i.removeItem(b)},G=()=>O();window.addEventListener("persona:clear-chat",G),Oe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(g&&_()&&setTimeout(()=>{Mt.open()},0),Xo(),!Nf){let i=ga(()=>{N&&(Ti++,So.clear(),zr(Re,N.getMessages(),Z))});Oe.push(i)}return Mt};var hf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},Ob=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},_b=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},$b=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},yf=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},tc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},bf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",tc(e)},Yl=e=>{e.style.transition=""},Zl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},ec=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},yi=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ub=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},zb=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},jb=e=>{let t=gr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Xt(t,r)??r;return{inset:o(n?.inset,Ba),canvasBackground:o(n?.canvasBackground,Da)}},vf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Vb=(e,t,n,o,r,s,a,l)=>{let p=hn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";Ub(e,t,n,o,d),zb(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,P=g!=null?g.innerWidth<=x:!1;if(v&&P&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Zl(t),Yl(o),bf(o),ec(n),yi(r,o),vf(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Vt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),bf(o),Ob(o,p.maxHeight),vf(o,c&&a,u,w),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Zl(t),Yl(o),ec(n),yi(r,o);let k=p.animate?"transform 180ms ease":"none",T=p.side==="right"?"translateX(100%)":"translateX(-100%)",M=a?"translateX(0)":T;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=k,o.style.transform=M,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Yl(o),tc(o),yi(r,o);let k=hf(p.width,e.clientWidth),T=Math.max(0,e.clientWidth),M=p.animate?"margin-left 180ms ease":"none",U=p.side==="right"?a?-k:0:a?0:-k;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${T+k}px`,t.style.transition=M,t.style.marginLeft=`${U}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${T}px`,n.style.maxWidth=`${T}px`,n.style.minWidth=`${T}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Zl(t),tc(o),ec(n),yi(r,o);let k=p.reveal==="emerge";k?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let T=a?p.width:"0px",M=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",U=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${T}`,o.style.width=T,o.style.maxWidth=T,o.style.minWidth=T,o.style.minHeight="0",_b(o,p.maxHeight),o.style.overflow=k||U?"hidden":"visible",o.style.transition=M,k){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let j=c?`calc(${hf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=j,r.style.minWidth=j,r.style.maxWidth=j,r.style.boxSizing="border-box"}}},qb=(e,t)=>{let n=e.ownerDocument.createElement("div");return yf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){yf(n,o)},destroy(){n.remove()}}},Kb=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let w=null,g=()=>{w?.disconnect(),w=null},v=null,x=()=>{v=t?.launcher?.detachedPanel===!0?jb(t):null};x();let P=()=>{Vb(a,l,p,d,c,t,u,v)},F=null,k=()=>{F?.(),F=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(F=Fa(()=>{x(),P()}))},T=()=>{g(),hn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},M=!1,U=()=>{P(),T(),u&&!M&&a.dataset.personaDockMobileFullscreen!=="true"&&(M=!0,$b(a,hn(t)))},j=a.ownerDocument.defaultView,A=()=>{U()};return j?.addEventListener("resize",A),hn(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),U(),k(),{mode:"docked",host:c,shell:a,syncWidgetState(V){let K=V.launcherEnabled?V.open:!0;u!==K&&(u=K,U())},updateConfig(V){t=V,(t?.launcher?.enabled??!0)===!1&&(u=!0),x(),U(),k()},destroy(){j?.removeEventListener("resize",A),F?.(),F=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},wf=(e,t)=>Dt(t)?Kb(e,t):qb(e,t);var Ds={desktop:{w:1280,h:800},mobile:{w:390,h:844}},xf=.15,Cf=1.5,nc="persona-preview-shell-theme",Gb={load:()=>null,save:()=>{},clear:()=>{}},Qb=["How do I get started?","Pricing & plans","Talk to support"];function oc(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Xb(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Af(e){let t=Xb(e);return`* { box-sizing: border-box; }
|
|
139
|
+
${wt?"background: transparent !important;":""}
|
|
140
|
+
`}if(!y&&!i){let Mt="max-height: -moz-available !important; max-height: stretch !important;",tn=p?"":"padding-top: 1.25em !important;",Pa=p?"":`z-index: ${o.launcher?.zIndex??Nt} !important;`;Le.style.cssText+=Mt+tn+Pa}hn()},Xi=()=>{e.style.setProperty("--persona-content-max-width",xo(o,Q()))},md=()=>{if(Q())return;let i=Rt(o),p=o.launcher?.sidebarMode??!1;if(i||p||(o.launcher?.fullHeight??!1)||!F)return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E)return;let U=y.innerHeight,O=64,V=o.launcher?.heightOffset??0,J=Math.max(200,U-O),fe=Math.min(640,J);ye.style.height=`${Math.max(200,fe-V)}px`};Yi(),Ds(e,o),ea(e,o),ta(e,o),Xi(),Lo=()=>{Yi(),md(),Ds(e,o),ea(e,o),ta(e,o),Xi(),aa?e.style.setProperty("--persona-artifact-welded-outer-radius",aa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Be=[];Be.push(()=>{document.removeEventListener("keydown",ud)}),Be.push(()=>{Qr!==null&&clearTimeout(Qr)});let Wn=null,Rn=null;Be.push(()=>{Wn?.(),Wn=null,Rn?.(),Rn=null}),es&&Be.push(()=>{es?.disconnect(),es=null}),Be.push(()=>{os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),me&&Be.push(()=>{ze!==null&&(cancelAnimationFrame(ze),ze=null),Ae?.destroy(),Ae=null,Oe?.destroy(),Oe=null,Ue=null});let Io=null,hd=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=oi(()=>{Ds(e,o)}))};hd(),Be.push(()=>{Io&&(Io(),Io=null)}),Be.push(d);let fa=o.features?.streamAnimation;if(fa?.type&&fa.type!=="none"){let i=Or(fa.type,fa.plugins);i&&(bi(i,e),Be.push(()=>yf(e)))}let _n=qs(M),yd=qs(An),bd=qs(ne),Wo=[_n,yd,bd];Be.push(()=>{Wo.forEach(i=>i.destroy())});let Ro=null,_,Ho=null,vd=!1,wd=0,xd=null,Cd=i=>i.reduce((p,m)=>m.role==="user"?p+1:p,0),Ad=i=>{for(let p=i.length-1;p>=0;p--)if(Ss(i[p]))return i[p].id??null;return null},Sd=!1,jg=()=>{Sd||o.debug!==!0||(Sd=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Td=!1,Md=!1,Ed=(i,p)=>{Td||o.debug!==!0||!p.enabled||p.expose||vd||Md&&(_.isStreaming()||i.some(Ss)||(Td=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},lr=i=>{if(!_)return;let p=i??_.getMessages(),m=J=>{J.render([],_,I,p)},y=J=>{Wo.forEach(fe=>{fe!==J&&m(fe)})};Ho&&(Cd(p)>wd||Ad(p)!==xd)&&(Ho=null);let x=vo(o);Ed(p,x);let E=x.enabled?au(p):null,U=Ho??E,O=Ho?"host":"agent";if(U){let J=o.suggestions?.followUps,fe=J?.placement??(J?"auto":"composer"),be=(fe==="auto"?Q()?"composer":"after-message":fe)==="after-message"?bd:_n;y(be),be.render(U,_,I,p,o.suggestionChipsConfig,{source:O,surface:"followUp",variant:J?.variant??"chip",behavior:J?.behavior??"send",overflow:J?.overflow??"wrap",maxItems:J?.maxItems??4,config:o,plugins:s});return}if(p.some(J=>J.role==="user")){Wo.forEach(m);return}let V=o.suggestions?.starters;if(V){let J=_r(Zo(o),p),fe=V.placement??"auto",le=fe==="auto"?J?"welcome":"composer":fe;if(le==="welcome"&&!J){jg(),Wo.forEach(m);return}let be=le==="welcome"?yd:_n;y(be),be.render(V.items??o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:o,plugins:s});return}y(_n),_n.render(o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},kd=()=>{Ho&&(Ho=null,lr())},Vg=i=>{let p=Array.isArray(i)?[...i]:[];if(!p.length){kd();return}let m=_?_.getMessages():[];Ho=p,vd=!0,wd=Cd(m),xd=Ad(m),lr(m)},En=!1,Bo=lf(),cr=new Map,Do=new Map,ro=new Map,Qi=0,qg=Gn()!==null,on=ui(),rn=0,so=null,Zt=!1,ga=!1,ao=0,Bt=null,Fo=null,Ji=!1,ma=!1,Oo=null,rs=!0,ha=!1,dr=null,ya=!1,No=()=>{ya=!0,Xg()},Zi=null,Kg=4,$n=24,Gg=80,Yg=1e3,Un=null,Ld=()=>{e.setAttribute("data-persona-scrollbar",Ni()),Ni()!=="on-scroll"&&(Un!==null&&clearTimeout(Un),Un=null,re.removeAttribute("data-persona-scrollbar-visible"))},Xg=()=>{Ni()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Un!==null&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,eo(re,$n)&&re.removeAttribute("data-persona-scrollbar-visible")},Yg))};Ld(),Be.push(()=>{Un!==null&&clearTimeout(Un)});let el=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Pd=o.voiceRecognition?.autoResume??!1,zn=i=>{c.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},kn=()=>{S(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Qg=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Nc(g.voiceState),p=!!i.active,m=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,p&&Date.now()-m<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("restore"),_.isVoiceActive()&&hr()}):Ma("restore"))},1e3)},Jg=()=>_?xg(_.getMessages()).filter(i=>!i.__skipPersist):[],ba=null,Id=(i,p)=>{typeof console<"u"&&console.error(i,p)},tl=(i,p)=>{let m=()=>{try{let U=i();return!U||typeof U.then!="function"?null:Promise.resolve(U).catch(O=>{Id(p,O)})}catch(U){return Id(p,U),null}},y=ba,x=y?y.then(()=>m()??void 0):m();if(!x)return;let E=x.finally(()=>{ba===E&&(ba=null)});ba=E};function nl(i){if(!w?.save)return;let m={messages:i?xg(i):_?Jg():[],metadata:g,artifacts:Tn.artifacts,selectedArtifactId:Tn.selectedId};tl(()=>w.save(m),"[AgentWidget] Failed to persist state:")}let pr=null,Wd=()=>Le.querySelector("#persona-scroll-container")||re,ur=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Zt=!1},Rd=()=>{so!==null&&(cancelAnimationFrame(so),so=null),ga=!1,ur()},Zg=()=>En&&rl()&&(nn()!=="anchor-top"||Kc()),ol=()=>{let i=Gr()||"Jump to latest",p=Zg();Et.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),ao>0?(Mo.textContent=String(ao),Mo.style.display="",Et.setAttribute("aria-label",`${i} (${ao} new)`)):(Mo.textContent="",Mo.style.display="none",Et.setAttribute("aria-label",p?`${i} (response streaming below)`:i))},Hd=()=>{ao!==0&&(ao=0,ol())},em=()=>{let i=Bt?.spacerHeight??0;return i<=0?eo(re,$n):xa(i)-re.scrollTop-re.clientHeight<=$n},rl=()=>no()?!on.isFollowing():!em(),sl=()=>!!_&&_.getMessages().length>0,$t=()=>{if(!Og()||Se){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==ve&&ve.appendChild(Et),ko();let p=Dn(re)>0&&rl()&&sl();p?ol():Hd(),Et.style.display=p?"":"none"},ss=()=>{on.pause()&&(Rd(),$t())},io=()=>{on.resume(),Hd(),$t()},lo=(i=!1)=>{no()&&sl()&&on.isFollowing()&&(!i&&!En||(so!==null&&(cancelAnimationFrame(so),so=null),ga=!0,so=requestAnimationFrame(()=>{so=null,ga=!1,on.isFollowing()&&tm(Wd(),i?220:140)})))},Bd=(i,p,m,y=()=>!0)=>{let x=i.scrollTop,E=p(),U=E-x;if(ur(),Math.abs(U)<1){Zt=!0,i.scrollTop=E,rn=i.scrollTop,Zt=!1;return}let O=performance.now();Zt=!0;let V=fe=>1-Math.pow(1-fe,3),J=fe=>{if(!y()){ur();return}let le=p();le!==E&&(E=le,U=E-x);let be=fe-O,Ge=Math.min(be/m,1),mt=V(Ge),ct=x+U*mt;i.scrollTop=ct,rn=i.scrollTop,Ge<1?pr=requestAnimationFrame(J):(i.scrollTop=E,rn=i.scrollTop,pr=null,Zt=!1)};pr=requestAnimationFrame(J)},tm=(i,p=500)=>{let m=Dn(i)-i.scrollTop;if(Math.abs(m)<1){rn=i.scrollTop;return}if(Math.abs(m)>=Gg){ur(),Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1;return}Bd(i,()=>Dn(i),p,()=>on.isFollowing())},Dd=()=>{if(!sl()){$t();return}let i=Wd();Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1,$t()},_o=i=>{let p=0,m=i;for(;m&&m!==re;)p+=m.offsetTop,m=m.offsetParent;return p},nm=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},va=()=>ff(nm(),re),Fd=()=>{if(Ng()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let p=[...i].reverse().find(E=>E.role==="user");if(!p)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=re.querySelector(`[data-message-id="${m}"]`);if(!y)return!1;let x=Math.min(Math.max(0,_o(y)-Yr()),Dn(re));return Zt=!0,re.scrollTop=x,rn=re.scrollTop,Zt=!1,nn()==="follow"&&!eo(re,$n)&&on.pause(),$t(),!0},wa=i=>{let p=Math.max(0,Math.round(i));fn.style.height=`${p}px`,fn.style.display=p>0?"":"none",Bt&&(Bt.spacerHeight=Math.max(0,i))},xa=i=>{let p=parseFloat(getComputedStyle(re).paddingBottom)||0,m=0;for(let x of Array.from(re.children)){if(x===fn||x.offsetHeight===0)continue;let E=_o(x)+x.offsetHeight;E>m&&(m=E)}let y=re.scrollHeight-i;return m>0?Math.min(m+p,y):y},om=()=>{if(!Bt||Bt.spacerHeight<=0)return;let i=xa(Bt.spacerHeight),p=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+$n);p<Bt.spacerHeight&&(wa(p),$t())},as=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),ur(),Bt=null,fn.style.height="0px",fn.style.display="none"},Od=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),al=i=>re.querySelector(`[data-message-id="${Od(i)}"]`),Nd=i=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{Fo=null;let p=Od(i),m=re.querySelector(`[data-message-id="${p}"]`);if(!m)return;let y=_o(m),x=Bt?.spacerHeight??0,E=xa(x),{targetScrollTop:U,spacerHeight:O}=sc({anchorOffsetTop:y,topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:E,slack:$n});Bt={initialSpacerHeight:O,contentHeightAtAnchor:E,spacerHeight:O},wa(O),Bd(re,()=>m.isConnected?Math.max(0,_o(m)-Yr()):U,220)})},_d=()=>{if(nn()!=="anchor-top"||!Bt||!dr)return;let i=al(dr);if(!i)return;ur();let p=Bt.spacerHeight,m=xa(p),{targetScrollTop:y,spacerHeight:x}=sc({anchorOffsetTop:_o(i),topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:m,slack:$n});Bt={initialSpacerHeight:x,contentHeightAtAnchor:m,spacerHeight:x},wa(x),Zt=!0,re.scrollTop=y,rn=re.scrollTop,Zt=!1,$t()},rm=()=>{if(no()){if(!on.isFollowing()||eo(re,1))return;lo(!En);return}if(Bt&&Bt.initialSpacerHeight>0){let i=re.scrollHeight-Bt.spacerHeight,p=gf({initialSpacerHeight:Bt.initialSpacerHeight,contentHeightAtAnchor:Bt.contentHeightAtAnchor,currentContentHeight:i});p!==Bt.spacerHeight&&wa(p)}$t()},sm=i=>{let p=nn();p==="follow"?(io(),lo(!0)):p==="anchor-top"&&(rs=!1,ha=!0,ya=!1,dr=i,Nd(i))},am=()=>{if(nn()==="anchor-top"){if(ha){rs=!1;return}rs=!0,as(),io(),lo(!0)}},im=96,lm=i=>{if(Oo===null)return!0;let p=al(Oo),m=al(i);if(!p||!m)return!0;let y=_o(m)-_o(p);return Yr()+y>re.clientHeight-im},cm=i=>{if(nn()!=="anchor-top"||!ha||ya||va())return;let p=Oo===null;for(let m of i){if(!p){m.id===Oo&&(p=!0);continue}if(uf(m)){if(m.id===dr||!lm(m.id))return;dr=m.id,Nd(m.id);return}}},dm=i=>{let p=new Map;i.forEach(m=>{let y=el.get(m.id);p.set(m.id,{streaming:m.streaming,role:m.role}),!y&&m.role==="assistant"&&(c.emit("assistant:message",m),!ma&&(nn()!=="anchor-top"||Kc())&&rl()&&(ao+=1,ol(),$t(),Yc(ao===1?"1 new message below.":`${ao} new messages below.`))),m.role==="assistant"&&y?.streaming&&m.streaming===!1&&c.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(y?m.approval.status!=="pending"&&c.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):c.emit("approval:requested",{approval:m.approval,message:m}))}),el.clear(),p.forEach((m,y)=>{el.set(y,m)})},Ca=(i,p)=>{let m=p==="user"?"user":"assistant",y=o.layout?.messages?.[m],x=y?.width??"content",E=y?.maxWidth??(x==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${p}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",p==="user"),i.setAttribute("data-message-role",p),i.setAttribute("data-message-width",x),i.style.setProperty("--persona-message-row-max-width",E)},$o=(i,p)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Ca(m,p),m},pm=(i,p,m)=>{let y=document.createElement("div"),E=(()=>{let D=s.find(Ie=>Ie.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),U=(D,Ie)=>Ie==null?!1:typeof Ie=="string"?(D.textContent=Ie,!0):(D.appendChild(Ie),!0),O=new Set,V=new Map,J=new Set,fe=s.some(D=>D.renderAskUserQuestion),le=[],be=[],Ge=o.enableComponentStreaming!==!1,mt=o.approval!==!1,ct=[];if(p.forEach(D=>{O.add(D.id),V.set(D.id,D.role);let Ie=fe&&qo(D),De=mt&&D.variant==="approval"&&!!D.approval,Me=!Ie&&D.role==="assistant"&&!D.variant&&Ge&&Oc(D);!De&&ro.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id)),!Me&&Do.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Do.delete(D.id));let Ct=qo(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=af(D,Qi)+Ct,Ft=Ie||De||Me?null:cf(Bo,D.id,dt);if(Ft){y.appendChild(Ft.cloneNode(!0)),qo(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let pt=null,en=s.find(Fe=>!!(D.variant==="reasoning"&&Fe.renderReasoning||D.variant==="tool"&&Fe.renderToolCall||!D.variant&&Fe.renderMessage)),Pt=o.layout?.messages;if(qo(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){cr.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ss(D)&&vo(o).enabled)return;if(qo(D)&&o.features?.askUserQuestion?.enabled!==!1){let Fe=s.find(Ut=>typeof Ut.renderAskUserQuestion=="function");if(Fe&&st.current){let Ut=cr.get(D.id),zt=Ut!==dt,wt=null;if(zt){let{payload:Xe,complete:He}=Tr(D),ht=D.id,jt=()=>st.current?.getMessages().find(hn=>hn.id===ht);wt=Fe.renderAskUserQuestion({message:D,payload:Xe,complete:He,resolve:hn=>{let ys=jt();ys&&st.current?.resolveAskUserQuestion(ys,hn)},dismiss:()=>{let hn=jt();hn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(hn),st.current?.resolveAskUserQuestion(hn,"(dismissed)"))},config:o})}let at=Ut!=null;if(zt&&wt===null&&!at){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let ut=$o(D.id,D.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),le.push({messageId:D.id,fingerprint:dt,bubble:wt});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}}else if(De){let Fe=s.find(at=>typeof at.renderApproval=="function")??u,zt=ro.get(D.id)!==dt,wt=null;if(zt&&Fe?.renderApproval){let at=D.id,ut=(Xe,He)=>{let ht=st.current?.getMessages().find(jt=>jt.id===at);ht?.approval&&(ht.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(ht.id,Xe):st.current?.resolveApproval(ht.approval,Xe,He))};wt=Fe.renderApproval({message:D,defaultRenderer:()=>Ri(D,o),config:o,approve:Xe=>ut("approved",Xe),deny:Xe=>ut("denied",Xe)})}if(zt&&wt===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id),pt=Ri(D,o);else{let at=$o(D.id,D.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),y.appendChild(at),ct.push({messageId:D.id,fingerprint:dt,bubble:wt});return}}else if(en)if(D.variant==="reasoning"&&D.reasoning&&en.renderReasoning){if(!pe)return;pt=en.renderReasoning({message:D,defaultRenderer:()=>xc(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&en.renderToolCall){if(!ee)return;pt=en.renderToolCall({message:D,defaultRenderer:()=>Ac(D,o),config:o})}else en.renderMessage&&(pt=en.renderMessage({message:D,defaultRenderer:()=>{let Fe=hc(D,m,Pt,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o});return D.role!=="user"&&Wc(Fe,D,o,_),Fe},config:o}));if(!pt&&Me){let Fe=bg(D);if(Fe){let Ut=Do.get(D.id),zt=Ut!==dt,wt=o.wrapComponentDirectiveInBubble!==!1&&Zn.getOptions(Fe.component)?.bubbleChrome!==!1,at=null;if(zt){let ut=hg(Fe,{config:o,message:D,transform:m});if(ut&&Fe.component==="PersonaArtifactInline"){let Xe=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Xe&&jt&&jt!==Xe&&tf(jt)&&(Xe===ut?ut=jt:Xe.replaceWith(jt))}if(ut)if(wt){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),Xe.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}}if(at||Ut!=null){let ut=$o(D.id,D.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),be.push({messageId:D.id,fingerprint:dt,bubble:at});return}}}if(!pt)if(D.variant==="reasoning"&&D.reasoning){if(!pe)return;pt=xc(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!ee)return;pt=Ac(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;pt=Ri(D,o)}else{let Fe=o.layout?.messages;Fe?.renderUserMessage&&D.role==="user"?pt=Fe.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):Fe?.renderAssistantMessage&&D.role==="assistant"?pt=Fe.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):pt=hc(D,m,Fe,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o}),D.role!=="user"&&pt&&Wc(pt,D,o,_)}let We=$o(D.id,D.role);We.appendChild(pt),df(Bo,D.id,dt,We),y.appendChild(We)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let De=Ie.getAttribute("data-persona-ask-sheet-for");De&&!J.has(De)&&Er(Te.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let D=[],Ie=[],De=o.features.toolCallDisplay.groupedMode==="summary";p.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&ee){Ie.push(Me);return}Me.variant==="reasoning"&&!pe||((Ie.length>1||De&&Ie.length>0)&&D.push(Ie),Ie=[])}),(Ie.length>1||De&&Ie.length>0)&&D.push(Ie),D.forEach(Me=>{let Ct=Me.map(Fe=>Array.from(y.children).find(Ut=>Ut instanceof HTMLElement&&Ut.getAttribute("data-wrapper-id")===Fe.id)).filter(Fe=>!!Fe);if(Ct.length<(De?1:2))return;let dt=$o(`tool-group-${Me[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Me[0].id}`;let en=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Pt=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map(Fe=>Fe.toolCall).filter(Fe=>!!Fe),defaultSummary:en,config:o});U(pt,Pt)||(pt.textContent=en);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Me[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(pt),De||Ft.appendChild(We),dt.appendChild(Ft),Ct[0].before(dt),Ct.forEach((Fe,Ut)=>{if(De){Fe.remove();return}Fe.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),Ut<Ct.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(Fe),We.appendChild(zt)})})}pf(Bo,O);let sn=p.some(D=>D.role==="assistant"&&D.streaming),At=p[p.length-1],Lt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(En&&p.some(D=>D.role==="user")&&!sn&&!Lt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Ie=s.find(Me=>Me.renderLoadingIndicator),De=null;if(Ie?.renderLoadingIndicator&&(De=Ie.renderLoadingIndicator(D)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(D)),De===null&&(De=Ys()),De){let Me=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Me.className=Ct?Xs("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Me.setAttribute("data-typing-indicator","true"),Ct&&(Me.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Me.appendChild(De);let Ft=$o("typing-indicator","assistant");Ft.appendChild(Me),y.appendChild(Ft)}}if(!En&&p.length>0){let D=p[p.length-1],Ie={config:o,lastMessage:D,messageCount:p.length},De=s.find(Ct=>Ct.renderIdleIndicator),Me=null;if(De?.renderIdleIndicator&&(Me=De.renderIdleIndicator(Ie)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(Ie)),Me){let Ct=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;Ct.className=dt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Me);let Ft=$o("idle-indicator","assistant");Ft.appendChild(Ct),y.appendChild(Ft)}}if(Np(y),pi(i,y),Il(i),le.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of le){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),cr.set(D,Ie)))}if(cr.size>0)for(let D of cr.keys())O.has(D)||cr.delete(D);if(be.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of be){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),Do.set(D,Ie)))}if(Do.size>0)for(let D of Do.keys())O.has(D)||Do.delete(D);if(ct.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of ct){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),ro.set(D,Ie)))}if(ro.size>0)for(let D of ro.keys())O.has(D)||ro.delete(D)},is=(i,p,m)=>{pm(i,p,m),cd()},ls=null,um=()=>{if(ls)return;let i=m=>{let y=m.composedPath();y.includes(Le)||tt&&y.includes(tt)||lt(!1,"user")};ls=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},$d=()=>{if(!ls)return;(e.ownerDocument??document).removeEventListener("pointerdown",ls,!0),ls=null};Be.push(()=>$d());let cs=null,fm=()=>{if(cs)return;let i=m=>{m.key==="Escape"&&(m.isComposing||lt(!1,"user"))};cs=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Ud=()=>{if(!cs)return;(e.ownerDocument??document).removeEventListener("keydown",cs,!0),cs=null};Be.push(()=>Ud());let ds=!1,zd=new Set,gm=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},fr=()=>{if(!Q())return;let i=Te.peekBanner,p=Te.peekTextNode;if(!i||!p)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],y;for(let At=m.length-1;At>=0;At--){let Lt=m[At];if(Lt.role==="assistant"&&Lt.content){y=Lt;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,E=!!y.streaming,U=gm(),O=mi(U),V=O.type!=="none"?Or(O.type,U?.plugins):null,J=V?.isAnimating?.(y)===!0,fe=V!==null&&(E||J);fe&&V&&!zd.has(V.name)&&(bi(V,e),zd.add(V.name));let le=fe&&V?.containerClass?V.containerClass:null,be=p.dataset.personaPeekStreamClass??null;be&&be!==le&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),le&&be!==le&&(p.classList.add(le),p.dataset.personaPeekStreamClass=le),fe?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ge=fe?hi(x,O.buffer,V,y,E):x;if(fe&&O.placeholder==="skeleton"&&E&&(!Ge||!Ge.trim())){let At=document.createElement("div"),Lt=Us();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),pi(p,At)}else{let At=Math.max(0,Ge.length-100),Lt=Ge.length>100?Ge.slice(-100):Ge,D=mo(Lt);if(!fe||!V){let Ie=Ge.length>100?`\u2026${Lt}`:Lt;p.textContent!==Ie&&(p.textContent=Ie)}else{let Ie=D;(V.wrap==="char"||V.wrap==="word")&&(Ie=$s(D,V.wrap,`peek-${y.id}`,{skipTags:V.skipTags,startIndex:At}));let De=document.createElement("div");if(De.innerHTML=Ie,V.useCaret&&Lt.length>0){let Me=yi(),Ct=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Ct[Ct.length-1];dt?.parentNode?dt.parentNode.insertBefore(Me,dt.nextSibling):De.appendChild(Me)}pi(p,De),V.onAfterRender?.({container:p,bubble:i,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let sn=En||ds;i.classList.toggle("persona-pill-peek--visible",sn)};if(Q()){let i=Te.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",y),Be.push(()=>{i.removeEventListener("pointerdown",y)})}let p=()=>{ds||(ds=!0,fr())},m=()=>{ds&&(ds=!1,fr())};ye.addEventListener("pointerenter",p),ye.addEventListener("pointerleave",m),Be.push(()=>{ye.removeEventListener("pointerenter",p),ye.removeEventListener("pointerleave",m)}),tt&&(tt.addEventListener("pointerenter",p),tt.addEventListener("pointerleave",m),Be.push(()=>{tt.removeEventListener("pointerenter",p),tt.removeEventListener("pointerleave",m)}))}let mm=i=>{let p=o.launcher?.composerBar??{},m=p.expandedSize??"anchored",y=p.bottomOffset??"16px",x=p.collapsedMaxWidth,E=p.expandedMaxWidth??"880px",U=p.expandedTopOffset??"5vh",O=p.modalMaxWidth??"880px",V=p.modalMaxHeight??"min(90vh, 800px)",J="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let be=tt.style;be.bottom=y,be.width=x??""}if(i&&m!=="fullscreen"){if(m==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=O,le.maxWidth=J,le.maxHeight=V,le.height=V;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${y} + ${fe})`,le.top=U,le.width=E,le.maxWidth=J}},ps=()=>{if(!ie())return;if(Q()){let J=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Y?"expanded":"collapsed";Le.dataset.state=fe,Le.dataset.expandedSize=J,tt&&(tt.dataset.state=fe,tt.dataset.expandedSize=J),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),mm(Y),ve.style.display=Y?"flex":"none",Lo(),Y?(um(),fm()):($d(),Ud()),fr();return}let i=Rt(o),p=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=p.innerWidth<=m,E=y&&x&&F,U=vn(o).reveal;Y?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),Tt?(Tt.setPanelOpen(!0),Tt.element.style.display="none"):Xt&&(Xt.style.display="none")):(i?i&&(U==="overlay"||U==="push")&&!E?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),Tt?(Tt.setPanelOpen(!1),Tt.element.style.display=i?"none":""):Xt&&(Xt.style.display=i?"none":""))},lt=(i,p="user")=>{if(!ie()||Y===i)return;let m=Y;Y=i,ps();let y=(()=>{let E=o.launcher?.sidebarMode??!1,U=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640,J=U.innerWidth<=V,fe=Rt(o)&&O&&J,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||O&&J&&F||fe||le})();if(Y&&y){if(!Wn){let E=e.getRootNode(),U=E instanceof ShadowRoot?E.host:e.closest(".persona-host");U&&(Wn=lc(U,o.launcher?.zIndex??Nt))}Rn||(Rn=cc(e.ownerDocument))}else Y||(Wn?.(),Wn=null,Rn?.(),Rn=null);Y&&(ms(),Fd()||(nn()==="follow"?lo(!0):Dd()));let x={open:Y,source:p,timestamp:Date.now()};Y&&!m?c.emit("widget:opened",x):!Y&&m&&c.emit("widget:closed",x),c.emit("widget:state",{open:Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()})},Aa=i=>{ra(i?"stop":"send"),oe&&(oe.disabled=i),Wo.forEach(p=>{p.elements.forEach(m=>{m.toggleAttribute("data-disabled",i),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",i?"true":"false")}),p.buttons.forEach(m=>{m.disabled=i})}),pl.forEach(p=>{p.toggleAttribute("data-disabled",i),p instanceof HTMLButtonElement?p.disabled=i:p.setAttribute("aria-disabled",i?"true":"false"),p.querySelectorAll("button").forEach(m=>{m.disabled=i})}),Ce.dataset.personaComposerStreaming=i?"true":"false",Ce.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=i)})},il=()=>{Ke.active||I&&I.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>il(),200)});let ll=!q.hidden,co=null,jd=!v,Vd=null,qd,Kd=null,us=null,cl=i=>{let p=Zo(o),m=`${p.variant}|${p.dismiss}|${p.title}|${p.subtitle}`;(m!==Vd||p.icon!==qd)&&(Vd=m,qd=p.icon,Pi({host:q,iconHolder:$,title:ce,subtitle:je,starterSuggestions:An},p));let y=p.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${p.message}`;y!==Kd&&(Kd=y,Ii(K,p.message,o));let x=i??(_?_.getMessages():o.initialMessages),E=_r(p,x),U=E!==ll;if(ll=E,us){co?.cancel(),co=null,Nr(re,q,!0);return}if(U&&!E&&p.dismiss==="on-first-message"&&jd){co=Pf(q,O=>{co===O&&(co=null),!ll&&!us&&(Nr(re,q,!1),_d()),O?.cancel()});return}if(co){if(!E)return;co.cancel(),co=null}Nr(re,q,E),U&&!E&&_d()},dl=[],pl=[],ul=!1,Gd=null,Yd,Xd=()=>{pl.length=0;let i=dl.splice(0,dl.length);for(let p of i)try{p()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Be.push(Xd);let hm=(i,p)=>{let m=pc(i,p);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),b("span");let y=o.suggestions?.starters,x=uc({item:{...m,behavior:m.behavior??y?.behavior??"send"},index:p,surface:"starter",source:"config",variant:y?.variant??"card",streaming:a?_.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>I,eventTarget:q});return pl.push(x),x},fl=()=>{if(ul)return;ul=!0;let i=Zo(o);Gd=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Yd=i.icon;try{Xd(),kf(re,q,us),us=null;let p=_?_.getMessages():o.initialMessages,m=_r(i,p),y=0,x=null;for(let E of s)if(E.renderWelcome&&(x=E.renderWelcome({config:i,variant:i.variant,visible:m,defaultRenderer:()=>q,sendMessage:U=>{if(!_||_.isStreaming())return;let O=U.trim();O&&_.sendMessage(O)},requestRender:()=>fl(),renderStarter:U=>hm(U,y++),storage:l(E.id),onCleanup:U=>{dl.push(U)}}),x))break;x&&x!==q&&(us=x,Ef(re,q,x))}finally{ul=!1}cl()},ym=()=>{let i=Zo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Gd&&i.icon===Yd||fl()},gl=()=>{cl(),zi||(I.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),I.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',I.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=g.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(p=>({...p,sessionId:i}))}});let Uo=null,bm=()=>{Uo==null&&(Uo=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let p=Date.now();i.forEach(m=>{let y=Number(m.getAttribute("data-tool-elapsed"));y&&(m.textContent=za(p-y))})},100))},ml=(i,p)=>{if(Object.is(i,p))return!0;if(i===null||p===null||typeof i!="object"||typeof p!="object")return!1;if(Array.isArray(i)||Array.isArray(p))return!Array.isArray(i)||!Array.isArray(p)||i.length!==p.length?!1:i.every((U,O)=>ml(U,p[O]));let m=i,y=p,x=Object.keys(m),E=Object.keys(y);return x.length===E.length&&x.every(U=>Object.prototype.hasOwnProperty.call(y,U)&&ml(m[U],y[U]))},Qd=i=>{let{content:p,rawContent:m,llmContent:y,...x}=i;return x},hl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Oc(i),vm=(i,p,m)=>{if(i.length!==p.length)return!1;let y=i[m.index],x=p[m.index];return!y||!x||y.id!==m.id||x.id!==m.id?!1:(!Object.is(y.content,x.content)||!Object.is(y.rawContent,x.rawContent)||!Object.is(y.llmContent,x.llmContent))&&hl(y)&&hl(x)&&ml(Qd(y),Qd(x))},Jd=null,gr=null,zo=null,jn=null,Sa=i=>{Jd=i;let p,m;gr=null;for(let x=i.length-1;x>=0;x-=1){let E=i[x];if(!p&&E.role==="user"&&(p=E),!m&&E.role==="assistant"&&(m=E),!gr&&hl(E)&&(gr={index:x,id:E.id}),p&&m&&gr)break}is(xe,i,Z),tc(xe,Tn.artifacts,{suppressTransition:En}),bm(),cl(i),lr(i),lo(!En),dm(i),i.length===0&&(as(),rs=!0,ha=!1,dr=null,ya=!1),!Ji||ma?(Ji=!0,Oo=p?.id??null,Zi=m?.id??null):p&&p.id!==Oo?(Oo=p.id,sm(p.id)):m&&m.id!==Zi&&am(),m&&(Zi=m.id),cm(i);let y=Ke.lastUserMessageId;p&&p.id!==y&&(Ke.lastUserMessageId=p.id,c.emit("user:message",p)),Ke.lastUserMessageWasVoice=!!p?.viaVoice,nl(i),fr()},yl=()=>{jn!==null&&(cancelAnimationFrame(jn),jn=null);let i=zo;zo=null,i&&Sa(i)},Zd=()=>{jn!==null&&cancelAnimationFrame(jn),jn=null,zo=null},wm=i=>{let p=zo??Jd;if(En&&p&&gr&&vm(p,i,gr)){zo=i,jn===null&&(jn=requestAnimationFrame(()=>{jn=null;let m=zo;zo=null,m&&Sa(m)}));return}if(i.length===0){Zd(),Sa(i);return}yl(),Sa(i)};_=new Qa(o,{onMessagesChanged(i){wm(i)},onStatusChanged(i){let p=o.statusIndicator??{};Cn(R,(y=>y==="idle"?p.idleText??It.idle:y==="connecting"?p.connectingText??It.connecting:y==="connected"?p.connectedText??It.connected:y==="error"?p.errorText??It.error:y==="paused"?p.pausedText??It.paused:y==="resuming"?p.resumingText??It.resuming:It[y])(i),p,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?Zd():yl()),En=i,Aa(i),_&&is(xe,_.getMessages(),Z),i||(lo(!0),om(),Md=!0,_&&Ed(_.getMessages(),vo(o))),$t(),Yc(i?"Responding\u2026":"Response complete."),fr()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Vn(),hr();break;case"processing":Vn(),Im();break;case"speaking":Vn(),Wm();break;default:i==="idle"&&_.isBargeInActive()?(Vn(),hr(),oe?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Vn(),zn("system"),kn());break}},onArtifactsState(i){Tn=i,i.artifacts.length===0&&(sr=!1),tc(xe,i.artifacts,{suppressTransition:En}),Nn(),nl()},onReconnect(i){let{executionId:p,lastEventId:m}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:p,after:m}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:p,after:m,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:p,after:m})}}),st.current=_,Be.push(()=>_.cancel());let bl=null;if(_.onReadAloudChange((i,p)=>{id=i,ld=p,cd();let m=i??bl;i&&(bl=i);let y=m?_.getMessages().find(x=>x.id===m)??null:null;c.emit("message:read-aloud",{messageId:m,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(bl=null)}),a=!0,Ji=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&_.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Oe||o.onSSEEvent)&&_.setSSEEventCallback((i,p)=>{o.onSSEEvent?.(i,p),_e?.processEvent(i,p),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(p)})});let ep=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};v?v.then(i=>{if(i){if(i.metadata&&(g=Nc(i.metadata),H.syncFromMetadata()),i.messages?.length){ma=!0;try{_.hydrateMessages(i.messages)}finally{ma=!1}}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{jd=!0,ep()}):ep();let tp=()=>{!Q()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},xm=(i,p)=>i?p?{refs:[...i.refs,...p.refs],finalize:async()=>{let[m,y]=await Promise.allSettled([i.finalize(),p.finalize()]),x=[];return m.status==="fulfilled"?x.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),y.status==="fulfilled"?x.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),mw(x)}}:i:p,Cm=()=>{let p=I.getInlineMessageFields?.();return p&&p.contentSegments.some(y=>y.kind==="mention")?p.contentSegments:void 0},fs=!1,Am=async i=>{let p=I.value.trim(),m=yt?.hasAttachments()??!1,y=p?await(Yt?.takeInlineCommand(p)??Promise.resolve(null)):null;if(y?.kind==="action"){I.value="",I.style.height="auto",gs(),Yt?.clear();return}let x=Yt?.collectForSubmit()??null,E=y?.kind==="server"?y.mentions:null,U=xm(x,E),O=y?.kind==="prompt"?y.sendText:p,V=!!x&&x.refs.length>0;if(!O&&!m&&!V&&!E)return;tp();let J;m&&(J=[],J.push(...yt.getContentParts()),O&&J.push(Lr(O)));let fe=y?.kind==="prompt"?void 0:Cm();I.value="",I.style.height="auto",gs(),_.sendMessage(O,{contentParts:J,mentions:U??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),m&&yt.clearAttachments(),x&&Yt?.clear()},vl=async i=>{if(!fs){fs=!0;try{await Am(i)}finally{fs=!1}}},Ta=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),_e?.reset(),Ae?.update();return}fs||vl()},Sm=()=>o.features?.composerHistory!==!1,wl={...rc},xl=!1,gs=()=>{wl={...rc}},Tm=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Mm=i=>{if(!I)return;xl=!0,I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),xl=!1;let p=I.value.length;I.setSelectionRange(p,p)},Em=i=>{xl||(i.isComposing||Yt?.handleInput(i.inputType??void 0),gs())},km=i=>{if(I&&!(!i.isComposing&&Yt?.handleKeydown(i))){if(Sm()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let p=I.selectionStart===0&&I.selectionEnd===0,m=sf({direction:i.key==="ArrowUp"?"up":"down",history:Tm(),currentValue:I.value,atStart:p,state:wl});if(wl=m.state,m.handled){i.preventDefault(),m.value!==void 0&&Mm(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(fs){i.preventDefault();return}gs(),i.preventDefault(),h.click()}}},np=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(ve)&&(_.cancel(),_e?.reset(),Ae?.update(),gs(),i.preventDefault(),i.stopImmediatePropagation())},Lm=async i=>{if(o.attachments?.enabled!==!0||!yt)return;let p=pw(i.clipboardData);p.length!==0&&(i.preventDefault(),await yt.handleFiles(p))},gn=null,Hn=!1,mr=null,vt=null,op=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ma=(i="user")=>{if(Hn||_.isStreaming())return;let p=op();if(!p)return;gn=new p;let y=(o.voiceRecognition??{}).pauseDuration??2e3;gn.continuous=!0,gn.interimResults=!0,gn.lang="en-US";let x=I.value;gn.onresult=E=>{let U="",O="";for(let J=0;J<E.results.length;J++){let fe=E.results[J],le=fe[0].transcript;fe.isFinal?U+=le+" ":O=le}let V=x+U+O;I.value=V,mr&&clearTimeout(mr),(U||O)&&(mr=window.setTimeout(()=>{I.value.trim()&&gn&&Hn&&(po(),vl({viaVoice:!0}))},y))},gn.onerror=E=>{E.error!=="no-speech"&&po()},gn.onend=()=>{if(Hn){let E=I.value.trim();E&&E!==x.trim()&&vl({viaVoice:!0}),po()}};try{if(gn.start(),Hn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),zn(i),kn(),oe){let E=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let U=E.recordingBackgroundColor,O=E.recordingIconColor,V=E.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=U??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let J=oe.querySelector("svg");J&&J.setAttribute("stroke",O)}V&&(oe.style.borderColor=V),oe.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(i="user")=>{if(Hn){if(Hn=!1,mr&&(clearTimeout(mr),mr=null),gn){try{gn.stop()}catch{}gn=null}if(Ke.active=!1,zn(i),kn(),oe){if(oe.classList.remove("persona-voice-recording"),vt){oe.style.backgroundColor=vt.backgroundColor,oe.style.color=vt.color,oe.style.borderColor=vt.borderColor;let p=oe.querySelector("svg");p&&p.setAttribute("stroke",vt.color||"currentColor"),vt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Pm=(i,p)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),y=i?.provider?.type==="runtype",x=i?.provider?.type==="custom";if(!(m||y||x))return null;let U=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button";let V=i?.tooltipText??"Start voice recognition";O.setAttribute("aria-label",V);let J=i?.iconName??"mic",fe=p?.size??"40px",le=i?.iconSize??fe,be=parseFloat(le)||24,Ge=i?.backgroundColor??p?.backgroundColor,mt=i?.iconColor??p?.textColor;O.style.width=le,O.style.height=le,O.style.minWidth=le,O.style.minHeight=le,O.style.fontSize="18px",O.style.lineHeight="1",mt?O.style.color=mt:O.style.color="var(--persona-text, #111827)";let sn=ae(J,be,mt||"currentColor",1.5);sn?O.appendChild(sn):O.textContent="\u{1F3A4}",Ge?O.style.backgroundColor=Ge:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),U.appendChild(O);let At=i?.showTooltip??!1;return _t({anchor:O,trigger:U,text:()=>O.getAttribute("aria-label")??V,enabled:At}),{micButton:O,micButtonWrapper:U}},Cl=()=>{if(!oe||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Al=(i,p)=>{if(!oe)return;let m=oe.querySelector("svg");m&&m.remove();let y=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),x=ae(i,y,p,1.5);x&&oe.appendChild(x)},Ea=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hr=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=i.recordingBackgroundColor,m=i.recordingIconColor,y=i.recordingBorderColor;if(Ea(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let x=oe.querySelector("svg");x&&x.setAttribute("stroke",m)}y&&(oe.style.borderColor=y),oe.setAttribute("aria-label","Stop voice recognition")},Im=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=i.processingIconName??"loader",y=i.processingIconColor??vt?.color??"",x=i.processingBackgroundColor??vt?.backgroundColor??"",E=i.processingBorderColor??vt?.borderColor??"";Ea(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=x,oe.style.borderColor=E;let U=y||"currentColor";oe.style.color=U,Al(m,U),oe.setAttribute("aria-label","Processing voice input"),p==="none"&&(oe.style.cursor="default")},Wm=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=i.speakingIconName??m,x=i.speakingIconColor??(p==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),E=i.speakingBackgroundColor??(p==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),U=i.speakingBorderColor??(p==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");Ea(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=E,oe.style.borderColor=U;let O=x||"currentColor";oe.style.color=O,Al(y,O);let V=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",V),p==="none"&&(oe.style.cursor="default"),p==="barge-in"&&oe.classList.add("persona-voice-recording")},Vn=()=>{oe&&(Ea(),vt&&(oe.style.backgroundColor=vt.backgroundColor??"",oe.style.color=vt.color??"",oe.style.borderColor=vt.borderColor??"",Al(vt.iconName,vt.color||"currentColor"),vt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},yr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),p=_.getVoiceInterruptionMode();if(p==="none"&&(i==="processing"||i==="speaking"))return;if(p==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()});return}_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),Ke.manuallyDeactivated=!_.isVoiceActive(),kn(),zn("user"),_.isVoiceActive()?hr():Vn()});return}if(Hn){let i=I.value.trim();Ke.manuallyDeactivated=!0,kn(),po("user"),i&&(I.value="",I.style.height="auto",_.sendMessage(i))}else Ke.manuallyDeactivated=!1,kn(),Ma("user")};Qc=yr,oe&&(oe.addEventListener("click",yr),Be.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Vn()):po("system"),oe&&oe.removeEventListener("click",yr)}));let Rm=c.on("assistant:complete",()=>{Pd&&(Ke.active||Ke.manuallyDeactivated||Pd==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("auto"),_.isVoiceActive()&&hr()}):Ma("auto"))},600))});Be.push(Rm);let Hm=c.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});Be.push(Hm);let rp=()=>{lt(!Y,"user")},Tt=null,Xt=null;if(F&&!Q()){let{instance:i,element:p}=wc({config:o,plugins:s,onToggle:rp});Tt=i,i||(Xt=p)}Tt?e.appendChild(Tt.element):Xt&&e.appendChild(Xt),ps(),lr(),gl(),fl(),Aa(_.isStreaming()),Fd()||(nn()==="follow"?lo(!0):Dd()),Qg(),z&&(!F||Q()?setTimeout(()=>il(),0):Y&&setTimeout(()=>il(),200));let ms=()=>{if(Q()){ko(),ps();return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,E=m.innerWidth<=x,U=y&&E&&F;try{if(U){Lo(),ts=ua();return}let O=!1;G&&(G=!1,Lo(),O=!0);let V=ua();if(!O&&V!==ts&&(Lo(),O=!0),ts=V,O&&Ki(),!F&&!i){ye.style.height="",ye.style.width="";return}if(!p&&!i){let fe=o?.launcher?.width??o?.launcherWidth??Jn;ye.style.width=fe,ye.style.maxWidth=fe}pa(),md()}finally{if(ko(),ps(),Y&&F){let V=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),J=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,le=Rt(o)&&fe&&V,be=J||fe&&V&&F||le;if(be&&!Rn){let Ge=e.getRootNode(),mt=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");mt&&!Wn&&(Wn=lc(mt,o.launcher?.zIndex??Nt)),Rn=cc(e.ownerDocument)}else be||(Wn?.(),Wn=null,Rn?.(),Rn=null)}}};ms();let sp=e.ownerDocument.defaultView??window;if(sp.addEventListener("resize",ms),Be.push(()=>sp.removeEventListener("resize",ms)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ko()});i.observe(Ce),Be.push(()=>i.disconnect())}rn=re.scrollTop;let ap=Dn(re),ip=()=>{let i=re.scrollTop,p=Dn(re),m=p<ap;if(ap=p,!no()){rn=i,$t();return}let{action:y,nextLastScrollTop:x}=fi({following:on.isFollowing(),currentScrollTop:i,lastScrollTop:rn,nearBottom:eo(re,$n),userScrollThreshold:Kg,isAutoScrolling:Zt||ga||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=x,y==="resume"){va()||io();return}y==="pause"&&ss()};if(re.addEventListener("scroll",ip,{passive:!0}),Be.push(()=>re.removeEventListener("scroll",ip)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{rm(),Il(xe)});i.observe(xe),i.observe(re),Be.push(()=>i.disconnect())}let lp=()=>{no()&&on.isFollowing()&&va()&&ss()},cp=re.ownerDocument;cp.addEventListener("selectionchange",lp),Be.push(()=>{cp.removeEventListener("selectionchange",lp)});let Bm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dp=i=>{Bm.has(i.key)&&(No(),qc()&&no()&&on.isFollowing()&&ss())},pp=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(No(),qc()&&no()&&on.isFollowing()&&ss())};re.addEventListener("keydown",dp),re.addEventListener("focusin",pp),Be.push(()=>{re.removeEventListener("keydown",dp),re.removeEventListener("focusin",pp)});let up=i=>{if(i.deltaY!==0&&No(),!no())return;let p=gi({following:on.isFollowing(),deltaY:i.deltaY,nearBottom:eo(re,$n),resumeWhenNearBottom:!0});p==="pause"?ss():p==="resume"&&!va()&&io()};re.addEventListener("wheel",up,{passive:!0}),re.addEventListener("touchmove",No,{passive:!0}),re.addEventListener("pointerdown",No,{passive:!0}),Be.push(()=>{re.removeEventListener("touchmove",No),re.removeEventListener("pointerdown",No)}),Be.push(()=>re.removeEventListener("wheel",up)),Et.addEventListener("click",()=>{as(),re.scrollTop=re.scrollHeight,rn=re.scrollTop,io(),lo(!0),$t()}),Be.push(()=>Et.remove()),Be.push(()=>{Rd(),as()});let fp=()=>{de&&(Ro&&(de.removeEventListener("click",Ro),Ro=null),ie()?(de.style.display="",Ro=()=>{lt(!1,"user")},de.addEventListener("click",Ro)):de.style.display="none")};fp(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),io(),Er(Te.composerOverlay);try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(p),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()})})(),L&&L.addEventListener("submit",Ta);let gp=[["keydown",km],["input",Em],["paste",Lm],["focus",_g]],Sl=i=>{if(i)for(let[p,m]of gp)i.addEventListener(p,m)},Tl=i=>{if(i)for(let[p,m]of gp)i.removeEventListener(p,m)};Sl(I);let mp=()=>{Yt?.onComposerSwap((i,p)=>{Tl(p),I=i,Sl(i)})};mp();let Ml=!1;function Dm(){if(!Ml){Ml=!0;try{let i=I?.value??"",p=Ce.ownerDocument??document,m=I?p.activeElement===I:!1;Tl(I),L?.removeEventListener("submit",Ta),oe?.removeEventListener("click",yr),Yt?.destroy(),Yt=null;let y=null,x=()=>(y=Q()?ki({config:o}):Gs({config:o}),y.footer),E=ed(x)??x();et.replaceComposer(E),Ce=et.composer.footer;let U=y!==null&&E===y.footer;zi=!U,ra=U?y.setSendButtonMode:()=>{},Zc(Ce),nd(Ce),od(),rd(),sd(),mp(),L&&L.addEventListener("submit",Ta),Sl(I),oe?.addEventListener("click",yr);let O=Wo.indexOf(_n);_n.destroy(),_n=qs(M),O>=0&&(Wo[O]=_n),I&&(I.value=i),gl(),lr(),Aa(_.isStreaming()),Lo(),ko(),m&&I?.focus()}finally{Ml=!1}}}let hp=e.ownerDocument??document;hp.addEventListener("keydown",np,!0);let yp="persona-attachment-drop-active",hs=0,El=()=>{hs=0,ve.classList.remove(yp)},br=()=>o.attachments?.enabled===!0&&yt!==null,bp=i=>{!Fi(i.dataTransfer)||!br()||(hs++,hs===1&&ve.classList.add(yp))},vp=i=>{!Fi(i.dataTransfer)||!br()||(hs--,hs<=0&&El())},wp=i=>{!Fi(i.dataTransfer)||!br()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},xp=i=>{if(!Fi(i.dataTransfer)||!br())return;i.preventDefault(),i.stopPropagation(),El();let p=Array.from(i.dataTransfer.files??[]);p.length!==0&&yt.handleFiles(p)},uo=!0;ve.addEventListener("dragenter",bp,uo),ve.addEventListener("dragleave",vp,uo),e.addEventListener("dragover",wp,uo),e.addEventListener("drop",xp,uo);let ka=e.ownerDocument,Cp=i=>{br()&&i.preventDefault()},Ap=i=>{br()&&i.preventDefault()};ka.addEventListener("dragover",Cp),ka.addEventListener("drop",Ap),Be.push(()=>{L&&L.removeEventListener("submit",Ta),Tl(I),hp.removeEventListener("keydown",np,!0),Yt?.destroy()}),Be.push(()=>{ve.removeEventListener("dragenter",bp,uo),ve.removeEventListener("dragleave",vp,uo),e.removeEventListener("dragover",wp,uo),e.removeEventListener("drop",xp,uo),ka.removeEventListener("dragover",Cp),ka.removeEventListener("drop",Ap),El()}),Be.push(()=>{_.cancel()}),Tt?Be.push(()=>{Tt?.destroy()}):Xt&&Be.push(()=>{Xt?.remove()});let kt={update(i){let p=o.toolCall,m=o.messageActions,y=o.layout?.messages,x=o.colorScheme,E=o.loadingIndicator,U=o.iterationDisplay,O=o.features?.showReasoning,V=o.features?.showToolCalls,J=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ug({...o,features:r},i),r=o.features,o=Pc(o),Yi(),Ds(e,o),ea(e,o),ta(e,o),Nn(),o.colorScheme!==x&&hd();let be=Hc.getForInstance(o.plugins);s.length=0,s.push(...be),F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,we=o.features?.scrollToBottom??{};let Ge=nn();he=o.features?.scrollBehavior??{},Ge!==nn()&&(as(),io()),Ld(),Xc(),$t();let mt=me;if(me=o.features?.showEventStreamToggle??!1,me&&!mt){if(Oe||(Ue=new Js(Ne),Oe=new Qs(Qe,Ue),_e=_e??new Zs,Ue.open().then(()=>Oe?.restore()).catch(()=>{}),_.setSSEEventCallback((se,qe)=>{o.onSSEEvent?.(se,qe),_e?.processEvent(se,qe),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!Je&&Re){let se=o.features?.eventStream?.classNames,qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(se?.toggleButton?" "+se.toggleButton:"");Je=b("button",qe),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let ft=ae("activity","18px","currentColor",1.5);ft&&Je.appendChild(ft);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Vt=Ze||ot;Vt&&Vt.parentNode===Re?Re.insertBefore(Je,Vt):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}}else!me&&mt&&(Jr(),Je&&(Je.remove(),Je=null),Oe?.clear(),Ue?.destroy(),Oe=null,Ue=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Tt&&(Tt.destroy(),Tt=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Tt&&!Xt){let{instance:se,element:qe}=wc({config:o,plugins:s,onToggle:rp});Tt=se,se||(Xt=qe),e.appendChild(qe)}Tt&&Tt.update(o),Ve&&o.launcher?.title!==void 0&&(Ve.textContent=o.launcher.title),$e&&o.launcher?.subtitle!==void 0&&($e.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==A&&Re){let se=ct?xi(o,ct,{showClose:ie(),onClose:()=>lt(!1,"user")}):Jo({config:o,showClose:ie(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),Re=et.header.element,Pe=et.header.iconHolder,Ve=et.header.headerTitle,$e=et.header.headerSubtitle,de=et.header.closeButton,A=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),Ve&&(Ve.style.display=ct.showTitle===!1?"none":""),$e&&($e.style.display=ct.showSubtitle===!1?"none":""),de){let se=ie()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:qe}=Te;qe&&!qe.classList.contains("persona-absolute")&&(se?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;Re&&(Re.style.display=At?"":"none");let Lt=o.layout?.showFooter!==!1;Ce&&(Ce.style.display=Lt?"":"none"),ko(),$t(),F!==te?F?lt(N,"auto"):(Y=!0,ps()):N!==j&<(N,"auto"),j=N,te=F,ms(),fp();let De=JSON.stringify(o.toolCall)!==JSON.stringify(p),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),dt=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,Ft=o.iterationDisplay!==U,pt=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(J)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(De||Me||Ct||dt||Ft||pt)&&_&&(Qi++,is(xe,_.getMessages(),Z));let Pt=o.features?.streamAnimation?.type;if(Pt!==le&&Pt&&Pt!=="none"){let se=Or(Pt,o.features?.streamAnimation?.plugins);se&&bi(se,e)}let We=o.launcher??{},Fe=We.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,zt=Fe||Ut===!1,wt=We.headerIconName,at=We.headerIconSize??"48px";if(Pe){let se=ve.querySelector(".persona-border-b-persona-divider"),qe=se?.querySelector(".persona-flex-col");if(zt)Pe.style.display="none",se&&qe&&!se.contains(qe)&&se.insertBefore(qe,se.firstChild);else{if(Pe.style.display="",Pe.style.height=at,Pe.style.width=at,se&&qe&&(se.contains(Pe)?Pe.nextSibling!==qe&&(Pe.remove(),se.insertBefore(Pe,qe)):se.insertBefore(Pe,qe)),wt){let Ze=parseFloat(at)||24,ot=ae(wt,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=We.iconUrl,Ze.style.height=at,Ze.style.width=at;else{let ot=document.createElement("img");ot.src=We.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=at,ot.style.width=at,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=We.agentIconText??"\u{1F4AC}"}let ft=Pe.querySelector("img");ft&&(ft.style.height=at,ft.style.width=at)}}let ut=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(Ve&&(Ve.style.display=ut===!1?"none":""),$e&&($e.style.display=Xe===!1?"none":""),de){let se=ie()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let qe=We.closeButtonSize??"32px",ft=We.closeButtonPlacement??"inline";de.style.height=qe,de.style.width=qe;let{closeButtonWrapper:Ze}=Te,ot=ft==="top-right",Vt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Vt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ve.style.position="relative",ve.appendChild(Ze);else{let go=We.clearChat?.placement??"inline",vs=We.clearChat?.enabled??!0;Ze.className=vs&&go==="inline"?"":"persona-ml-auto";let Sp=ve.querySelector(".persona-border-b-persona-divider");Sp&&Sp.appendChild(Ze)}if(de.style.color=We.closeButtonColor||Kt.actionIconColor,We.closeButtonBackgroundColor?(de.style.backgroundColor=We.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let go=We.closeButtonBorderWidth||"0px",vs=We.closeButtonBorderColor||"transparent";de.style.border=`${go} solid ${vs}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");We.closeButtonBorderRadius?(de.style.borderRadius=We.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(de.style.paddingLeft=We.closeButtonPaddingX,de.style.paddingRight=We.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),We.closeButtonPaddingY?(de.style.paddingTop=We.closeButtonPaddingY,de.style.paddingBottom=We.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let an=We.closeButtonIconName??"x",Ln=We.closeButtonIconText??"\xD7";de.innerHTML="";let Ot=ae(an,"28px","currentColor",1);Ot?(Ot.style.display="block",de.appendChild(Ot)):de.textContent=Ln;let qt=We.closeButtonTooltipText??"Close chat",Kn=We.closeButtonShowTooltip??!0;de.setAttribute("aria-label",qt),Ze&&_t({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??qt,enabled:Kn})}let{clearChatButton:He,clearChatButtonWrapper:ht}=Te;if(He){let se=We.clearChat??{},qe=se.enabled??!0,ft=o.layout?.header?.showClearChat,Ze=ft!==void 0?ft:qe,ot=se.placement??"inline";if(ht){ht.style.display=Ze?"":"none";let{closeButtonWrapper:Vt}=Te;!Q()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Ze?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let an=ot==="top-right",Ln=ht.classList.contains("persona-absolute");if(!Q()&&an!==Ln&&Ze){if(ht.remove(),an)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",ve.style.position="relative",ve.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let qt=ve.querySelector(".persona-border-b-persona-divider"),Kn=Te.closeButtonWrapper;qt&&Kn&&Kn.parentElement===qt?qt.insertBefore(ht,Kn):qt&&qt.appendChild(ht)}let Ot=Te.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(an?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let go=se.size??"32px";He.style.height=go,He.style.width=go}let Vt=se.iconName??"refresh-cw",an=se.iconColor??"";He.style.color=an||Kt.actionIconColor,He.innerHTML="";let Ln=Q()?"14px":"20px",Ot=ae(Vt,Ln,"currentColor",1);if(Ot&&(Ot.style.display="block",He.appendChild(Ot)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let go=se.borderWidth||"0px",vs=se.borderColor||"transparent";He.style.border=`${go} solid ${vs}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let qt=se.tooltipText??"Clear chat",Kn=se.showTooltip??!0;He.setAttribute("aria-label",qt),ht&&_t({anchor:He,trigger:ht,text:()=>He?.getAttribute("aria-label")??qt,enabled:Kn})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],hn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick];H=Fc({parsers:jt,handlers:hn,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null}),Z=Cg(o,H,ge),_.updateConfig(o),is(xe,_.getMessages(),Z),lr(),gl(),ym(),Aa(_.isStreaming());let ys=o.voiceRecognition?.enabled===!0,La=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(ys&&(La||Mt))if(!oe||!pn){let se=Pm(o.voiceRecognition,o.sendButton);se&&(oe=se.micButton,pn=se.micButtonWrapper,xt.insertBefore(pn,W),oe.addEventListener("click",yr),oe.disabled=_.isStreaming())}else{let se=o.voiceRecognition??{},qe=o.sendButton??{},ft=se.iconName??"mic",Ze=qe.size??"40px",ot=se.iconSize??Ze,Vt=parseFloat(ot)||24;oe.style.width=ot,oe.style.height=ot,oe.style.minWidth=ot,oe.style.minHeight=ot;let an=se.iconColor??qe.textColor;oe.innerHTML="";let Ln=ae(ft,Vt,an||"currentColor",1.5);Ln?oe.appendChild(Ln):oe.textContent="\u{1F3A4}";let Ot=se.backgroundColor??qe.backgroundColor;Ot?oe.style.backgroundColor=Ot:oe.style.backgroundColor="",an?oe.style.color=an:oe.style.color="var(--persona-text, #111827)",se.borderWidth?(oe.style.borderWidth=se.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),se.borderColor?oe.style.borderColor=se.borderColor:oe.style.borderColor="",se.paddingX?(oe.style.paddingLeft=se.paddingX,oe.style.paddingRight=se.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),se.paddingY?(oe.style.paddingTop=se.paddingY,oe.style.paddingBottom=se.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let qt=se.tooltipText??"Start voice recognition",Kn=se.showTooltip??!1;oe.setAttribute("aria-label",qt),pn&&_t({anchor:oe,trigger:pn,text:()=>oe?.getAttribute("aria-label")??qt,enabled:Kn}),pn.style.display="",oe.disabled=_.isStreaming()}else oe&&pn&&(pn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Hn&&po());if(o.attachments?.enabled===!0){if(!un||!it){let se=o.attachments??{},ft=(o.sendButton??{}).size??"40px";Sn||(Sn=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",L.insertBefore(Sn,I)),St||(St=document.createElement("input"),St.type="file",St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),L.insertBefore(St,I)),un=b("div","persona-send-button-wrapper"),it=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=ft,Vt=parseFloat(ot)||40,an=Math.round(Vt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Ln=ae(Ze,an,"currentColor",1.5);Ln?it.appendChild(Ln):it.textContent="\u{1F4CE}",it.addEventListener("click",qt=>{qt.preventDefault(),St?.click()}),un.appendChild(it);let Ot=se.buttonTooltipText??"Attach file";_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??Ot}),dn?dn.append(un):L.appendChild(un),!yt&&St&&Sn&&(yt=Rs.fromConfig(se),yt.setPreviewsContainer(Sn),St.addEventListener("change",async()=>{yt&&St?.files&&(await yt.handleFileSelect(St.files),St.value="")}))}else{un.style.display="";let se=o.attachments??{};St&&(St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1),yt&&yt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(Ag(o.attachments?.dropOverlay)),it){let se=o.attachments??{},qe=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",qe),it.textContent="";let ft=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(ft*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",un&&_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??qe})}}else un&&(un.style.display="none"),yt&&yt.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},bs=Dt.useIcon??!1,Ia=Dt.iconText??"\u2191",vr=Dt.iconName,Wa=Dt.tooltipText??"Send message",kl=Dt.showTooltip??!1,jo=Dt.size??"40px",qn=Dt.backgroundColor,Vo=Dt.textColor;if(bs){if(h.style.width=jo,h.style.height=jo,h.style.minWidth=jo,h.style.minHeight=jo,h.style.fontSize="18px",h.style.lineHeight="1",Vo?h.style.color=Vo:h.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(h.innerHTML="",vr){let se=parseFloat(jo)||24,qe=Vo?.trim()||"currentColor",ft=ae(vr,se,qe,2);ft?h.appendChild(ft):h.textContent=Ia}else h.textContent=Ia;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),Vo?h.style.color=Vo:h.classList.add("persona-text-white");Dt.borderWidth?(h.style.borderWidth=Dt.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),Dt.borderColor?h.style.borderColor=Dt.borderColor:h.style.borderColor="",Dt.paddingX?(h.style.paddingLeft=Dt.paddingX,h.style.paddingRight=Dt.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),Dt.paddingY?(h.style.paddingTop=Dt.paddingY,h.style.paddingBottom=Dt.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),_.isStreaming()||h.setAttribute("aria-label",Wa),W&&_t({anchor:h,trigger:W,text:()=>h.getAttribute("aria-label")??Wa,enabled:kl});let wr=xo(o,Q());Xi(),wr?(xe.style.maxWidth=wr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=wr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",L&&(L.style.maxWidth=wr,L.style.marginLeft="auto",L.style.marginRight="auto"),M&&(M.style.maxWidth=wr,M.style.marginLeft="auto",M.style.marginRight="auto"),R.style.maxWidth=wr,R.style.marginLeft="auto",R.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",K.style.maxWidth="",K.style.marginLeft="",K.style.marginRight="",K.style.width="",L&&(L.style.maxWidth="",L.style.marginLeft="",L.style.marginRight=""),M&&(M.style.maxWidth="",M.style.marginLeft="",M.style.marginRight=""),R.style.maxWidth="",R.style.marginLeft="",R.style.marginRight="");let fo=o.statusIndicator??{},Fm=fo.visible??!0;if(R.style.display=Fm?"":"none",_){let se=_.getStatus();Cn(R,(ft=>ft==="idle"?fo.idleText??It.idle:ft==="connecting"?fo.connectingText??It.connecting:ft==="connected"?fo.connectedText??It.connected:ft==="error"?fo.errorText??It.error:It[ft])(se),fo,se)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Om=fo.align==="left"?"persona-text-left":fo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Om)},open(){ie()&<(!0,"api")},close(){ie()&<(!1,"api")},toggle(){ie()&<(!Y,"api")},reconnect(){_.reconnectNow()},clearChat(){On=!1,_.clearMessages(),Bo.clear(),io();try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!I||_.isStreaming()?!1:(!Y&&ie()&<(!0,"system"),I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let p=i?.trim()||I.value.trim();return p?(!Y&&ie()&<(!0,"system"),I.value="",I.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("user"),_.isVoiceActive()&&hr()})),!0):Hn?!0:op()?(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),Ma("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()}),!0):!1:Hn?(Ke.manuallyDeactivated=!0,kn(),po("user"),!0):!1},injectMessage(i){return!Y&&ie()&<(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Y&&ie()&<(!0,"system");let p=_.injectAssistantMessage(i);return ue&&(ue=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(i){return!Y&&ie()&<(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Y&&ie()&<(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&ie()&<(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&ie()&<(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Y&&ie()&<(!0,"system"),_.injectTestEvent(i)},async connectStream(i,p){return _.connectStream(i,p)},__pushEventStreamEvent(i){Oe&&(_e?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Oe||$i()},hideEventStream(){Se&&Jr()},isEventStreamVisible(){return Se},showArtifacts(){Jt(o)&&(On=!1,sr=!0,Nn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(On=!0,Nn())},upsertArtifact(i){return Jt(o)?(ho(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(On=!1,sr=!0),_.upsertArtifact(i)):null},selectArtifact(i){Jt(o)&&_.selectArtifact(i)},clearArtifacts(){Jt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return F&&!Y&&!Q()||!I?!1:(I.focus(),!0)},async resolveApproval(i,p,m){let x=_.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,p);return}return _.resolveApproval(x.approval,p,m)},setFollowUpSuggestions(i){Vg(i)},clearFollowUpSuggestions(){kd()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...g}},updatePersistentMetadata(i){S(i)},on(i,p){return c.on(i,p)},off(i,p){c.off(i,p)},isOpen(){return ie()&&Y},isVoiceActive(){return Ke.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:ie()&&Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=vg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=wg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,p){return _.submitCSATFeedback(i,p)},async submitNPSFeedback(i,p){return _.submitNPSFeedback(i,p)},destroy(){yl(),Uo!=null&&(clearInterval(Uo),Uo=null),Be.forEach(i=>i()),Le.remove(),tt?.remove(),Tt?.destroy(),Xt?.remove(),Ro&&de.removeEventListener("click",Ro)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,p={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:m=>m?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Be.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",p),Be.push(()=>{window.removeEventListener("persona:focusInput",p)}),me){let O=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.showEventStream()},V=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",V),Be.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",V)})}let m=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.showArtifacts()},y=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.hideArtifacts()},x=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||V?.artifact&&kt.upsertArtifact(V.artifact)},E=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||typeof V?.id=="string"&&kt.selectArtifact(V.id)},U=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",x),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",U),Be.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",x),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",U)})}let mn=uw(o.persistState);if(mn&&ie()){let i=fw(mn.storage),p=`${mn.keyPrefix}widget-open`,m=`${mn.keyPrefix}widget-voice`,y=`${mn.keyPrefix}widget-voice-mode`;if(i){let x=mn.persist?.openState&&i.getItem(p)==="true",E=mn.persist?.voiceState&&i.getItem(m)==="true",U=mn.persist?.voiceState&&i.getItem(y)==="true";if(x&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(E||U)kt.startVoiceRecognition();else if(mn.persist?.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0)),mn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(p,"true")}),c.on("widget:closed",()=>{i.setItem(p,"false")})),mn.persist?.voiceState&&(c.on("voice:state",O=>{i.setItem(m,O.active?"true":"false")}),c.on("user:message",O=>{i.setItem(y,O.viaVoice?"true":"false")})),mn.clearOnChatClear){let O=()=>{i.removeItem(p),i.removeItem(m),i.removeItem(y)},V=()=>O();window.addEventListener("persona:clear-chat",V),Be.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(C&&ie()&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fr(),!qg){let i=Ha(()=>{_&&(Qi++,Bo.clear(),is(xe,_.getMessages(),Z))});Be.push(i)}return kt};var Tg=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Mg=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},zc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",zc(e)},_c=e=>{e.style.transition=""},$c=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Uc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Oi=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vw=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ww=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},xw=e=>{let t=Rr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(t,r)??r;return{inset:o(n?.inset,ti),canvasBackground:o(n?.canvasBackground,ni)}},kg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Cw=(e,t,n,o,r,s,a,l)=>{let u=vn(s),d=u.reveal==="push",c=l!=null,f=l?.inset??"",w=l?.canvasBackground??"";vw(e,t,n,o,d),ww(e,t,n,o,u.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=u.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,T=g!=null?g.innerWidth<=C:!1;if(v&&T&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$c(t),_c(o),Eg(o),Uc(n),Oi(r,o),kg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Nt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Eg(o),hw(o,u.maxHeight),kg(o,c&&a,f,w),u.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$c(t),_c(o),Uc(n),Oi(r,o);let S=u.animate?"transform 180ms ease":"none",k=u.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":k;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=P,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_c(o),zc(o),Oi(r,o);let S=Tg(u.width,e.clientWidth),k=Math.max(0,e.clientWidth),P=u.animate?"margin-left 180ms ease":"none",H=u.side==="right"?a?-S:0:a?0:-S;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${k+S}px`,t.style.transition=P,t.style.marginLeft=`${H}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",$c(t),zc(o),Uc(n),Oi(r,o);let S=u.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?u.width:"0px",P=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",H=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${k}`,o.style.width=k,o.style.maxWidth=k,o.style.minWidth=k,o.style.minHeight="0",yw(o,u.maxHeight),o.style.overflow=S||H?"hidden":"visible",o.style.transition=P,S){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let F=c?`calc(${Tg(u.width,e.clientWidth)}px - (2 * ${f}))`:u.width;r.style.width=F,r.style.minWidth=F,r.style.maxWidth=F,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Mg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Mg(n,o)},destroy(){n.remove()}}},Sw=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),u=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),u.appendChild(e);let w=null,g=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?xw(t):null};C();let T=()=>{Cw(a,l,u,d,c,t,f,v)},B=null,S=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=oi(()=>{C(),T()}))},k=()=>{g(),vn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{T()}),w.observe(a)))},P=!1,H=()=>{T(),k(),f&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,bw(a,vn(t)))},F=a.ownerDocument.defaultView,N=()=>{H()};return F?.addEventListener("resize",N),vn(t).reveal==="push"?(l.appendChild(u),l.appendChild(d),a.appendChild(l)):(a.appendChild(u),a.appendChild(d)),H(),S(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let j=z.launcherEnabled?z.open:!0;f!==j&&(f=j,H())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(f=!0),C(),H(),S()},destroy(){F?.removeEventListener("resize",N),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Lg=(e,t)=>Rt(t)?Sw(e,t):Aw(e,t);var oa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Pg=.15,Ig=1.5,jc="persona-preview-shell-theme",Tw={load:()=>null,save:()=>{},clear:()=>{}},Mw=["How do I get started?","Pricing & plans","Talk to support"];function Vc(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ew(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Wg(e){let t=Ew(e);return`* { box-sizing: border-box; }
|
|
141
141
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
142
142
|
html { color-scheme: ${e}; }
|
|
143
143
|
body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
|
|
@@ -161,7 +161,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
161
161
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
162
162
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
163
163
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
|
|
164
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
164
|
+
.preview-workspace-card.short { height: 96px; }`}function Rg(e,t){let n=e.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(jc);o||(o=n.createElement("style"),o.id=jc,n.head.appendChild(o)),o.textContent=Wg(t)}var kw=`
|
|
165
165
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
166
166
|
<div class="preview-iframe-chrome">
|
|
167
167
|
<span class="preview-iframe-dot"></span>
|
|
@@ -180,7 +180,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
180
180
|
<div class="preview-iframe-line body"></div>
|
|
181
181
|
<div class="preview-iframe-line body"></div>
|
|
182
182
|
</div>
|
|
183
|
-
</div>`,
|
|
183
|
+
</div>`,Lw=`
|
|
184
184
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
185
185
|
<div class="preview-iframe-line hero"></div>
|
|
186
186
|
<div class="preview-iframe-line body"></div>
|
|
@@ -193,8 +193,8 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
193
193
|
<div class="preview-workspace-card short"></div>
|
|
194
194
|
<div class="preview-workspace-card short"></div>
|
|
195
195
|
</div>
|
|
196
|
-
</div>`;function
|
|
197
|
-
${
|
|
196
|
+
</div>`;function Hg(e,t,n,o){let r=`
|
|
197
|
+
${kw}
|
|
198
198
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${e}" data-mount-id="${e}"></div></div>`,s=`
|
|
199
199
|
<div class="preview-workspace-shell">
|
|
200
200
|
<div class="preview-workspace-topbar">
|
|
@@ -206,7 +206,7 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
206
206
|
</div>
|
|
207
207
|
<div class="preview-workspace-body">
|
|
208
208
|
<div id="preview-content-${e}" class="preview-workspace-content" data-mount-id="${e}">
|
|
209
|
-
${
|
|
209
|
+
${Lw}
|
|
210
210
|
</div>
|
|
211
211
|
</div>
|
|
212
212
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
214
214
|
<head>
|
|
215
215
|
<meta charset="UTF-8">
|
|
216
216
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
217
|
-
<link rel="stylesheet" href="${
|
|
218
|
-
<style id="${
|
|
217
|
+
<link rel="stylesheet" href="${Vc(o)}">
|
|
218
|
+
<style id="${jc}">${Wg(t)}</style>
|
|
219
219
|
</head>
|
|
220
220
|
<body>
|
|
221
221
|
${n?s:r}
|
|
222
222
|
</body>
|
|
223
|
-
</html>`}var
|
|
224
|
-
${
|
|
225
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
226
|
-
</div>`,
|
|
223
|
+
</html>`}var Pw=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Iw=e=>!!(e?.features?.toolCallDisplay?.activePreview||e?.features?.toolCallDisplay?.grouped||e?.features?.toolCallDisplay?.collapsedMode&&e.features.toolCallDisplay.collapsedMode!=="tool-call"||e?.features?.reasoningDisplay?.activePreview);function Ww(e,t,n=[]){if(e==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return e==="home"?[]:e==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:e==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:e==="conversation"&&Iw(t)?[...Pw(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Rw(e,t,n=[]){let o={...e.launcher,enabled:!0,autoExpand:t!=="minimized"},r={...e,launcher:o,suggestionChips:t==="home"?e.suggestionChips?.length?e.suggestionChips:Mw:e.suggestionChips,initialMessages:Ww(t,e,n),storageAdapter:Tw};return t==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Hw(e,t){let n=e.theme?Wr(e.theme,{validate:!1}):Wr();return{...rt,...e.config,theme:n,darkTheme:e.darkTheme,colorScheme:t??e.config?.colorScheme??"light"}}function Kr(e,t){let n=e.scene??"conversation";return Rw(Hw(e,t),n,e.appendedMessages??[])}function Bg(e){let t=e.compareMode??"off",n=e.shellMode??"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Kr(e,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Kr(e,"dark"),shellMode:"dark"}];if(t==="baseline"&&(e.baselineConfig||e.baselineTheme)){let o={...e,config:e.baselineConfig??e.config,theme:e.baselineTheme??e.theme,darkTheme:e.baselineDarkTheme??e.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Kr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Kr(e,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Kr(e,n),shellMode:n}]}function Bw(e,t){let n={...t},o=[],r=[],s=null,a=!1,l=1,u=1,d=0;function c(){return n.device??"desktop"}function f(){return n.zoom??l}function w(){let S=getComputedStyle(e),k=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),P=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),H=40,F=(n.compareMode??"off")!=="off",N=(e.clientWidth-k-H)/(F?2:1),z=e.clientHeight-P-H;if(N<=0||z<=0)return 1;let j=oa[c()]??oa.desktop;return Math.min(N/j.w,z/j.h,1)}function g(){l=w();let S=Math.max(Pg,Math.min(Ig,f()));u=S;let k=Array.from(e.querySelectorAll(".preview-iframe-wrapper"));for(let P of k){let H=P.dataset.device??"desktop",F=oa[H]??oa.desktop;P.style.width=`${F.w*S}px`,P.style.height=`${F.h*S}px`,H==="mobile"&&(P.style.borderRadius=`${32*S}px`);let N=P.querySelector("iframe");N&&(N.style.width=`${F.w}px`,N.style.height=`${F.h}px`,N.style.transformOrigin="top left",N.style.transition="none",N.style.transform=`scale(${S})`)}n.onScaleChange?.(S)}function v(){n.onBeforeDestroy?.();for(let S of o)S.destroy();for(let S of r)S();o=[],r=[]}function C(){return Array.from(e.querySelectorAll("iframe[data-mount-id]"))}function T(){if(a)return;v();let S=++d,k=Bg(n),P=c(),H=(n.compareMode??"off")!=="off",F=(n.scene??"conversation")==="minimized",N=n.widgetCssPath??"/widget-dist/widget.css",z=n.buildSrcdoc??Hg,j=P==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",te=ue=>`<div class="${j}" data-mount-id="${ue.mountId}" data-device="${P}" data-shell-mode="${ue.shellMode}">
|
|
224
|
+
${H?`<div class="preview-frame-meta"><span class="preview-frame-label">${Vc(ue.label)}</span></div>`:""}
|
|
225
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ue.mountId}"></iframe>
|
|
226
|
+
</div>`,A=H?`<div class="preview-compare-grid">${k.map(ue=>`<div class="preview-compare-cell">${te(ue)}</div>`).join("")}</div>`:`<div class="preview-single">${te(k[0])}</div>`;n.morphContainer?n.morphContainer(e,A):e.innerHTML=A,g();let G=C(),Q=0,ie=G.length,Y=()=>{if(a||S!==d)return;for(let X of G){let ge=X.dataset.mountId;if(!ge||!X.contentDocument)continue;let Z=k.find(he=>he.mountId===ge);if(!Z)continue;let pe=()=>{},ee=Rt(Z.config),me=ee?(()=>{let he=X.contentDocument?.getElementById(`preview-content-${ge}`);if(!he)return null;let ke=Lg(he,Z.config),Ne=X.contentDocument.createElement("div");Ne.id=ge,Ne.style.height="100%",Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1",Ne.style.minHeight="0",ke.host.appendChild(Ne);let Ue=()=>ke.syncWidgetState(we.getState()),Qe=pe;return pe=()=>{ke.destroy(),Qe()},Ne.__syncDock=Ue,Ne.__hostLayout=ke,Ne})():X.contentDocument.getElementById(ge);if(!me)continue;let we=Sg(me,Z.config);if(o.push(we),ee&&me.__syncDock){let he=me.__syncDock,ke=we.on("widget:opened",he),Ne=we.on("widget:closed",he),Ue=pe;pe=()=>{ke(),Ne(),Ue()},he()}r.push(pe),F&&we.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let X of o)X.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
227
227
|
|
|
228
228
|
This is a preview of the artifact sidebar.
|
|
229
229
|
|
|
@@ -231,4 +231,4 @@ This is a preview of the artifact sidebar.
|
|
|
231
231
|
|
|
232
232
|
- Markdown rendering
|
|
233
233
|
- Document toolbar
|
|
234
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:
|
|
234
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:G,controllers:[...o]})};for(let ue of G){let X=ue.dataset.mountId;if(!X)continue;let ge=k.find(Z=>Z.mountId===X);ge&&(ue.addEventListener("load",()=>{Q++,Q>=ie&&Y()},{once:!0}),ue.srcdoc=z(X,ge.shellMode,Rt(ge.config),N))}ie===0&&Y()}function B(){if(a)return;let S=Bg(n);if(o.length!==S.length){T();return}if(S.some(P=>{let H=e.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!H||H.dataset.shellMode!==P.shellMode})){T();return}o.forEach((P,H)=>{P.update(S[H].config),(n.scene??"conversation")==="minimized"&&P.close()});for(let P of S){let H=e.querySelector(`iframe[data-mount-id="${P.mountId}"]`);H&&Rg(H,P.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||g()}),s.observe(e)),T(),{update(S){if(a)return;let k=S.device!==void 0&&S.device!==n.device||S.scene!==void 0&&S.scene!==n.scene||S.compareMode!==void 0&&S.compareMode!==n.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==n.widgetCssPath;n={...n,...S},k?T():B()},destroy(){a||(a=!0,v(),s?.disconnect(),e.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return u},setZoom(S){a||(n={...n,zoom:S},g())}}}export{Bw as createThemePreview};
|