@runtypelabs/persona 4.3.0 → 4.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.global.js +3 -3
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +6 -0
- package/dist/smart-dom-reader.d.ts +6 -0
- package/dist/theme-editor-preview.cjs +3 -3
- package/dist/theme-editor-preview.d.cts +6 -0
- package/dist/theme-editor-preview.d.ts +6 -0
- package/dist/theme-editor-preview.js +3 -3
- package/dist/theme-editor.d.cts +6 -0
- package/dist/theme-editor.d.ts +6 -0
- package/dist/widget.css +3 -0
- package/package.json +1 -1
- package/src/components/launcher.ts +11 -1
- package/src/components/panel.ts +10 -6
- package/src/styles/widget.css +3 -0
- package/src/types.ts +6 -0
|
@@ -8,7 +8,7 @@ ${e}`:"")+(t.description?`
|
|
|
8
8
|
${t.description}`:"");return window.confirm(n)},Dg=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Ng=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Fg=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var Og="agent_",_g="flow_";function Kp(t){return t.startsWith(Og)?{kind:"agentId",agentId:t}:t.startsWith(_g)?{kind:"flowId",flowId:t}:null}function Gp(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=Kp(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Kp(n);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as $g,ARR as Ug,OBJ as zg,STR as qg}from"partial-json";var y=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Pr=(t,e,n)=>{let r=t.createElement(e);return n&&(r.className=n),r};var Et=(t,e={},...n)=>{let r=document.createElement(t);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Is=(...t)=>t.filter(Boolean).join(" ");var hi="ask_user_question",Ws=8,ts="data-persona-ask-sheet-for",jg="Other",Vg="Other\u2026",Xp="Type your own answer here",Jp="Send",Kg="Next",Gg="Back",Qg="Submit all",Xg="Skip",Jg=3,yi="data-ask-current-index",bi="data-ask-question-count",Yp="data-ask-answers",vi="data-ask-grouped",Zp="data-ask-layout",Yg=t=>t.layout==="pills"?"pills":"rows",Zg=t=>t.getAttribute(Zp)==="pills"?"pills":"rows",Qp=!1,eu=t=>t.replace(/["\\]/g,"\\$&"),Lo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===hi,wi=t=>{var e,n;return(n=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?n:{}},ns=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=$g(o,qg|zg|Ug);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Rs=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Ws&&!Qp&&(Qp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ws}.`)),e.slice(0,Ws)},ef=t=>{var e;return(e=Rs(t)[0])!=null?e:null},tf=(t,e)=>{var n;return(n=Rs(t)[e])!=null?n:null},nf=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},tu=(t,e,n)=>{if(t!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},rf=(t,e,n,r)=>{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",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let c=y("span","persona-ask-row-description");c.textContent=t.description,a.appendChild(c)}s.appendChild(a);let d=tu(n,r,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},of=t=>{let n=y("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},sf=(t,e,n,r)=>{var u,m,g;let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Jg;f++)s.appendChild(of(r));return s}if(d.forEach((f,w)=>{s.appendChild(rf(f,w,r,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=r==="rows"?jg:Vg;if(r==="rows"){let w=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=e.freeTextPlaceholder)!=null?u:Xp,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),v.appendChild(M),w.appendChild(v);let W=tu(r,a,d.length);W&&w.appendChild(W),s.appendChild(w)}else{let w=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(g=e.freeTextLabel)!=null?g:f,s.appendChild(w)}}return s},nu=(t,e)=>{var s,a;let r=y("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:Xp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:Jp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},af=t=>{var r;let e=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=t.submitLabel)!=null?r:Jp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},lf=(t,e,n)=>{var c,u,m,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Gg,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,r.appendChild(o);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=(u=n.skipLabel)!=null?u:Xg,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:Qg:(g=n.nextLabel)!=null?g:Kg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Po=t=>{let e=t.getAttribute(Yp);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},ru=(t,e)=>{t.setAttribute(Yp,JSON.stringify(e))},or=t=>{var n;let e=Number((n=t.getAttribute(yi))!=null?n:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},cf=(t,e)=>{t.setAttribute(yi,String(Math.max(0,Math.floor(e))))},rs=t=>{var n;let e=Number((n=t.getAttribute(bi))!=null?n:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},io=t=>t.getAttribute(vi)==="true",df=(t,e)=>{var o;let n=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},pf=(t,e)=>{var r;let n=(r=t.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},ba=(t,e)=>{let{payload:n}=ns(e),r=Rs(n),o=Po(t),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},ou=t=>{let e=Po(t),n=or(t),r=e[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},su=t=>{if(!io(t))return;let e=Po(t),n=or(t),r=e[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},xi=(t,e,n)=>{let r=wi(n),o=Zg(t),{payload:s,complete:a}=ns(e),i=io(t),d=or(t),c=rs(t),u=i?tf(s,d):ef(s),m=!!(u!=null&&u.multiSelect),g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let w=t.querySelector('[data-ask-question="true"]');if(w){let T=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=T,w.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let v=t.querySelector('[data-ask-pill-list="true"]');if(v){let T=sf(u,r,a,o);v.replaceWith(T)}if(o!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(nu(r,o))}let M=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!M?t.appendChild(af(r)):(!m||i)&&M&&M.remove(),t.setAttribute("data-multi-select",m?"true":"false");let W=t.querySelector('[data-ask-nav-row="true"]');if(i){let T=lf(d,c,r);W?W.replaceWith(T):t.appendChild(T)}else W&&W.remove();ou(t),su(t)},uf=(t,e,n)=>{let r=wi(e),o=Yg(r),s=t.toolCall.id,a=Rs(n),i=Math.max(1,a.length),d=i>1,c=df(t,a),u=d?pf(t,i):0,m=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(ts,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(bi,String(i)),m.setAttribute(yi,String(u)),m.setAttribute(vi,d?"true":"false"),m.setAttribute(Zp,o),ru(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),nf(m,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let w=y("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),m.appendChild(g);let M=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");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),m.appendChild(M),o!=="rows"&&m.appendChild(nu(r,o)),xi(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},mf=(t,e,n)=>{let{payload:r}=ns(e),o=Math.max(1,Rs(r).length);o>rs(t)&&(t.setAttribute(bi,String(o)),o>1&&!io(t)&&t.setAttribute(vi,"true")),xi(t,e,n)};var va=(t,e,n)=>{if(!n||!Lo(t)||wi(e).enabled===!1)return;let o=t.toolCall.id;n.querySelectorAll(`[${ts}]`).forEach(c=>{c.getAttribute(ts)!==o&&c.remove()});let a=n.querySelector(`[${ts}="${eu(o)}"]`);if(a){mf(a,t,e);return}let{payload:i}=ns(t),d=uf(t,e,i);n.appendChild(d)},os=(t,e)=>{if(!t)return;let n=e?`[${ts}="${eu(e)}"]`:`[${ts}]`;t.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Ci=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),lo=(t,e)=>{let n=Po(t),r=or(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[r]:n[r]=e,ru(t,n),ou(t),su(t)},wa=(t,e,n,r)=>{let o=rs(t),s=Math.max(0,Math.min(o-1,r));cf(t,s),xi(t,e,n)};var zr="suggest_replies";var gf={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},au={name:zr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:gf,origin:"sdk",annotations:{readOnlyHint:!0}},Ai=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Si=t=>{var e;return t.variant==="tool"&&((e=t.toolCall)==null?void 0:e.name)===zr},ff=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e==null?void 0:e.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},iu=t=>{var e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.role==="user")return null;if(!Si(r))continue;let o=ff((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},lu=t=>{var n;let e=(n=t==null?void 0:t.features)==null?void 0:n.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var hf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ws,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},yf={name:hi,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:hf,origin:"sdk",annotations:{readOnlyHint:!0}},Ti=t=>{var r;let e=[],n=(r=t==null?void 0:t.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&e.push(yf),lu(t)&&e.push(au),e};import{parse as bf,STR as vf,OBJ as wf}from"partial-json";var cu=t=>t.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),co=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},xf=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),n=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},du=t=>t.status==="complete"?xf(t):t.status==="pending"?"Waiting":"",Cf=t=>{var o,s,a;let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a: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 pu=t=>t.status==="complete"?Cf(t):"Using tool...",xa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Bs=t=>{var n,r,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return xa(e)},Ca=t=>{var n,r,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return xa(e)},Ei=(t,e,n)=>{var s;if(!e)return n;let r=((s=t.name)==null?void 0:s.trim())||"tool",o=Bs(t);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Aa=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Hs(r,n.slice(s,a.index),[]),a[1]!==void 0?Hs(r,a[1],["bold"]):a[2]!==void 0?Hs(r,a[2],["italic"]):a[3]!==void 0&&Hs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Hs(r,n.slice(s),[]),r},Hs=(t,e,n)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&t.push({text:r[o],styles:n}),o<r.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Af=()=>{let t=null,e=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);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*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async r=>{if(r.length<=e)return t!==null?{text:t,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(t=s),e=r.length,t!==null?{text:t,raw:r}:null},close:async()=>{}}},Ds=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},uu=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},mu=()=>{var e;let t=Af();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:t.processChunk(n)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},gu=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let o=bf(n,vf|wf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?cu(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=cu(o.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var fu=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(t=r[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var hu="4.3.0";var Ns=hu;var Tf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Ef(t){var s,a;let e=t.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Mi=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Mf(t){switch(t){case"json":return gu;case"regex-json":return mu;case"xml":return fu;default:return uu}}var yu=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function kf(t,e){if(!t)return e;let n=t.trim(),r=e.trim();if(n.length===0)return e;if(r.length===0)return t;let o=yu(n);if(!yu(r))return t;if(!o||r===n||r.startsWith(n))return e;let a=Ds(t);return Ds(e)!==null&&a===null?e:t}var Fs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=e.apiUrl)!=null?n:Tf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ns,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Mf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:n};let s=Gp(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(e=this.config).onSessionInit)==null||n.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Mi).map(E=>{var P,C,L;return{id:E.id,role:E.role,content:(L=(C=(P=E.contentParts)!=null?P:E.llmContent)!=null?C:E.rawContent)!=null?L:E.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,f=!!(g&&g.length>0),w=f?jp(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&v&&this.lastSentClientToolsFingerprint===w,W=!1,T=null,k;for(let E=0;;E++){let C={...m,...f&&(W||!M)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(C),signal:r.signal}),k.status===409&&E===0&&f){let L=await k.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){W=!0,this.lastSentClientToolsFingerprint=null;continue}T=L!=null?L:{error:"Chat request failed"}}break}if(!k.ok){let E=T!=null?T:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(E.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(e,n,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Mi).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let m=new Date(c.createdAt).getTime(),g=new Date(u.createdAt).getTime();return m-g}).map(c=>{var u,m,g;return{role:c.role,content:(g=(m=(u=c.contentParts)!=null?u:c.llmContent)!=null?m:c.rawContent)!=null?g:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ti(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async u=>{try{let m=await u({messages:e,config:this.config});m&&typeof m=="object"&&Object.assign(c,m)}catch(m){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",m)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let n=e.slice().filter(Mi).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),m=new Date(c.createdAt).getTime();return u-m}).map(d=>{var c,u,m;return{role:d.role,content:(m=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?m:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Ti(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=m,o(m),m},c=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,n,r){var Bt,Xt,Ir,hr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Re=A.tools?A.tools.map(ke=>({...ke,chunks:ke.chunks?[...ke.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:Re}},m=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{m(A)&&n({type:"message",message:u(A)})},f=null,w=null,v={current:null},M={current:null},W=null,T="",k=new Map,E=new Map,P=new Map,C=new Map,L=new Map,F={lastId:null,byStep:new Map},O={lastId:null,byCall:new Map},R=A=>{if(A==null)return null;try{return String(A)}catch{return null}},$=A=>{var te,Te,Re,ke,Be;return R((Be=(ke=(Re=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?Re:A.parentId)!=null?ke:A.flowStepId)!=null?Be:A.flow_step_id)},N=A=>{var te,Te,Re,ke,Be,Ve,at;return R((at=(Ve=(Be=(ke=(Re=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?Re:A.request_id)!=null?ke:A.toolCallId)!=null?Be:A.tool_call_id)!=null?Ve:A.stepId)!=null?at:A.step_id)},Z=r,Se=!1,pe=()=>{if(f)return f;let A,te=W;return!Se&&Z?(A=Z,Se=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},ve=(A,te)=>{var Be;let Te=(Be=A.reasoningId)!=null?Be:A.id,Re=$(A);if(Te){let Ve=String(Te);return ee(Re,Ve),Ve}if(Re){let Ve=F.byStep.get(Re);if(Ve)return F.lastId=Ve,Ve}if(F.lastId&&!te)return F.lastId;if(!te)return null;let ke=`reason-${c()}`;return ee(Re,ke),ke},Ie=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},ce=(A,te)=>{O.lastId=te,A&&O.byCall.set(A,te)},ue=new Set,oe=new Map,se=new Set,de=new Map,$e=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Ne=(A,te)=>{var Be;let Te=(Be=A.toolId)!=null?Be:A.id,Re=N(A);if(Te){let Ve=String(Te);return ce(Re,Ve),Ve}if(Re){let Ve=O.byCall.get(Re);if(Ve)return O.lastId=Ve,Ve}if(O.lastId&&!te)return O.lastId;if(!te)return null;let ke=`tool-${c()}`;return ce(Re,ke),ke},V=A=>{let te=L.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:A,status:"pending"}};return L.set(A,Te),g(Te),Te},G=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},be=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},X=new Map,le=new Map,Ee=new Map,Xe=(A,te,Te)=>{var at;let Re=Ee.get(A);Re||(Re=[],Ee.set(A,Re));let ke=0,Be=Re.length;for(;ke<Be;){let Pt=ke+Be>>>1;Re[Pt].seq<te?ke=Pt+1:Be=Pt}((at=Re[ke])==null?void 0:at.seq)===te?Re[ke]={seq:te,text:Te}:Re.splice(ke,0,{seq:te,text:Te});let Ve="";for(let Pt=0;Pt<Re.length;Pt++)Ve+=Re[Pt].text;return Ve},Ze=(A,te)=>{let Te=be(te),Re=le.get(A.id),ke=kf(Re,Te);A.rawContent=ke;let Be=X.get(A.id),Ve=J=>{var it;let Ae=(it=A.content)!=null?it:"";J.trim()!==""&&(Ae.trim().length===0||J.startsWith(Ae)||J.trimStart().startsWith(Ae.trim()))&&(A.content=J)},at=()=>{var J;if(Be){let Ae=(J=Be.close)==null?void 0:J.call(Be);Ae instanceof Promise&&Ae.catch(()=>{})}X.delete(A.id),le.delete(A.id),A.streaming=!1,g(A)};if(!Be){Ve(Te),at();return}let Pt=Ds(ke);if(Pt!==null&&Pt.trim()!==""){Ve(Pt),at();return}let bt=J=>{var Qe;let Ae=typeof J=="string"?J:(Qe=J==null?void 0:J.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!=="")return Ae;let it=Be.getExtractedText();return it!==null&&it.trim()!==""?it:Te},H;try{H=Be.processChunk(ke)}catch{Ve(Te),at();return}if(H instanceof Promise){H.then(J=>{Ve(bt(J)),at()}).catch(()=>{Ve(Te),at()});return}Ve(bt(H)),at()},xt=null,dt=(A,te,Te,Re)=>{var Pt;A.rawContent=te,X.has(A.id)||X.set(A.id,this.createStreamParser());let ke=X.get(A.id),Be=te.trim().startsWith("{")||te.trim().startsWith("[");if(Be&&le.set(A.id,te),ke.__isPlainTextParser===!0){A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A);return}let at=ke.processChunk(te);if(at instanceof Promise)at.then(bt=>{var J;let H=typeof bt=="string"?bt:(J=bt==null?void 0:bt.text)!=null?J:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let Re=le.get(A.id),ke=Re!=null?Re:be(Te);A.rawContent=ke;let Be=X.get(A.id),Ve=null,at=!1;if(Be&&(Ve=Be.getExtractedText(),Ve===null&&(Ve=Ds(ke)),Ve===null)){let H=Be.processChunk(ke);H instanceof Promise?(at=!0,H.then(J=>{var it;let Ae=typeof J=="string"?J:(it=J==null?void 0:J.text)!=null?it:null;Ae!==null&&(A.content=Ae,A.streaming=!1,X.delete(A.id),le.delete(A.id),g(A))}).catch(()=>{})):Ve=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!at){Ve!==null&&Ve.trim()!==""?A.content=Ve:le.has(A.id)||(A.content=be(Te));let H=X.get(A.id);if(H){let J=(bt=H.close)==null?void 0:bt.call(H);J instanceof Promise&&J.catch(()=>{}),X.delete(A.id)}le.delete(A.id),A.streaming=!1,g(A)}},He=(A,te,Te)=>{let Re=E.get(A);if(Re)return Re;let ke={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return E.set(A,ke),g(ke),ke},K=[],qe,ze=new Map,we=0,Ce="agent",tt=!1,Ot=null,ne=null,Oe=new Map,gn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(qe=()=>{var A,te,Te,Re,ke,Be,Ve,at,Pt,bt,H,J,Ae,it,Qe,Ut,fn,vt,wt,It,Ct,ln,_t,Nn,Sn,Tn,bn,En,ar,At,yr,br,Wr,ir,ut,mo,vr,go,Wn,Oo,Kr,Rr,Gr,Qr,fo,ho,Xr,yt,Fn,On,Mn,St,Xn,Jn,_n,Jr,Hr,Yr,$n,Wt,kn,Yn,Zr,Br,eo,he,Rn,wr,mt,nn,rn,xr,hs,Dr,yo,Cr,U,_o,Ar,Sr,Nr,Tr,lr,$o,sa,Un,zn,cr,dr,bo,Fr,vn,Er,Uo,vo,zo,aa,qo,ia,jo,pt,ys,Zn,Hn,la;for(let Vo=0;Vo<K.length;Vo++){let et=K[Vo].payloadType,x=K[Vo].payload;if(!tt&&Ce!=="flow"&&typeof x.stepType=="string"&&(Ce="flow"),et==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&z){k.set(j,z),He(j,z,"reasoning");continue}let Q=(A=ve(x,!0))!=null?A:`reason-${c()}`,ge=Ie(Q);ge.reasoning=(te=ge.reasoning)!=null?te:{id:Q,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Re=ge.reasoning.startedAt)!=null?Re:G((Te=x.startedAt)!=null?Te:x.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(ge.reasoning.scope=x.scope),ge.streaming=!0,ge.reasoning.status="streaming",g(ge)}else if(et==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)&&E.has(j)){let Fe=E.get(j),gt=(Ve=(Be=(ke=x.reasoningText)!=null?ke:x.text)!=null?Be:x.delta)!=null?Ve:"";gt&&x.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let z=(Pt=(at=ve(x,!1))!=null?at:ve(x,!0))!=null?Pt:`reason-${c()}`,Q=Ie(z);Q.reasoning=(bt=Q.reasoning)!=null?bt:{id:z,status:"streaming",chunks:[]},Q.reasoning.startedAt=(J=Q.reasoning.startedAt)!=null?J:G((H=x.startedAt)!=null?H:x.timestamp);let ge=(Qe=(it=(Ae=x.reasoningText)!=null?Ae:x.text)!=null?it:x.delta)!=null?Qe:"";if(ge&&x.hidden!==!0){let Fe=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Fe!==void 0){let gt=Xe(z,Fe,String(ge));Q.reasoning.chunks=[gt]}else Q.reasoning.chunks.push(String(ge))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=G((Ut=x.completedAt)!=null?Ut:x.timestamp);let Fe=(fn=Q.reasoning.startedAt)!=null?fn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-Fe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(et==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)&&E.has(j)){let gt=E.get(j);if(gt.reasoning){let ot=typeof x.text=="string"?x.text:"";ot&>.reasoning.chunks.length===0&>.reasoning.chunks.push(ot),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(j),E.delete(j);continue}let z=(It=(wt=ve(x,!1))!=null?wt:ve(x,!0))!=null?It:`reason-${c()}`,Q=typeof x.text=="string"?x.text:"";!C.get(z)&&(Q||x.scope==="loop")&&Ie(z);let ge=C.get(z);if(ge!=null&&ge.reasoning){(x.scope==="loop"||x.scope==="turn")&&(ge.reasoning.scope=x.scope),Q&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(Q),ge.reasoning.status="complete",ge.reasoning.completedAt=G((Ct=x.completedAt)!=null?Ct:x.timestamp);let gt=(ln=ge.reasoning.startedAt)!=null?ln:Date.now();ge.reasoning.durationMs=Math.max(0,((_t=ge.reasoning.completedAt)!=null?_t:Date.now())-gt),ge.streaming=!1,g(ge)}let Fe=$(x);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(Sn=(Nn=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?Nn:Ne(x,!0))!=null?Sn:`tool-${c()}`,z=(Tn=x.toolName)!=null?Tn:x.name;if($e(z)){ue.add(j);continue}ce(N(x),j);let Q=V(j),ge=(bn=Q.toolCall)!=null?bn:{id:j,status:"pending"};ge.name=z!=null?z:ge.name,ge.status="running",x.parameters!==void 0?ge.args=x.parameters:x.args!==void 0&&(ge.args=x.args),ge.startedAt=(ar=ge.startedAt)!=null?ar:G((En=x.startedAt)!=null?En:x.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,Q.toolCall=ge,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),g(Q)}else if(et==="tool_output_delta"){let j=(yr=(At=Ne(x,!1))!=null?At:Ne(x,!0))!=null?yr:`tool-${c()}`;if(ue.has(j))continue;let z=V(j),Q=(br=z.toolCall)!=null?br:{id:j,status:"running"};Q.startedAt=(ir=Q.startedAt)!=null?ir:G((Wr=x.startedAt)!=null?Wr:x.timestamp);let ge=(vr=(mo=(ut=x.text)!=null?ut:x.delta)!=null?mo:x.message)!=null?vr:"";ge&&(Q.chunks=(go=Q.chunks)!=null?go:[],Q.chunks.push(String(ge))),Q.status="running",z.toolCall=Q,z.streaming=!0;let Fe=x.agentContext;(Fe||x.executionId)&&(z.agentMetadata=(Kr=z.agentMetadata)!=null?Kr:{executionId:(Wn=Fe==null?void 0:Fe.executionId)!=null?Wn:x.executionId,iteration:(Oo=Fe==null?void 0:Fe.iteration)!=null?Oo:x.iteration}),g(z)}else if(et==="tool_complete"){let j=(Gr=(Rr=Ne(x,!1))!=null?Rr:Ne(x,!0))!=null?Gr:`tool-${c()}`;if(ue.has(j)){ue.delete(j);continue}let z=V(j),Q=(Qr=z.toolCall)!=null?Qr:{id:j,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=G((fo=x.completedAt)!=null?fo:x.timestamp);let ge=(ho=x.duration)!=null?ho:x.executionTime;if(typeof ge=="number")Q.durationMs=ge;else{let ot=(Xr=Q.startedAt)!=null?Xr:Date.now();Q.durationMs=Math.max(0,((yt=Q.completedAt)!=null?yt:Date.now())-ot)}z.toolCall=Q,z.streaming=!1;let Fe=x.agentContext;(Fe||x.executionId)&&(z.agentMetadata=(Mn=z.agentMetadata)!=null?Mn:{executionId:(Fn=Fe==null?void 0:Fe.executionId)!=null?Fn:x.executionId,iteration:(On=Fe==null?void 0:Fe.iteration)!=null?On:x.iteration}),g(z);let gt=N(x);gt&&O.byCall.delete(gt)}else if(et==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,z=(St=j!=null?j:x.toolId)!=null?St:`local-${c()}`,Q=V(z),ge=x.toolName,Fe=x.origin==="webmcp"&&!es(ge)?`webmcp:${ge}`:ge,gt=es(Fe),ot=(Xn=Q.toolCall)!=null?Xn:{id:z,status:"pending"};ot.name=Fe,ot.args=x.parameters,ot.status=gt?"running":"complete",ot.chunks=(Jn=ot.chunks)!=null?Jn:[],ot.startedAt=(Hr=ot.startedAt)!=null?Hr:G((Jr=(_n=x.startedAt)!=null?_n:x.timestamp)!=null?Jr:x.awaitedAt),gt?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(Yr=ot.completedAt)!=null?Yr:ot.startedAt,Q.toolCall=ot,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=x.executionId)!=null?Wt:($n=Q.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(et==="text_start"){let j=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&z){k.set(j,z);continue}let Q=f;Q&&(Ce==="flow"?(Ye(Q),xt=Q):(Q.streaming=!1,g(Q)),f=null),W=typeof x.id=="string"?x.id:W,T=""}else if(et==="text_delta"){let j=typeof x.id=="string"?x.id:null,z=j?k.get(j):void 0;if(j&&z){let ge=typeof x.delta=="string"?x.delta:"",Fe=((kn=P.get(j))!=null?kn:"")+ge;if(P.set(j,Fe),Fe.trim()==="")continue;let gt=He(j,z);gt.agentMetadata={...gt.agentMetadata,executionId:x.executionId,parentToolId:z},dt(gt,Fe,ge,void 0);continue}if(W=typeof x.id=="string"?x.id:W,Ce==="flow"){let ge=typeof x.delta=="string"?x.delta:"";if(T+=ge,T.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:x.executionId,iteration:x.iteration},dt(Fe,T,ge,void 0),w=Fe;continue}let Q=pe();Q.content+=(Yn=x.delta)!=null?Yn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:Ot!=null?Ot:void 0,agentName:ne==null?void 0:ne.agentName},w=Q,g(Q)}else if(et==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)){let Q=E.get(j);Q&&Ye(Q),k.delete(j),P.delete(j),E.delete(j);continue}let z=f;z&&(Ce==="flow"?(Ye(z),xt=z):(((Zr=z.content)!=null?Zr:"")===""&&typeof x.text=="string"&&(z.content=x.text),z.streaming=!1,g(z)),f=null),W=null,T=""}else if(et==="step_complete"){let j=x.stepType,z=x.executionType;if(j==="tool"||z==="context")continue;if(x.success===!1){let Q=x.error,ge=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Br=Q.message)!=null?Br:"Step failed"):"Step failed";n({type:"error",error:new Error(ge)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let Q=xt;xt=null;let ge=x.stopReason,Fe=(eo=x.result)==null?void 0:eo.response;if(Q)ge&&(Q.stopReason=ge),Fe!=null?Ze(Q,Fe):Q.streaming!==!1&&(X.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let gt=Fe!=null&&Fe!=="";if(gt||ge){let ot=pe();ge&&(ot.stopReason=ge),gt?Ye(ot,Fe):(ot.streaming=!1,g(ot))}}continue}}else if(et==="execution_start")Ce=x.kind==="flow"?"flow":"agent",tt=!0,Ce==="agent"&&(ne={executionId:x.executionId,agentId:(he=x.agentId)!=null?he:"virtual",agentName:(Rn=x.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(wr=x.maxTurns)!=null?wr:1,startedAt:G(x.startedAt)});else if(et==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(ne&&(ne.currentIteration=j),gn==="separate"&&j>1){let z=f;z&&(z.streaming=!1,g(z),Oe.set(j-1,z),f=null)}we=j}Ot=typeof x.id=="string"?x.id:null,w=null}else if(et==="tool_input_delta"){let j=(mt=x.toolCallId)!=null?mt:O.lastId;if(j){let z=L.get(j);z!=null&&z.toolCall&&(z.toolCall.chunks=(nn=z.toolCall.chunks)!=null?nn:[],z.toolCall.chunks.push((rn=x.delta)!=null?rn:""),g(z))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let j=x.stopReason,z=f!=null?f:w;if(j&&z!==null){let Q=x.id;(!Q||((xr=z.agentMetadata)==null?void 0:xr.turnId)===Q)&&(z.stopReason=j,g(z))}Ot===x.id&&(Ot=null)}else if(et==="media_start"){let j=String(x.id);ze.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(et==="media_delta"){let j=ze.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(et==="media_complete"){let j=String(x.id),z=ze.get(j);ze.delete(j);let Q=(Dr=(hs=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?hs:z==null?void 0:z.mediaType)!=null?Dr:"application/octet-stream",ge=typeof x.data=="string"?x.data:void 0,Fe=typeof x.url=="string"?x.url:z&&z.parts.length>0?z.parts.join(""):void 0,gt=null;if(ge)gt={type:"media",data:ge,mediaType:Q};else if(Fe){let cn=Q.toLowerCase();gt={type:cn==="image"||cn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:Q}}let ot=(yo=x.toolCallId)!=null?yo:z==null?void 0:z.toolCallId,bs=gt?[gt]:[],Bn=[];for(let cn of bs){if(!cn||typeof cn!="object")continue;let dn=cn,wo=typeof dn.type=="string"?dn.type:void 0,Or=typeof dn.mediaType=="string"?dn.mediaType.toLowerCase():"",Ln=null,hn="";if(wo==="media"){let qn=typeof dn.data=="string"?dn.data:void 0;if(!qn)continue;hn=Or.length>0?Or:"application/octet-stream",Ln=`data:${hn};base64,${qn}`}else if(wo==="image-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else if(wo==="file-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else continue;if(Ln)if(wo==="image-url"||hn.startsWith("image/"))Bn.push({type:"image",image:Ln,...hn.includes("/")?{mimeType:hn}:{}});else if(hn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:hn});else if(hn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:hn});else{let qn=hn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Ef(qn)})}}if(Bn.length>0){let cn=c(),dn=ot,Or={id:`agent-media-${typeof dn=="string"&&dn.length>0?`${dn}-${cn}`:String(cn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:cn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};g(Or);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,v.current=null}}else if(et==="execution_complete"){let j=(Cr=x.kind)!=null?Cr:Ce;j==="agent"&&ne&&(ne.status=x.success?"complete":"error",ne.completedAt=G(x.completedAt),ne.stopReason=x.stopReason);let z=f;z&&(j==="flow"&&z.streaming!==!1?Ye(z):(z.streaming=!1,g(z)),f=null),W=null,T="",xt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let j=typeof x.error=="string"?x.error:(_o=(U=x.error)==null?void 0:U.message)!=null?_o:"Execution error";n({type:"error",error:new Error(j)})}else if(et!=="ping"){if(et==="approval_start"){let j=(Ar=x.approvalId)!=null?Ar:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(Sr=ne==null?void 0:ne.agentId)!=null?Sr:"virtual",executionId:(Tr=(Nr=x.executionId)!=null?Nr:ne==null?void 0:ne.executionId)!=null?Tr:"",toolName:(lr=x.toolName)!=null?lr:"",toolType:x.toolType,description:(sa=x.description)!=null?sa:`Execute ${($o=x.toolName)!=null?$o:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(z)}else if(et==="step_await"&&x.awaitReason==="approval_required"){let j=(Un=x.approvalId)!=null?Un:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(zn=ne==null?void 0:ne.agentId)!=null?zn:"virtual",executionId:(dr=(cr=x.executionId)!=null?cr:ne==null?void 0:ne.executionId)!=null?dr:"",toolName:(bo=x.toolName)!=null?bo:"",toolType:x.toolType,description:(vn=x.description)!=null?vn:`Execute ${(Fr=x.toolName)!=null?Fr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(z)}else if(et==="approval_complete"){let j=x.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(Er=x.decision)!=null?Er:"approved",agentId:(Uo=ne==null?void 0:ne.agentId)!=null?Uo:"virtual",executionId:(zo=(vo=x.executionId)!=null?vo:ne==null?void 0:ne.executionId)!=null?zo:"",toolName:(aa=x.toolName)!=null?aa:"",description:(qo=x.description)!=null?qo:"",resolvedAt:Date.now()}};g(Q)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let j=x.artifactType,z=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(n({type:"artifact_start",id:z,artifactType:j,title:Q,component:typeof x.component=="string"?x.component:void 0}),de.set(z,{markdown:"",title:Q}),!se.has(z)){se.add(z);let ge={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:Q,artifactType:j,status:"streaming"}})};oe.set(z,ge),g(ge)}}else if(et==="artifact_delta"){let j=String(x.id),z=typeof x.delta=="string"?x.delta:String((ia=x.delta)!=null?ia:"");n({type:"artifact_delta",id:j,artDelta:z});let Q=de.get(j);Q&&(Q.markdown+=z)}else if(et==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(et==="artifact_complete"){let j=String(x.id);n({type:"artifact_complete",id:j});let z=oe.get(j);if(z){z.streaming=!1;try{let Q=JSON.parse((jo=z.rawContent)!=null?jo:"{}");if(Q.props){Q.props.status="complete";let ge=de.get(j);ge!=null&&ge.markdown&&(Q.props.markdown=ge.markdown)}z.rawContent=JSON.stringify(Q)}catch{}de.delete(j),g(z),oe.delete(j)}}}else if(et==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let z=String((pt=j.id)!=null?pt:`msg-${c()}`),Q=j.role,Fe={id:z,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),ot=(ys=gt==null?void 0:gt.props)==null?void 0:ys.artifactId;typeof ot=="string"&&se.add(ot)}catch{}f=null,v.current=null,X.delete(z),le.delete(z)}else if(et==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Zn=x.error)==null?void 0:Zn.message)!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(j)});let z=f;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(et==="dispatch_error"){let z=(Hn=x.message)!=null?Hn:x.error;z!=null&&z!==""&&(j=new Error(String(z)))}else{let z=x.error;typeof z=="string"&&z!==""?j=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&(j=new Error(String((la=z.message)!=null?la:z)))}if(j){n({type:"error",error:j});let z=f;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}K.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async r=>{if(r.length<=e)return t!==null?{text:t,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(t=s),e=r.length,t!==null?{text:t,raw:r}:null},close:async()=>{}}},Ds=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},uu=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},mu=()=>{var e;let t=Af();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:t.processChunk(n)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},gu=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let o=bf(n,vf|wf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?cu(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=cu(o.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var fu=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(t=r[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var hu="4.4.0";var Ns=hu;var Tf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Ef(t){var s,a;let e=t.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Mi=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Mf(t){switch(t){case"json":return gu;case"regex-json":return mu;case"xml":return fu;default:return uu}}var yu=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function kf(t,e){if(!t)return e;let n=t.trim(),r=e.trim();if(n.length===0)return e;if(r.length===0)return t;let o=yu(n);if(!yu(r))return t;if(!o||r===n||r.startsWith(n))return e;let a=Ds(t);return Ds(e)!==null&&a===null?e:t}var Fs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=e.apiUrl)!=null?n:Tf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ns,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Mf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:n};let s=Gp(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(e=this.config).onSessionInit)==null||n.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Mi).map(E=>{var P,C,L;return{id:E.id,role:E.role,content:(L=(C=(P=E.contentParts)!=null?P:E.llmContent)!=null?C:E.rawContent)!=null?L:E.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,f=!!(g&&g.length>0),w=f?jp(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&v&&this.lastSentClientToolsFingerprint===w,W=!1,T=null,k;for(let E=0;;E++){let C={...m,...f&&(W||!M)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ns},body:JSON.stringify(C),signal:r.signal}),k.status===409&&E===0&&f){let L=await k.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){W=!0,this.lastSentClientToolsFingerprint=null;continue}T=L!=null?L:{error:"Chat request failed"}}break}if(!k.ok){let E=T!=null?T:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(E.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(e,n,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Mi).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let m=new Date(c.createdAt).getTime(),g=new Date(u.createdAt).getTime();return m-g}).map(c=>{var u,m,g;return{role:c.role,content:(g=(m=(u=c.contentParts)!=null?u:c.llmContent)!=null?m:c.rawContent)!=null?g:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ti(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async u=>{try{let m=await u({messages:e,config:this.config});m&&typeof m=="object"&&Object.assign(c,m)}catch(m){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",m)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let n=e.slice().filter(Mi).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),m=new Date(c.createdAt).getTime();return u-m}).map(d=>{var c,u,m;return{role:d.role,content:(m=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?m:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Ti(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=m,o(m),m},c=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,n,r){var Bt,Xt,Ir,hr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Re=A.tools?A.tools.map(ke=>({...ke,chunks:ke.chunks?[...ke.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:Re}},m=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{m(A)&&n({type:"message",message:u(A)})},f=null,w=null,v={current:null},M={current:null},W=null,T="",k=new Map,E=new Map,P=new Map,C=new Map,L=new Map,F={lastId:null,byStep:new Map},O={lastId:null,byCall:new Map},R=A=>{if(A==null)return null;try{return String(A)}catch{return null}},$=A=>{var te,Te,Re,ke,Be;return R((Be=(ke=(Re=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?Re:A.parentId)!=null?ke:A.flowStepId)!=null?Be:A.flow_step_id)},N=A=>{var te,Te,Re,ke,Be,Ve,at;return R((at=(Ve=(Be=(ke=(Re=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?Re:A.request_id)!=null?ke:A.toolCallId)!=null?Be:A.tool_call_id)!=null?Ve:A.stepId)!=null?at:A.step_id)},Z=r,Se=!1,pe=()=>{if(f)return f;let A,te=W;return!Se&&Z?(A=Z,Se=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},ve=(A,te)=>{var Be;let Te=(Be=A.reasoningId)!=null?Be:A.id,Re=$(A);if(Te){let Ve=String(Te);return ee(Re,Ve),Ve}if(Re){let Ve=F.byStep.get(Re);if(Ve)return F.lastId=Ve,Ve}if(F.lastId&&!te)return F.lastId;if(!te)return null;let ke=`reason-${c()}`;return ee(Re,ke),ke},Ie=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},ce=(A,te)=>{O.lastId=te,A&&O.byCall.set(A,te)},ue=new Set,oe=new Map,se=new Set,de=new Map,$e=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Ne=(A,te)=>{var Be;let Te=(Be=A.toolId)!=null?Be:A.id,Re=N(A);if(Te){let Ve=String(Te);return ce(Re,Ve),Ve}if(Re){let Ve=O.byCall.get(Re);if(Ve)return O.lastId=Ve,Ve}if(O.lastId&&!te)return O.lastId;if(!te)return null;let ke=`tool-${c()}`;return ce(Re,ke),ke},V=A=>{let te=L.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:A,status:"pending"}};return L.set(A,Te),g(Te),Te},G=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},be=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},X=new Map,le=new Map,Ee=new Map,Xe=(A,te,Te)=>{var at;let Re=Ee.get(A);Re||(Re=[],Ee.set(A,Re));let ke=0,Be=Re.length;for(;ke<Be;){let Pt=ke+Be>>>1;Re[Pt].seq<te?ke=Pt+1:Be=Pt}((at=Re[ke])==null?void 0:at.seq)===te?Re[ke]={seq:te,text:Te}:Re.splice(ke,0,{seq:te,text:Te});let Ve="";for(let Pt=0;Pt<Re.length;Pt++)Ve+=Re[Pt].text;return Ve},Ze=(A,te)=>{let Te=be(te),Re=le.get(A.id),ke=kf(Re,Te);A.rawContent=ke;let Be=X.get(A.id),Ve=J=>{var it;let Ae=(it=A.content)!=null?it:"";J.trim()!==""&&(Ae.trim().length===0||J.startsWith(Ae)||J.trimStart().startsWith(Ae.trim()))&&(A.content=J)},at=()=>{var J;if(Be){let Ae=(J=Be.close)==null?void 0:J.call(Be);Ae instanceof Promise&&Ae.catch(()=>{})}X.delete(A.id),le.delete(A.id),A.streaming=!1,g(A)};if(!Be){Ve(Te),at();return}let Pt=Ds(ke);if(Pt!==null&&Pt.trim()!==""){Ve(Pt),at();return}let bt=J=>{var Qe;let Ae=typeof J=="string"?J:(Qe=J==null?void 0:J.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!=="")return Ae;let it=Be.getExtractedText();return it!==null&&it.trim()!==""?it:Te},H;try{H=Be.processChunk(ke)}catch{Ve(Te),at();return}if(H instanceof Promise){H.then(J=>{Ve(bt(J)),at()}).catch(()=>{Ve(Te),at()});return}Ve(bt(H)),at()},xt=null,dt=(A,te,Te,Re)=>{var Pt;A.rawContent=te,X.has(A.id)||X.set(A.id,this.createStreamParser());let ke=X.get(A.id),Be=te.trim().startsWith("{")||te.trim().startsWith("[");if(Be&&le.set(A.id,te),ke.__isPlainTextParser===!0){A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A);return}let at=ke.processChunk(te);if(at instanceof Promise)at.then(bt=>{var J;let H=typeof bt=="string"?bt:(J=bt==null?void 0:bt.text)!=null?J:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!Be&&!te.trim().startsWith("<")&&(A.content=Re!==void 0?te:A.content+Te,le.delete(A.id),X.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let Re=le.get(A.id),ke=Re!=null?Re:be(Te);A.rawContent=ke;let Be=X.get(A.id),Ve=null,at=!1;if(Be&&(Ve=Be.getExtractedText(),Ve===null&&(Ve=Ds(ke)),Ve===null)){let H=Be.processChunk(ke);H instanceof Promise?(at=!0,H.then(J=>{var it;let Ae=typeof J=="string"?J:(it=J==null?void 0:J.text)!=null?it:null;Ae!==null&&(A.content=Ae,A.streaming=!1,X.delete(A.id),le.delete(A.id),g(A))}).catch(()=>{})):Ve=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!at){Ve!==null&&Ve.trim()!==""?A.content=Ve:le.has(A.id)||(A.content=be(Te));let H=X.get(A.id);if(H){let J=(bt=H.close)==null?void 0:bt.call(H);J instanceof Promise&&J.catch(()=>{}),X.delete(A.id)}le.delete(A.id),A.streaming=!1,g(A)}},He=(A,te,Te)=>{let Re=E.get(A);if(Re)return Re;let ke={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return E.set(A,ke),g(ke),ke},K=[],qe,ze=new Map,we=0,Ce="agent",tt=!1,Ot=null,ne=null,Oe=new Map,gn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(qe=()=>{var A,te,Te,Re,ke,Be,Ve,at,Pt,bt,H,J,Ae,it,Qe,Ut,fn,vt,wt,It,Ct,ln,_t,Nn,Sn,Tn,bn,En,ar,At,yr,br,Wr,ir,ut,mo,vr,go,Wn,Oo,Kr,Rr,Gr,Qr,fo,ho,Xr,yt,Fn,On,Mn,St,Xn,Jn,_n,Jr,Hr,Yr,$n,Wt,kn,Yn,Zr,Br,eo,he,Rn,wr,mt,nn,rn,xr,hs,Dr,yo,Cr,U,_o,Ar,Sr,Nr,Tr,lr,$o,sa,Un,zn,cr,dr,bo,Fr,vn,Er,Uo,vo,zo,aa,qo,ia,jo,pt,ys,Zn,Hn,la;for(let Vo=0;Vo<K.length;Vo++){let et=K[Vo].payloadType,x=K[Vo].payload;if(!tt&&Ce!=="flow"&&typeof x.stepType=="string"&&(Ce="flow"),et==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&z){k.set(j,z),He(j,z,"reasoning");continue}let Q=(A=ve(x,!0))!=null?A:`reason-${c()}`,ge=Ie(Q);ge.reasoning=(te=ge.reasoning)!=null?te:{id:Q,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Re=ge.reasoning.startedAt)!=null?Re:G((Te=x.startedAt)!=null?Te:x.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(ge.reasoning.scope=x.scope),ge.streaming=!0,ge.reasoning.status="streaming",g(ge)}else if(et==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)&&E.has(j)){let Fe=E.get(j),gt=(Ve=(Be=(ke=x.reasoningText)!=null?ke:x.text)!=null?Be:x.delta)!=null?Ve:"";gt&&x.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let z=(Pt=(at=ve(x,!1))!=null?at:ve(x,!0))!=null?Pt:`reason-${c()}`,Q=Ie(z);Q.reasoning=(bt=Q.reasoning)!=null?bt:{id:z,status:"streaming",chunks:[]},Q.reasoning.startedAt=(J=Q.reasoning.startedAt)!=null?J:G((H=x.startedAt)!=null?H:x.timestamp);let ge=(Qe=(it=(Ae=x.reasoningText)!=null?Ae:x.text)!=null?it:x.delta)!=null?Qe:"";if(ge&&x.hidden!==!0){let Fe=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Fe!==void 0){let gt=Xe(z,Fe,String(ge));Q.reasoning.chunks=[gt]}else Q.reasoning.chunks.push(String(ge))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=G((Ut=x.completedAt)!=null?Ut:x.timestamp);let Fe=(fn=Q.reasoning.startedAt)!=null?fn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-Fe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(et==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)&&E.has(j)){let gt=E.get(j);if(gt.reasoning){let ot=typeof x.text=="string"?x.text:"";ot&>.reasoning.chunks.length===0&>.reasoning.chunks.push(ot),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(j),E.delete(j);continue}let z=(It=(wt=ve(x,!1))!=null?wt:ve(x,!0))!=null?It:`reason-${c()}`,Q=typeof x.text=="string"?x.text:"";!C.get(z)&&(Q||x.scope==="loop")&&Ie(z);let ge=C.get(z);if(ge!=null&&ge.reasoning){(x.scope==="loop"||x.scope==="turn")&&(ge.reasoning.scope=x.scope),Q&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(Q),ge.reasoning.status="complete",ge.reasoning.completedAt=G((Ct=x.completedAt)!=null?Ct:x.timestamp);let gt=(ln=ge.reasoning.startedAt)!=null?ln:Date.now();ge.reasoning.durationMs=Math.max(0,((_t=ge.reasoning.completedAt)!=null?_t:Date.now())-gt),ge.streaming=!1,g(ge)}let Fe=$(x);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(Sn=(Nn=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?Nn:Ne(x,!0))!=null?Sn:`tool-${c()}`,z=(Tn=x.toolName)!=null?Tn:x.name;if($e(z)){ue.add(j);continue}ce(N(x),j);let Q=V(j),ge=(bn=Q.toolCall)!=null?bn:{id:j,status:"pending"};ge.name=z!=null?z:ge.name,ge.status="running",x.parameters!==void 0?ge.args=x.parameters:x.args!==void 0&&(ge.args=x.args),ge.startedAt=(ar=ge.startedAt)!=null?ar:G((En=x.startedAt)!=null?En:x.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,Q.toolCall=ge,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),g(Q)}else if(et==="tool_output_delta"){let j=(yr=(At=Ne(x,!1))!=null?At:Ne(x,!0))!=null?yr:`tool-${c()}`;if(ue.has(j))continue;let z=V(j),Q=(br=z.toolCall)!=null?br:{id:j,status:"running"};Q.startedAt=(ir=Q.startedAt)!=null?ir:G((Wr=x.startedAt)!=null?Wr:x.timestamp);let ge=(vr=(mo=(ut=x.text)!=null?ut:x.delta)!=null?mo:x.message)!=null?vr:"";ge&&(Q.chunks=(go=Q.chunks)!=null?go:[],Q.chunks.push(String(ge))),Q.status="running",z.toolCall=Q,z.streaming=!0;let Fe=x.agentContext;(Fe||x.executionId)&&(z.agentMetadata=(Kr=z.agentMetadata)!=null?Kr:{executionId:(Wn=Fe==null?void 0:Fe.executionId)!=null?Wn:x.executionId,iteration:(Oo=Fe==null?void 0:Fe.iteration)!=null?Oo:x.iteration}),g(z)}else if(et==="tool_complete"){let j=(Gr=(Rr=Ne(x,!1))!=null?Rr:Ne(x,!0))!=null?Gr:`tool-${c()}`;if(ue.has(j)){ue.delete(j);continue}let z=V(j),Q=(Qr=z.toolCall)!=null?Qr:{id:j,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=G((fo=x.completedAt)!=null?fo:x.timestamp);let ge=(ho=x.duration)!=null?ho:x.executionTime;if(typeof ge=="number")Q.durationMs=ge;else{let ot=(Xr=Q.startedAt)!=null?Xr:Date.now();Q.durationMs=Math.max(0,((yt=Q.completedAt)!=null?yt:Date.now())-ot)}z.toolCall=Q,z.streaming=!1;let Fe=x.agentContext;(Fe||x.executionId)&&(z.agentMetadata=(Mn=z.agentMetadata)!=null?Mn:{executionId:(Fn=Fe==null?void 0:Fe.executionId)!=null?Fn:x.executionId,iteration:(On=Fe==null?void 0:Fe.iteration)!=null?On:x.iteration}),g(z);let gt=N(x);gt&&O.byCall.delete(gt)}else if(et==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,z=(St=j!=null?j:x.toolId)!=null?St:`local-${c()}`,Q=V(z),ge=x.toolName,Fe=x.origin==="webmcp"&&!es(ge)?`webmcp:${ge}`:ge,gt=es(Fe),ot=(Xn=Q.toolCall)!=null?Xn:{id:z,status:"pending"};ot.name=Fe,ot.args=x.parameters,ot.status=gt?"running":"complete",ot.chunks=(Jn=ot.chunks)!=null?Jn:[],ot.startedAt=(Hr=ot.startedAt)!=null?Hr:G((Jr=(_n=x.startedAt)!=null?_n:x.timestamp)!=null?Jr:x.awaitedAt),gt?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(Yr=ot.completedAt)!=null?Yr:ot.startedAt,Q.toolCall=ot,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=x.executionId)!=null?Wt:($n=Q.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(Q)}else if(et==="text_start"){let j=typeof x.id=="string"?x.id:null,z=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&z){k.set(j,z);continue}let Q=f;Q&&(Ce==="flow"?(Ye(Q),xt=Q):(Q.streaming=!1,g(Q)),f=null),W=typeof x.id=="string"?x.id:W,T=""}else if(et==="text_delta"){let j=typeof x.id=="string"?x.id:null,z=j?k.get(j):void 0;if(j&&z){let ge=typeof x.delta=="string"?x.delta:"",Fe=((kn=P.get(j))!=null?kn:"")+ge;if(P.set(j,Fe),Fe.trim()==="")continue;let gt=He(j,z);gt.agentMetadata={...gt.agentMetadata,executionId:x.executionId,parentToolId:z},dt(gt,Fe,ge,void 0);continue}if(W=typeof x.id=="string"?x.id:W,Ce==="flow"){let ge=typeof x.delta=="string"?x.delta:"";if(T+=ge,T.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:x.executionId,iteration:x.iteration},dt(Fe,T,ge,void 0),w=Fe;continue}let Q=pe();Q.content+=(Yn=x.delta)!=null?Yn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:Ot!=null?Ot:void 0,agentName:ne==null?void 0:ne.agentName},w=Q,g(Q)}else if(et==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&k.has(j)){let Q=E.get(j);Q&&Ye(Q),k.delete(j),P.delete(j),E.delete(j);continue}let z=f;z&&(Ce==="flow"?(Ye(z),xt=z):(((Zr=z.content)!=null?Zr:"")===""&&typeof x.text=="string"&&(z.content=x.text),z.streaming=!1,g(z)),f=null),W=null,T=""}else if(et==="step_complete"){let j=x.stepType,z=x.executionType;if(j==="tool"||z==="context")continue;if(x.success===!1){let Q=x.error,ge=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Br=Q.message)!=null?Br:"Step failed"):"Step failed";n({type:"error",error:new Error(ge)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let Q=xt;xt=null;let ge=x.stopReason,Fe=(eo=x.result)==null?void 0:eo.response;if(Q)ge&&(Q.stopReason=ge),Fe!=null?Ze(Q,Fe):Q.streaming!==!1&&(X.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let gt=Fe!=null&&Fe!=="";if(gt||ge){let ot=pe();ge&&(ot.stopReason=ge),gt?Ye(ot,Fe):(ot.streaming=!1,g(ot))}}continue}}else if(et==="execution_start")Ce=x.kind==="flow"?"flow":"agent",tt=!0,Ce==="agent"&&(ne={executionId:x.executionId,agentId:(he=x.agentId)!=null?he:"virtual",agentName:(Rn=x.agentName)!=null?Rn:"",status:"running",currentIteration:0,maxTurns:(wr=x.maxTurns)!=null?wr:1,startedAt:G(x.startedAt)});else if(et==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(ne&&(ne.currentIteration=j),gn==="separate"&&j>1){let z=f;z&&(z.streaming=!1,g(z),Oe.set(j-1,z),f=null)}we=j}Ot=typeof x.id=="string"?x.id:null,w=null}else if(et==="tool_input_delta"){let j=(mt=x.toolCallId)!=null?mt:O.lastId;if(j){let z=L.get(j);z!=null&&z.toolCall&&(z.toolCall.chunks=(nn=z.toolCall.chunks)!=null?nn:[],z.toolCall.chunks.push((rn=x.delta)!=null?rn:""),g(z))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let j=x.stopReason,z=f!=null?f:w;if(j&&z!==null){let Q=x.id;(!Q||((xr=z.agentMetadata)==null?void 0:xr.turnId)===Q)&&(z.stopReason=j,g(z))}Ot===x.id&&(Ot=null)}else if(et==="media_start"){let j=String(x.id);ze.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(et==="media_delta"){let j=ze.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(et==="media_complete"){let j=String(x.id),z=ze.get(j);ze.delete(j);let Q=(Dr=(hs=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?hs:z==null?void 0:z.mediaType)!=null?Dr:"application/octet-stream",ge=typeof x.data=="string"?x.data:void 0,Fe=typeof x.url=="string"?x.url:z&&z.parts.length>0?z.parts.join(""):void 0,gt=null;if(ge)gt={type:"media",data:ge,mediaType:Q};else if(Fe){let cn=Q.toLowerCase();gt={type:cn==="image"||cn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:Q}}let ot=(yo=x.toolCallId)!=null?yo:z==null?void 0:z.toolCallId,bs=gt?[gt]:[],Bn=[];for(let cn of bs){if(!cn||typeof cn!="object")continue;let dn=cn,wo=typeof dn.type=="string"?dn.type:void 0,Or=typeof dn.mediaType=="string"?dn.mediaType.toLowerCase():"",Ln=null,hn="";if(wo==="media"){let qn=typeof dn.data=="string"?dn.data:void 0;if(!qn)continue;hn=Or.length>0?Or:"application/octet-stream",Ln=`data:${hn};base64,${qn}`}else if(wo==="image-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else if(wo==="file-url"){let qn=typeof dn.url=="string"?dn.url:void 0;if(!qn)continue;hn=Or,Ln=qn}else continue;if(Ln)if(wo==="image-url"||hn.startsWith("image/"))Bn.push({type:"image",image:Ln,...hn.includes("/")?{mimeType:hn}:{}});else if(hn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:hn});else if(hn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:hn});else{let qn=hn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Ef(qn)})}}if(Bn.length>0){let cn=c(),dn=ot,Or={id:`agent-media-${typeof dn=="string"&&dn.length>0?`${dn}-${cn}`:String(cn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:cn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};g(Or);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,v.current=null}}else if(et==="execution_complete"){let j=(Cr=x.kind)!=null?Cr:Ce;j==="agent"&&ne&&(ne.status=x.success?"complete":"error",ne.completedAt=G(x.completedAt),ne.stopReason=x.stopReason);let z=f;z&&(j==="flow"&&z.streaming!==!1?Ye(z):(z.streaming=!1,g(z)),f=null),W=null,T="",xt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let j=typeof x.error=="string"?x.error:(_o=(U=x.error)==null?void 0:U.message)!=null?_o:"Execution error";n({type:"error",error:new Error(j)})}else if(et!=="ping"){if(et==="approval_start"){let j=(Ar=x.approvalId)!=null?Ar:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(Sr=ne==null?void 0:ne.agentId)!=null?Sr:"virtual",executionId:(Tr=(Nr=x.executionId)!=null?Nr:ne==null?void 0:ne.executionId)!=null?Tr:"",toolName:(lr=x.toolName)!=null?lr:"",toolType:x.toolType,description:(sa=x.description)!=null?sa:`Execute ${($o=x.toolName)!=null?$o:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(z)}else if(et==="step_await"&&x.awaitReason==="approval_required"){let j=(Un=x.approvalId)!=null?Un:`approval-${c()}`,z={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(zn=ne==null?void 0:ne.agentId)!=null?zn:"virtual",executionId:(dr=(cr=x.executionId)!=null?cr:ne==null?void 0:ne.executionId)!=null?dr:"",toolName:(bo=x.toolName)!=null?bo:"",toolType:x.toolType,description:(vn=x.description)!=null?vn:`Execute ${(Fr=x.toolName)!=null?Fr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(z)}else if(et==="approval_complete"){let j=x.approvalId;if(j){let Q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(Er=x.decision)!=null?Er:"approved",agentId:(Uo=ne==null?void 0:ne.agentId)!=null?Uo:"virtual",executionId:(zo=(vo=x.executionId)!=null?vo:ne==null?void 0:ne.executionId)!=null?zo:"",toolName:(aa=x.toolName)!=null?aa:"",description:(qo=x.description)!=null?qo:"",resolvedAt:Date.now()}};g(Q)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let j=x.artifactType,z=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(n({type:"artifact_start",id:z,artifactType:j,title:Q,component:typeof x.component=="string"?x.component:void 0}),de.set(z,{markdown:"",title:Q}),!se.has(z)){se.add(z);let ge={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:Q,artifactType:j,status:"streaming"}})};oe.set(z,ge),g(ge)}}else if(et==="artifact_delta"){let j=String(x.id),z=typeof x.delta=="string"?x.delta:String((ia=x.delta)!=null?ia:"");n({type:"artifact_delta",id:j,artDelta:z});let Q=de.get(j);Q&&(Q.markdown+=z)}else if(et==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(et==="artifact_complete"){let j=String(x.id);n({type:"artifact_complete",id:j});let z=oe.get(j);if(z){z.streaming=!1;try{let Q=JSON.parse((jo=z.rawContent)!=null?jo:"{}");if(Q.props){Q.props.status="complete";let ge=de.get(j);ge!=null&&ge.markdown&&(Q.props.markdown=ge.markdown)}z.rawContent=JSON.stringify(Q)}catch{}de.delete(j),g(z),oe.delete(j)}}}else if(et==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let z=String((pt=j.id)!=null?pt:`msg-${c()}`),Q=j.role,Fe={id:z,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),ot=(ys=gt==null?void 0:gt.props)==null?void 0:ys.artifactId;typeof ot=="string"&&se.add(ot)}catch{}f=null,v.current=null,X.delete(z),le.delete(z)}else if(et==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Zn=x.error)==null?void 0:Zn.message)!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(j)});let z=f;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(et==="dispatch_error"){let z=(Hn=x.message)!=null?Hn:x.error;z!=null&&z!==""&&(j=new Error(String(z)))}else{let z=x.error;typeof z=="string"&&z!==""?j=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&(j=new Error(String((la=z.message)!=null?la:z)))}if(j){n({type:"error",error:j});let z=f;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}K.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
|
|
12
12
|
|
|
13
13
|
`);a=(Xt=Te.pop())!=null?Xt:"";for(let Re of Te){let ke=Re.split(`
|
|
14
14
|
`),Be="message",Ve="";for(let bt of ke)bt.startsWith("event:")?Be=bt.replace("event:","").trim():bt.startsWith("data:")&&(Ve+=bt.replace("data:","").trim());if(!Ve)continue;let at;try{at=JSON.parse(Ve)}catch(bt){n({type:"error",error:bt instanceof Error?bt:new Error("Failed to parse chat stream payload")});continue}let Pt=Be!=="message"?Be:(Ir=at.type)!=null?Ir:"message";if((hr=this.onSSEEvent)==null||hr.call(this,Pt,at),this.parseSSEEvent){v.current=f;let bt=await this.handleCustomSSEEvent(at,n,v,g,c,M);if(v.current&&v.current!==f&&(f=v.current),bt)continue}K.push({payloadType:Pt,payload:at}),qe()}}qe()}};function Ta(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Os(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Ea="[Image]";function ki(t){return{type:"text",text:t}}var bu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Lf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],qr=[...bu,...Lf];function Pf(t){return bu.includes(t)||t.startsWith("image/")}function Ma(t){return Pf(t.type)}async function vu(t){return new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ma(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)})}function wu(t,e=qr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function If(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function xu(t,e){let n=If(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}Li();var Cu=16e3,Wf=24e3,Rf=4096,Hf=1380533830;function Bf(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Hf?new Uint8Array(t,44):new Uint8Array(t)}function Df(t){var r;let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var _s=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Cu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,m=new u({sampleRate:Cu});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ss(Wf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Df(r)}/ws/agents/${encodeURIComponent(e)}/voice`,w=new WebSocket(f,["runtype.bearer",n]);w.binaryType="arraybuffer",this.ws=w,w.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,w,o))},w.onmessage=v=>this.handleMessage(v,o),w.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},w.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let M=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,r,o){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Rf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let m=Math.max(-1,Math.min(1,d[u]));c[u]=m<0?m*32768:m*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){var o,s;if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let r=Bf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,r){this.transcriptCallbacks.forEach(o=>o(e,n,r))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function as(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new _s(t.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function Au(t){if((t==null?void 0:t.type)==="custom"&&t.custom)return as({type:"custom",custom:t.custom});if((t==null?void 0:t.type)==="runtype"&&t.runtype)return as({type:"runtype",runtype:t.runtype});if(Io.isSupported())return as({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Pi(t){try{return Au(t),!0}catch{return!1}}function ka(t){var n;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=t.find(s=>s.name===r);if(o)return o}return(n=t.find(r=>r.lang.startsWith("en")))!=null?n:t[0]}var is=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,n){var a;if(!t.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ka(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(u=n.onError)==null||u.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var $s=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,n;return(n=(e=this.engine)==null?void 0:e.supportsPause)!=null?n:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,n;this.stop(),(n=(e=this.engine)==null?void 0:e.destroy)==null||n.call(e),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Ii(t){if(!t)return"";let e=Nf(t);return Su(e!==null?e:t)}function Nf(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Su(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
@@ -16,7 +16,7 @@ ${t.description}`:"");return window.confirm(n)},Dg=t=>{if(t==null)return"";try{l
|
|
|
16
16
|
`),e.trim()}var Lu=null;var Wi=()=>Lu?Lu():Promise.resolve().then(()=>(ku(),Mu));var _f=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function $f(t,e){return _f.some(n=>t[n]!==e[n])}function Pu(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let r="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?`${r}
|
|
17
17
|
|
|
18
18
|
_Details: ${n.message}_`:r}var Us=t=>({isError:!0,content:[{type:"text",text:t}]}),Iu=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Wu=t=>es(t)||t===zr,Ia=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 $s(()=>this.createSpeechEngine());this.handleEvent=e=>{var n,r,o,s,a,i,d,c,u,m;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,f=!!(g!=null&&g.name)&&(es(g.name)||g.name===zr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(u=this.callbacks).onError)==null||m.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Fs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let n=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||Wi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Pi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,n,r;return(r=(n=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:n.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let n=is.isSupported()?new is({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,m=this.config.clientToken,g=e.browserFallback!==!1;if(c&&u&&m)return Wi().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:w})=>{let v=new f({host:c,agentId:u,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return g&&n?new w(v,n,{onFallback:M=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${M.message}`)}):v});if(g&&n)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){var n,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=as(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,u,m,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(m=e.runtype)==null?void 0:m.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=e.browser)==null?void 0:g.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(e=this.callbacks).onError)==null||n.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!$f(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new Fs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:m}=e,f={id:a!=null?a:n==="user"?Ta():n==="assistant"?Os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:m=!1,voiceProcessing:g,rawContent:f}=r,v={id:d!=null?d:o==="user"?Ta():o==="assistant"?Os():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,n){var c,u,m,g,f;let r=e.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ta(),s=Os(),a={id:o,role:"user",content:r||Ea,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(w){let v=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!v){let M=Pu(w,this.config.errorMessage);if(M){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(W)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(w instanceof Error?(m=(u=this.callbacks).onError)==null||m.call(u,w):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(w))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Os();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let m=Pu(c,this.config.errorMessage);if(m){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,n){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(e,n,r){var u,m,g,f,w;let o=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(m=this.abortController)==null||m.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,r):v=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let W=await v.json().catch(()=>null);throw new Error((g=W==null?void 0:W.error)!=null?g:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(w=(f=this.callbacks).onError)==null||w.call(f,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){var u,m,g,f,w,v,M,W,T,k,E,P;let r=this.messages.find(C=>C.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(w=(f=this.callbacks).onError)==null||w.call(f,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=(v=e.toolCall)==null?void 0:v.args,L=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(L.length===1){let F=typeof((M=L[0])==null?void 0:M.question)=="string"?L[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(e,a),(W=this.abortController)==null||W.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([L,F])=>`${L}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((L,F)=>{let O=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!O)return;let R=C[O],$=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:O,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let L=await C.json().catch(()=>null);throw new Error((k=L==null?void 0:L.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let L=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(P=(E=this.callbacks).onError)==null||P.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let n=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let n=this.messages.find(a=>a.id===e.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let n=this.messages.find(s=>s.id===e.id);return((o=(n!=null?n:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){var d,c,u,m;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,L,F,O,R,$;let f=(P=g.toolCall)==null?void 0:P.name,w=(C=g.toolCall)==null?void 0:C.id;if(!f||!w)return null;let v=`${e}:${w}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let M=this.markWebMcpToolRunning(g),W=(F=(L=g.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?F:f;if(f===zr)return{dedupeKey:v,resumeKey:W,output:Ai(),toolMessage:g,startedAt:M,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let k=this.client.executeWebMcpToolCall(f,(O=g.toolCall)==null?void 0:O.args,T.signal),E;if(!k)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await k}catch(N){let Z=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Z||($=(R=this.callbacks).onError)==null||$.call(R,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,Us(Z?"Aborted by cancel()":Iu(N)),M),this.webMcpInflightKeys.delete(v),null}return T.signal.aborted?(this.markWebMcpToolComplete(g,Us("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:W,output:E,toolMessage:g,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(w=>w!==null),i.length===0)return;let g={};for(let w of i)g[w.resumeKey]=w.output;let f=await this.client.resumeFlow(e,g,{signal:s.signal});if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((d=w==null?void 0:w.error)!=null?d:`Resume failed: ${f.status}`)}for(let w of i)this.webMcpResolvedKeys.add(w.dedupeKey),this.markWebMcpToolComplete(w.toolMessage,w.output,w.startedAt,w.completedAt,((c=w.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(m=(u=this.callbacks).onError)==null||m.call(u,g instanceof Error?g:new Error(String(g)));else for(let w of i)this.markWebMcpToolComplete(w.toolMessage,Us("Aborted by cancel()"),w.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var w,v,M,W,T,k,E,P,C,L,F,O;let n=(w=e.agentMetadata)==null?void 0:w.executionId,r=(v=e.toolCall)==null?void 0:v.name,o=(M=e.toolCall)==null?void 0:M.id;if(!n){(T=(W=this.callbacks).onError)==null||T.call(W,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch($){(E=(k=this.callbacks).onError)==null||E.call(k,$ instanceof Error?$:new Error(String($)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(P=e.toolCall)==null?void 0:P.args,m=c?null:this.client.executeWebMcpToolCall(r,u,d),g="execute",f=a;try{let R;if(c?R=Ai():m?R=await m:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Us("Aborted by cancel()"),a);return}let $=(L=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?L:r;g="resume",await this.resumeWithToolOutput(n,$,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,R,a,f,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let $=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(g==="execute"||$||d.aborted)&&this.markWebMcpToolComplete(e,Us($||d.aborted?"Aborted by cancel()":Iu(R)),a),$||(O=(F=this.callbacks).onError)==null||O.call(F,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,r,o){var a,i;let s=await this.client.resumeFlow(e,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,n;(n=(e=this.callbacks).onArtifactsState)==null||n.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var n,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(n=e.component)!=null?n:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Ii(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ka(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let r=Ii(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var u,m,g,f,w,v,M,W,T,k,E,P,C,L,F;if(s!==r)return o;let a={...o,...n};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=o.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let O=o.approval,R=n.approval;a.approval={...O,...R,executionId:R.executionId||O.executionId,toolName:R.toolName||O.toolName,description:R.description||O.description,toolType:(f=R.toolType)!=null?f:O.toolType,reason:(w=R.reason)!=null?w:O.reason,parameters:(v=R.parameters)!=null?v:O.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(W=n.agentMetadata)==null?void 0:W.executionId,c=(T=n.toolCall)==null?void 0:T.id;if(i&&Wu(i)&&d&&c&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let O=`${d}:${c}`,R=this.webMcpInflightKeys.has(O),$=this.webMcpResolvedKeys.has(O),N=(E=o.toolCall)==null?void 0:E.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&N!==void 0&&Wu(N)&&((L=o.toolCall)==null?void 0:L.status)==="complete";(R||$||Z)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Uf,ArrowDown as zf,ArrowUp as qf,ArrowUpRight as jf,Bot as Vf,ChevronDown as Kf,ChevronUp as Gf,ChevronRight as Qf,ChevronLeft as Xf,Check as Jf,Clipboard as Yf,ClipboardCopy as Zf,Copy as eh,File as th,FileCode as nh,FileSpreadsheet as rh,FileText as oh,ImagePlus as sh,Loader as ah,LoaderCircle as ih,Mic as lh,Paperclip as ch,RefreshCw as dh,Search as ph,Send as uh,ShieldAlert as mh,ShieldCheck as gh,ShieldX as fh,Square as hh,ThumbsDown as yh,ThumbsUp as bh,Upload as vh,Volume2 as wh,X as xh,User as Ch,Mail as Ah,Phone as Sh,Calendar as Th,Clock as Eh,Building as Mh,MapPin as kh,Lock as Lh,Key as Ph,CreditCard as Ih,AtSign as Wh,Hash as Rh,Globe as Hh,Link as Bh,CircleCheck as Dh,CircleX as Nh,TriangleAlert as Fh,Info as Oh,Ban as _h,Shield as $h,ArrowLeft as Uh,ArrowRight as zh,ExternalLink as qh,Ellipsis as jh,EllipsisVertical as Vh,Menu as Kh,House as Gh,Plus as Qh,Minus as Xh,Pencil as Jh,Trash as Yh,Trash2 as Zh,Save as ey,Download as ty,Share as ny,Funnel as ry,Settings as oy,RotateCw as sy,Maximize as ay,Minimize as iy,ShoppingCart as ly,ShoppingBag as cy,Package as dy,Truck as py,Tag as uy,Gift as my,Receipt as gy,Wallet as fy,Store as hy,DollarSign as yy,Percent as by,Play as vy,Pause as wy,VolumeX as xy,Camera as Cy,Image as Ay,Film as Sy,Headphones as Ty,MessageCircle as Ey,MessageSquare as My,Bell as ky,Heart as Ly,Star as Py,Eye as Iy,EyeOff as Wy,Bookmark as Ry,CalendarDays as Hy,History as By,Timer as Dy,Folder as Ny,FolderOpen as Fy,Files as Oy,Sparkles as _y,Zap as $y,Sun as Uy,Moon as zy,Flag as qy,Monitor as jy,Smartphone as Vy}from"lucide";var Ky={activity:Uf,"arrow-down":zf,"arrow-up":qf,"arrow-up-right":jf,bot:Vf,"chevron-down":Kf,"chevron-up":Gf,"chevron-right":Qf,"chevron-left":Xf,check:Jf,clipboard:Yf,"clipboard-copy":Zf,copy:eh,file:th,"file-code":nh,"file-spreadsheet":rh,"file-text":oh,"image-plus":sh,loader:ah,"loader-circle":ih,mic:lh,paperclip:ch,"refresh-cw":dh,search:ph,send:uh,"shield-alert":mh,"shield-check":gh,"shield-x":fh,square:hh,"thumbs-down":yh,"thumbs-up":bh,upload:vh,"volume-2":wh,x:xh,user:Ch,mail:Ah,phone:Sh,calendar:Th,clock:Eh,building:Mh,"map-pin":kh,lock:Lh,key:Ph,"credit-card":Ih,"at-sign":Wh,hash:Rh,globe:Hh,link:Bh,"circle-check":Dh,"circle-x":Nh,"triangle-alert":Fh,info:Oh,ban:_h,shield:$h,"arrow-left":Uh,"arrow-right":zh,"external-link":qh,ellipsis:jh,"ellipsis-vertical":Vh,menu:Kh,house:Gh,plus:Qh,minus:Xh,pencil:Jh,trash:Yh,"trash-2":Zh,save:ey,download:ty,share:ny,funnel:ry,settings:oy,"rotate-cw":sy,maximize:ay,minimize:iy,"shopping-cart":ly,"shopping-bag":cy,package:dy,truck:py,tag:uy,gift:my,receipt:gy,wallet:fy,store:hy,"dollar-sign":yy,percent:by,play:vy,pause:wy,"volume-x":xy,camera:Cy,image:Ay,film:Sy,headphones:Ty,"message-circle":Ey,"message-square":My,bell:ky,heart:Ly,star:Py,eye:Iy,"eye-off":Wy,bookmark:Ry,"calendar-days":Hy,history:By,timer:Dy,folder:Ny,"folder-open":Fy,files:Oy,sparkles:_y,zap:$y,sun:Uy,moon:zy,flag:qy,monitor:jy,smartphone:Vy},fe=(t,e=24,n="currentColor",r=2)=>{let o=Ky[t];return o?Gy(o,e,n,r):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Gy(t,e,n,r){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Wa={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function Qy(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Xy(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var zs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=e.allowedTypes)!=null?n:Wa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Wa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Wa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Wa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var n,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let u=wu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let m=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,m);continue}try{let m=await vu(c),g=Ma(c)?URL.createObjectURL(c):null,f={id:Qy(),file:c,previewUrl:g,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let n=this.attachments.findIndex(d=>d.id===e);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(e=this.config).onAttachmentsChange)==null||n.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ma(e.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",n&&e.previewUrl){let a=y("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=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 i=Xy(e.file.type),d=fe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=xu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:n})}};var Ru=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function qs(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];Ru(s)&&Ru(o)?n[r]=qs(s,o):n[r]=o}return n}var jr="min(440px, calc(100vw - 24px))",Bu="440px",Jy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:jr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Ht={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Jy,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:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Hu(t,e){if(!(!t&&!e))return t?e?qs(t,e):t:e}function Du(t){var e,n,r,o,s,a,i,d,c,u,m,g,f,w,v,M,W,T,k,E,P;return t?{...Ht,...t,theme:Hu(Ht.theme,t.theme),darkTheme:Hu(Ht.darkTheme,t.darkTheme),launcher:{...Ht.launcher,...t.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(n=t.launcher)==null?void 0:n.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...t.copy},sendButton:{...Ht.sendButton,...t.sendButton},statusIndicator:{...Ht.statusIndicator,...t.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...t.voiceRecognition},features:(()=>{var oe,se,de,$e,Ne,V,G,be,X,le;let C=(oe=Ht.features)==null?void 0:oe.artifacts,L=(se=t.features)==null?void 0:se.artifacts,F=(de=Ht.features)==null?void 0:de.scrollToBottom,O=($e=t.features)==null?void 0:$e.scrollToBottom,R=(Ne=Ht.features)==null?void 0:Ne.scrollBehavior,$=(V=t.features)==null?void 0:V.scrollBehavior,N=(G=Ht.features)==null?void 0:G.streamAnimation,Z=(be=t.features)==null?void 0:be.streamAnimation,Se=(X=Ht.features)==null?void 0:X.askUserQuestion,pe=(le=t.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&L===void 0?void 0:{...C,...L,layout:{...C==null?void 0:C.layout,...L==null?void 0:L.layout}},ve=F===void 0&&O===void 0?void 0:{...F,...O},Ie=R===void 0&&$===void 0?void 0:{...R,...$},ce=N===void 0&&Z===void 0?void 0:{...N,...Z},ue=Se===void 0&&pe===void 0?void 0:{...Se,...pe,styles:{...Se==null?void 0:Se.styles,...pe==null?void 0:pe.styles}};return{...Ht.features,...t.features,...ve!==void 0?{scrollToBottom:ve}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ce!==void 0?{streamAnimation:ce}:{},...ue!==void 0?{askUserQuestion:ue}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Ht.layout,...t.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=t.layout)==null?void 0:c.messages,avatar:{...(m=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:m.avatar,...(f=(g=t.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(v=(w=Ht.layout)==null?void 0:w.messages)==null?void 0:v.timestamp,...(W=(M=t.layout)==null?void 0:M.messages)==null?void 0:W.timestamp}},slots:{...(T=Ht.layout)==null?void 0:T.slots,...(k=t.layout)==null?void 0:k.slots}},markdown:{...Ht.markdown,...t.markdown,options:{...(E=Ht.markdown)==null?void 0:E.options,...(P=t.markdown)==null?void 0:P.options}},messageActions:{...Ht.messageActions,...t.messageActions}}:Ht}var Yy={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"}},Zy={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},eb={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:jr,maxWidth:Bu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function ls(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),r=t;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ls(t,r):r}function Nu(t){let e={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ls(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function tb(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Fu(t,e){let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Fu(s,o):n[r]=o}return n}function nb(t,e){return e?Fu(t,e):t}function Wo(t,e={}){var o,s,a,i,d,c,u,m,g,f,w,v,M;let n={palette:Yy,semantic:Zy,components:eb},r={palette:{...n.palette,...t==null?void 0:t.palette,colors:{...n.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=t==null?void 0:t.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...t==null?void 0:t.semantic,colors:{...n.semantic.colors,...(u=t==null?void 0:t.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(v=t==null?void 0:t.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=t==null?void 0:t.semantic)==null?void 0:M.typography}},components:nb(n.components,t==null?void 0:t.components)};if(e.validate!==!1){let W=tb(r);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let W of e.plugins)r=W.transform(r);return r}function Ou(t){var v,M,W,T,k,E,P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe,se,de,$e,Ne,V,G,be,X,le,Ee,Xe,Ze,xt,dt,Ye,He,K,qe,ze,we,Ce,tt,Ot,ne,Oe,gn,Bt,Xt,Ir,hr,A,te,Te,Re,ke,Be,Ve,at,Pt,bt,H,J,Ae,it,Qe,Ut,fn,vt,wt,It,Ct,ln,_t,Nn,Sn,Tn,bn,En,ar,At,yr,br,Wr,ir,ut,mo,vr,go,Wn,Oo,Kr,Rr,Gr,Qr,fo,ho,Xr,yt,Fn,On,Mn,St,Xn,Jn,_n,Jr,Hr,Yr,$n,Wt,kn,Yn,Zr,Br,eo;let e=Nu(t),n={};for(let[he,Rn]of Object.entries(e)){let wr=he.replace(/\./g,"-");n[`--persona-${wr}`]=Rn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(W=n["--persona-semantic-colors-accent"])!=null?W:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(T=n["--persona-semantic-colors-surface"])!=null?T:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(L=n["--persona-semantic-colors-text-inverse"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(O=n["--persona-semantic-colors-divider"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=($=n["--persona-components-voice-recording-background"])!=null?$:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Se=n["--persona-components-approval-requested-background"])!=null?Se:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(ve=n["--persona-components-approval-requested-shadow"])!=null?ve:"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"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ce=n["--persona-components-approval-deny-background"])!=null?ce:n["--persona-container"],n["--persona-attachment-image-bg"]=(ue=n["--persona-components-attachment-image-background"])!=null?ue:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(de=n["--persona-semantic-typography-fontSize"])!=null?de:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=($e=n["--persona-semantic-typography-fontWeight"])!=null?$e:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Ne=n["--persona-semantic-typography-lineHeight"])!=null?Ne: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(G=n["--persona-palette-radius-md"])!=null?G:"0.375rem",n["--persona-radius-lg"]=(be=n["--persona-palette-radius-lg"])!=null?be:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(Xe=(Ee=n["--persona-components-launcher-borderRadius"])!=null?Ee:n["--persona-palette-radius-full"])!=null?Xe:"9999px",n["--persona-launcher-bg"]=(Ze=n["--persona-components-launcher-background"])!=null?Ze:n["--persona-primary"],n["--persona-launcher-fg"]=(xt=n["--persona-components-launcher-foreground"])!=null?xt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(dt=n["--persona-components-launcher-border"])!=null?dt:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(qe=(K=n["--persona-components-button-primary-borderRadius"])!=null?K:n["--persona-palette-radius-full"])!=null?qe:"9999px",n["--persona-panel-radius"]=(we=(ze=n["--persona-components-panel-borderRadius"])!=null?ze:n["--persona-radius-xl"])!=null?we:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ot=(tt=n["--persona-components-panel-shadow"])!=null?tt:n["--persona-palette-shadows-xl"])!=null?Ot:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ne=n["--persona-components-launcher-shadow"])!=null?ne:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(gn=(Oe=n["--persona-components-input-borderRadius"])!=null?Oe:n["--persona-radius-lg"])!=null?gn:"0.5rem",n["--persona-message-user-radius"]=(Xt=(Bt=n["--persona-components-message-user-borderRadius"])!=null?Bt:n["--persona-radius-lg"])!=null?Xt:"0.5rem",n["--persona-message-assistant-radius"]=(hr=(Ir=n["--persona-components-message-assistant-borderRadius"])!=null?Ir:n["--persona-radius-lg"])!=null?hr:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Te=n["--persona-components-header-iconBackground"])!=null?Te:n["--persona-primary"],n["--persona-header-icon-fg"]=(Re=n["--persona-components-header-iconForeground"])!=null?Re:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ve=n["--persona-components-header-actionIconForeground"])!=null?Ve:n["--persona-muted"];let r=(at=t.components)==null?void 0:at.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Pt=t.components)==null?void 0:Pt.introCard;n["--persona-intro-card-bg"]=(bt=n["--persona-components-introCard-background"])!=null?bt:n["--persona-surface"],n["--persona-intro-card-radius"]=(H=n["--persona-components-introCard-borderRadius"])!=null?H:"1rem",n["--persona-intro-card-padding"]=(J=n["--persona-components-introCard-padding"])!=null?J:"1.5rem",n["--persona-intro-card-shadow"]=(it=(Ae=o==null?void 0:o.shadow)!=null?Ae:n["--persona-components-introCard-shadow"])!=null?it:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Qe=n["--persona-components-input-background"])!=null?Qe:n["--persona-surface"],n["--persona-input-placeholder"]=(Ut=n["--persona-components-input-placeholder"])!=null?Ut:n["--persona-text-muted"],n["--persona-message-user-bg"]=(fn=n["--persona-components-message-user-background"])!=null?fn:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(wt=n["--persona-components-message-user-shadow"])!=null?wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(It=n["--persona-components-message-assistant-background"])!=null?It:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ct=n["--persona-components-message-assistant-text"])!=null?Ct:n["--persona-text"],n["--persona-message-assistant-border"]=(ln=n["--persona-components-message-assistant-border"])!=null?ln:n["--persona-border"],n["--persona-message-assistant-shadow"]=(_t=n["--persona-components-message-assistant-shadow"])!=null?_t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Sn=(Nn=n["--persona-components-scrollToBottom-background"])!=null?Nn:n["--persona-button-primary-bg"])!=null?Sn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(bn=(Tn=n["--persona-components-scrollToBottom-foreground"])!=null?Tn:n["--persona-button-primary-fg"])!=null?bn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(En=n["--persona-components-scrollToBottom-border"])!=null?En:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(br=(yr=(At=n["--persona-components-scrollToBottom-borderRadius"])!=null?At:n["--persona-button-radius"])!=null?yr:n["--persona-radius-full"])!=null?br:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Wr=n["--persona-components-scrollToBottom-shadow"])!=null?Wr:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(mo=n["--persona-components-scrollToBottom-gap"])!=null?mo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(go=(vr=n["--persona-components-scrollToBottom-fontSize"])!=null?vr:n["--persona-palette-typography-fontSize-sm"])!=null?go:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Wn=n["--persona-components-scrollToBottom-iconSize"])!=null?Wn:"14px",n["--persona-tool-bubble-shadow"]=(Oo=n["--persona-components-toolBubble-shadow"])!=null?Oo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Kr=n["--persona-components-reasoningBubble-shadow"])!=null?Kr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Rr=n["--persona-components-composer-shadow"])!=null?Rr:"none",n["--persona-md-inline-code-bg"]=(Gr=n["--persona-components-markdown-inlineCode-background"])!=null?Gr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Qr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Qr:n["--persona-text"],n["--persona-md-link-color"]=(ho=(fo=n["--persona-components-markdown-link-foreground"])!=null?fo:n["--persona-accent"])!=null?ho:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Xr=n["--persona-components-markdown-codeBlock-background"])!=null?Xr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(yt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?yt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Fn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Fn:"inherit",n["--persona-md-table-header-bg"]=(On=n["--persona-components-markdown-table-headerBackground"])!=null?On:n["--persona-container"],n["--persona-md-table-border-color"]=(Mn=n["--persona-components-markdown-table-borderColor"])!=null?Mn:n["--persona-border"],n["--persona-md-hr-color"]=(St=n["--persona-components-markdown-hr-color"])!=null?St:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Xn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Jn=n["--persona-components-markdown-blockquote-background"])!=null?Jn:"transparent",n["--persona-md-blockquote-text-color"]=(_n=n["--persona-components-markdown-blockquote-textColor"])!=null?_n:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Jr=n["--persona-components-collapsibleWidget-container"])!=null?Jr:n["--persona-surface"],n["--cw-surface"]=(Hr=n["--persona-components-collapsibleWidget-surface"])!=null?Hr:n["--persona-surface"],n["--cw-border"]=(Yr=n["--persona-components-collapsibleWidget-border"])!=null?Yr:n["--persona-border"],n["--persona-message-border"]=($n=n["--persona-components-message-border"])!=null?$n:n["--persona-border"];let u=t.components,m=u==null?void 0:u.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=u==null?void 0:u.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=u==null?void 0:u.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let he=w.toolbar;he.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,n["--persona-dropdown-bg"]=(Wt=n["--persona-dropdown-bg"])!=null?Wt:he.copyMenuBackground),he.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,n["--persona-dropdown-border"]=(kn=n["--persona-dropdown-border"])!=null?kn:he.copyMenuBorder),he.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,n["--persona-dropdown-shadow"]=(Yn=n["--persona-dropdown-shadow"])!=null?Yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Zr=n["--persona-dropdown-radius"])!=null?Zr:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Br=n["--persona-dropdown-item-hover-bg"])!=null?Br:he.copyMenuItemHoverBackground),he.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(w!=null&&w.tab){let he=w.tab;he.background&&(n["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(n["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(n["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(n["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(n["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(n["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(n["--persona-artifact-tab-list-padding"]=he.listPadding)}if(w!=null&&w.pane){let he=w.pane;if(he.toolbarBackground){let Rn=(eo=ls(t,he.toolbarBackground))!=null?eo:he.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Rn}}return n}var rb={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"}}},_u=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ri=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},ob=t=>{var n;let e=(n=t==null?void 0:t.colorScheme)!=null?n:"light";return e==="light"?"light":e==="dark"?"dark":Ri()},sb=t=>ob(t),ab=t=>Wo(t),ib=t=>{var n;let e=Wo(void 0,{validate:!1});return Wo({...t,palette:{...e.palette,colors:{...rb.colors,...(n=t==null?void 0:t.palette)==null?void 0:n.colors}}},{validate:!1})},Ra=t=>{let e=sb(t),n=_u(t==null?void 0:t.theme),r=_u(t==null?void 0:t.darkTheme);return e==="dark"?ib(qs(n!=null?n:{},r!=null?r:{})):ab(n)},lb=t=>Ou(t),cs=(t,e)=>{let n=Ra(e),r=lb(n);for(let[o,s]of Object.entries(r))t.style.setProperty(o,s)},$u=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{t(Ri())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>t(Ri());n.addEventListener?(n.addEventListener("change",r),e.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),e.push(()=>n.removeListener(r)))}return()=>{e.forEach(n=>n())}};import{Idiomorph as cb}from"idiomorph";var Ha=(t,e,n={})=>{let{preserveTypingAnimation:r=!0}=n;cb.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Uu=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function zu(t){let{direction:e,history:n,currentValue:r,atStart:o,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ba}}}function qu(t,e){var n,r,o,s,a,i,d,c,u,m,g,f,w,v,M,W,T,k,E,P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe,se,de;return[t.id,t.role,(r=(n=t.content)==null?void 0:n.length)!=null?r:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=t.llmContent)==null?void 0:c.length)!=null?u:0,(g=(m=t.approval)==null?void 0:m.status)!=null?g:"",(w=(f=t.toolCall)==null?void 0:f.status)!=null?w:"",(M=(v=t.toolCall)==null?void 0:v.name)!=null?M:"",(k=(T=(W=t.toolCall)==null?void 0:W.chunks)==null?void 0:T.length)!=null?k:0,(L=(C=(P=(E=t.toolCall)==null?void 0:E.chunks)==null?void 0:P[t.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?L:"",typeof((F=t.toolCall)==null?void 0:F.args)=="string"?t.toolCall.args.length:(O=t.toolCall)!=null&&O.args?JSON.stringify(t.toolCall.args).length:0,(N=($=(R=t.reasoning)==null?void 0:R.chunks)==null?void 0:$.length)!=null?N:0,(ee=(pe=(Se=(Z=t.reasoning)==null?void 0:Z.chunks)==null?void 0:Se[t.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(ue=(ce=(Ie=(ve=t.reasoning)==null?void 0:ve.chunks)==null?void 0:Ie[t.reasoning.chunks.length-1])==null?void 0:ce.slice(-32))!=null?ue:"",(se=(oe=t.contentParts)==null?void 0:oe.length)!=null?se:0,(de=t.stopReason)!=null?de:"",e].join("\0")}function ju(){return new Map}function Vu(t,e,n){let r=t.get(e);return r&&r.fingerprint===n?r.wrapper:null}function Ku(t,e,n,r){t.set(e,{fingerprint:n,wrapper:r})}function Gu(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Da(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Vr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Ro(t,e){return Vr(t)-t.scrollTop<=e}function Na(t){let{following:e,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=t,u=n-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Fa(t){let{following:e,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=t;return e&&n<0?"pause":!e&&o&&n>0&&r?"resume":"none"}function Qu(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Xu(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Ju(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Cn=1e5,po=Cn+1;var js={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},db=["pre","code","a","script","style"],Oa=t=>{var e,n,r,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:js.type,placeholder:(n=t==null?void 0:t.placeholder)!=null?n:js.placeholder,speed:(r=t==null?void 0:t.speed)!=null?r:js.speed,duration:(o=t==null?void 0:t.duration)!=null?o:js.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:js.buffer}},pb=[{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"}],Zu=new Map;for(let t of pb)Zu.set(t.name,t);var Vs=(t,e)=>{var n,r;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(n=e[t])!=null?n:null:(r=Zu.get(t))!=null?r:null},_a=(t,e,n,r,o)=>{if(!o)return t;if(n!=null&&n.bufferContent)return n.bufferContent(t,r);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
19
|
-
`);return s<0?"":t.slice(0,s)}return t},ub=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},mb=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Hi=/\s/,gb=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(e.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},fb=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Hi.test(s[i])){let c=i;for(;c<s.length&&Hi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Hi.test(s[u]);)c.appendChild(ub(r,s[u],e,n.value)),n.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,t)},hb=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(mb(r,c,e,n.value)),n.value+=1));o.replaceChild(a,t)},Ks=(t,e,n,r)=>{var m,g;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=r==null?void 0:r.skipTags)!=null?m:db).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)gb(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},u=e==="char"?fb:hb;for(let f of i)u(f,n,c);return o.innerHTML},$a=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Gs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Yu=new WeakMap,yb=(t,e)=>{var s;if(!t.styles)return;let n=Yu.get(e);if(n||(n=new Set,Yu.set(e,n)),n.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(t.name)}n.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Bi=new WeakMap,bb=(t,e)=>{if(!t.onAttach)return;let n=Bi.get(e);if(n||(n=new Map,Bi.set(e,n)),n.has(t.name))return;let r=t.onAttach(e);n.set(t.name,r)},em=t=>{let e=Bi.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Di=(t,e)=>{yb(t,e),bb(t,e)};function Ni(t,e=Cn){let n=t.style.position,r=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=r,t.style.isolation=o}}var Qs=0,uo=null;function Fi(t=document){var n;if(Qs++,Qs===1){let r=t.body,s=((n=t.defaultView)!=null?n:window).scrollY||t.documentElement.scrollTop;uo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,Qs=Math.max(0,Qs-1),Qs===0&&uo)){let o=t.body,s=(r=t.defaultView)!=null?r:window;o.style.overflow=uo.originalOverflow,o.style.position=uo.originalPosition,o.style.top=uo.originalTop,o.style.width=uo.originalWidth,s.scrollTo(0,uo.scrollY),uo=null}}}var Xs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},yn=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="docked"},Js=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="composer-bar"},gr=t=>{var n,r,o,s,a,i;let e=(n=t==null?void 0:t.launcher)==null?void 0:n.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Xs.side,width:(o=e==null?void 0:e.width)!=null?o:Xs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Xs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Xs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Xs.maxHeight}};var fr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(t,e={})=>{var M,W,T,k,E,P;let{showClose:n=!0,wrapperClassName:r=vb,buttonSize:o,iconSize:s="28px"}=e,a=(M=t==null?void 0:t.launcher)!=null?M:{},i=(W=o!=null?o:a.closeButtonSize)!=null?W:"32px",d=y("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(k=a.closeButtonShowTooltip)!=null?k:!0,m=(E=a.closeButtonIconName)!=null?E:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),w=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||In.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=fe(m,s,"currentColor",1);if(v?(v.style.display="block",w.appendChild(v)):w.textContent=g,d.appendChild(w),u&&c){let C=null,L=()=>{if(C)return;let O=w.ownerDocument,R=O.body;if(!R)return;C=Pr(O,"div","persona-clear-chat-tooltip"),C.textContent=c;let $=Pr(O,"div");$.className="persona-clear-chat-tooltip-arrow",C.appendChild($);let N=w.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(po),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",F),w.addEventListener("focus",L),w.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",F),w.removeEventListener("focus",L),w.removeEventListener("blur",F)}}return{button:w,wrapper:d}},wb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",za=(t,e={})=>{var C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie;let{wrapperClassName:n=wb,buttonSize:r,iconSize:o="20px"}=e,a=(L=((C=t==null?void 0:t.launcher)!=null?C:{}).clearChat)!=null?L:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",c=(R=a.iconColor)!=null?R:"",u=($=a.backgroundColor)!=null?$:"",m=(N=a.borderWidth)!=null?N:"",g=(Z=a.borderColor)!=null?Z:"",f=(Se=a.borderRadius)!=null?Se:"",w=(pe=a.paddingX)!=null?pe:"",v=(ee=a.paddingY)!=null?ee:"",M=(ve=a.tooltipText)!=null?ve:"Clear chat",W=(Ie=a.showTooltip)!=null?Ie:!0,T=y("div",n),k=!!(m||g),E=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||In.actionIconColor,backgroundColor:u||void 0,border:k?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:w||void 0,paddingRight:w||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),P=fe(d,o,"currentColor",1);if(P&&(P.style.display="block",E.appendChild(P)),T.appendChild(E),W&&M){let ce=null,ue=()=>{if(ce)return;let se=E.ownerDocument,de=se.body;if(!de)return;ce=Pr(se,"div","persona-clear-chat-tooltip"),ce.textContent=M;let $e=Pr(se,"div");$e.className="persona-clear-chat-tooltip-arrow",ce.appendChild($e);let Ne=E.getBoundingClientRect();ce.style.position="fixed",ce.style.zIndex=String(po),ce.style.left=`${Ne.left+Ne.width/2}px`,ce.style.top=`${Ne.top-8}px`,ce.style.transform="translate(-50%, -100%)",de.appendChild(ce)},oe=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};T.addEventListener("mouseenter",ue),T.addEventListener("mouseleave",oe),E.addEventListener("focus",ue),E.addEventListener("blur",oe),T._cleanupTooltip=()=>{oe(),T.removeEventListener("mouseenter",ue),T.removeEventListener("mouseleave",oe),E.removeEventListener("focus",ue),E.removeEventListener("blur",oe)}}return{button:E,wrapper:T}};var In={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue;let{config:e,showClose:n=!0}=t,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=e==null?void 0:e.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let oe=parseFloat(s)||24,se=fe(d,oe*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=(O=e==null?void 0:e.launcher)==null?void 0:O.agentIconText)!=null?R:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let oe=y("img");oe.src=e.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(Z=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?Z:"\u{1F4AC}";let u=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Et("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Se=e==null?void 0:e.launcher)==null?void 0:Se.title)!=null?pe:"Chat Assistant",style:{color:In.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(ve=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?ve:"Here to help you get answers fast",style:{color:In.subtitleColor}});u.append(m,g),i?r.append(u):r.append(c,u);let f=(Ie=o.clearChat)!=null?Ie:{},w=(ce=f.enabled)!=null?ce:!0,v=(ue=f.placement)!=null?ue:"inline",M=null,W=null;if(w){let se=za(e,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=se.button,W=se.wrapper,v==="top-right"&&(W.style.right="48px"),v==="inline"&&r.appendChild(W)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&v==="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:E}=Ua(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:g,closeButton:k,closeButtonWrapper:E,clearChatButton:M,clearChatButtonWrapper:W}},Ys=(t,e,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function ds(t){let{items:e,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=t,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(po)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",f.id),f.destructive&&w.setAttribute("data-destructive",""),f.icon){let M=fe(f.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let v=document.createElement("span");v.textContent=f.label,w.appendChild(v),w.addEventListener("click",M=>{M.stopPropagation(),u(),n(f.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=w=>{!a.contains(w.target)&&!r.contains(w.target)&&u()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:m,destroy:g}}function An(t){let{icon:e,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=fe(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,m]of Object.entries(i))d.setAttribute(u,m);return d}function Oi(t){let{icon:e,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=y("button",c);if(u.type="button",u.setAttribute("aria-label",n),e){let g=fe(e,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let m=y("span");if(m.textContent=n,u.appendChild(m),i&&u.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))u.setAttribute(g,f);return u}function tm(t){var f,w;let{label:e,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=y("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let m=fe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",c.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=ds({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{u.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var xb=t=>{var r;let e=Ho({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=(r=t.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function Cb(t,e,n){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=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(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=fe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ds({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),t.appendChild(i)}}var Ab=t=>{var T,k,E,P,C,L,F,O,R;let{config:e,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=tm({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=In.titleColor,u=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=y("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=In.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(u),Cb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let N=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||N()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),N())})}let $=o==null?void 0:o.titleRowHover;$&&(c.style.borderRadius=(L=$.borderRadius)!=null?L:"10px",c.style.padding=(F=$.padding)!=null?F:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var N,Z;c.style.backgroundColor=(N=$.background)!=null?N:"",c.style.borderColor=(Z=$.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(O=a.closeButtonSize)!=null?O:"32px",g=y("div",""),f=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");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||In.actionIconColor;let w=(R=a.closeButtonIconName)!=null?R:"x",v=fe(w,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let M=y("div");M.style.display="none";let W=y("span");return W.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:W,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},nm={default:xb,minimal:Ab},Sb=t=>{var e;return(e=nm[t])!=null?e:nm.default},qa=(t,e,n)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:t,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=y("div");u.style.display="none";let m=y("span"),g=y("span"),f=y("button");f.style.display="none";let w=y("div");return w.style.display="none",{header:c,iconHolder:u,headerTitle:m,headerSubtitle:g,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Sb(r)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ja=t=>{var a,i;let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;e.style.maxHeight=`${n*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Va=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee;let e=(P=t==null?void 0:t.sendButton)!=null?P:{},n=(C=e.useIcon)!=null?C:!1,r=(L=e.iconText)!=null?L:"\u2191",o=e.iconName,s=(F=e.stopIconName)!=null?F:"square",a=(O=e.tooltipText)!=null?O:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(N=($=t==null?void 0:t.copy)==null?void 0:$.sendButtonLabel)!=null?N:"Send",c=(Se=(Z=t==null?void 0:t.copy)==null?void 0:Z.stopButtonLabel)!=null?Se:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,m=(ee=e.size)!=null?ee:"40px",g=e.backgroundColor,f=e.textColor,w=y("div","persona-send-button-wrapper"),v=Et("button",{className:Is("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&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),M=null,W=null;if(n){let ve=parseFloat(m)||24,Ie=(f==null?void 0:f.trim())||"currentColor";o?(M=fe(o,ve,Ie,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,W=fe(s,ve,Ie,2)}else v.textContent=d;let T=null;u&&a&&(T=y("div","persona-send-button-tooltip"),T.textContent=a,w.appendChild(T)),v.setAttribute("aria-label",a),w.appendChild(v);let k="send";return{button:v,wrapper:w,setMode:ve=>{if(ve===k)return;k=ve;let Ie=ve==="stop"?i:a;if(v.setAttribute("aria-label",Ie),T&&(T.textContent=Ie),n){if(M&&W){let ce=ve==="stop"?W:M;v.replaceChildren(ce)}}else v.textContent=ve==="stop"?c:d}}},Ka=t=>{var T,k,E,P,C,L,F,O,R,$,N,Z;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(E=t==null?void 0:t.sendButton)==null?void 0:E.size)!=null?P:"40px",i=(C=e.iconName)!=null?C:"mic",d=(L=e.iconSize)!=null?L:a,c=parseFloat(d)||24,u=(O=e.backgroundColor)!=null?O:(F=t==null?void 0:t.sendButton)==null?void 0:F.backgroundColor,m=($=e.iconColor)!=null?$:(R=t==null?void 0:t.sendButton)==null?void 0:R.textColor,g=y("div","persona-send-button-wrapper"),f=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),v=fe(i,c,m||"currentColor",1.5);v?f.appendChild(v):f.textContent="\u{1F3A4}",g.appendChild(f);let M=(N=e.tooltipText)!=null?N:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&M){let Se=y("div","persona-send-button-tooltip");Se.textContent=M,g.appendChild(Se)}return{button:f,wrapper:g}},Ga=t=>{var w,v,M,W,T,k,E,P;let e=(w=t==null?void 0:t.attachments)!=null?w:{};if(e.enabled!==!0)return null;let n=(M=(v=t==null?void 0:t.sendButton)==null?void 0:v.size)!=null?M:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((W=e.allowedTypes)!=null?W:qr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=e.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),u=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=e.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let m=fe(s,d,"currentColor",1.5);m?u.appendChild(m):u.textContent="\u{1F4CE}",u.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(u);let g=(P=e.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:u,wrapper:c,input:o,previewsContainer:r}},Qa=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=y("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Xa=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=t=>{var w,v,M,W,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa(),o=Et("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),u=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let m=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(g,f),o.append(m),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,u),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var rm=()=>{let t=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=y("span","persona-pill-peek__icon"),n=fe("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=fe("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,r,o),{root:t,textNode:r}},om=t=>{var w,v,M,W,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(m,s,g),c&&n.append(c.previewsContainer),n.append(u,r,o);let f=u;return{footer:n,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:f,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var sm=t=>{var u,m,g,f,w,v,M,W,T,k,E,P,C,L,F,O,R;let e=(m=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?m:!0,n=yn(t);if(Js(t)){let $=(f=(g=t==null?void 0:t.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(w=$.expandedSize)!=null?w:"anchored",N.style.zIndex=String((M=(v=t==null?void 0:t.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Se=y("div","persona-widget-pill-root");return Se.setAttribute("data-persona-composer-bar",""),Se.dataset.state="collapsed",Se.dataset.expandedSize=(W=$.expandedSize)!=null?W:"anchored",Se.style.zIndex=String((k=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?k:Cn),{wrapper:N,panel:Z,pillRoot:Se}}if(n){let $=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(N),{wrapper:$,panel:N}}if(!e){let $=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.width)!=null?P:"100%";return $.style.width=Z,N.style.width="100%",$.appendChild(N),{wrapper:$,panel:N}}let o=(C=t==null?void 0:t.launcher)!=null?C:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(L=t==null?void 0:t.launcher)==null?void 0:L.zIndex)!=null?F:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(O=t==null?void 0:t.launcher)==null?void 0:O.width)!=null?R:t==null?void 0:t.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Tb=(t,e)=>{var E,P,C,L,F,O,R,$,N;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:r,wrapper:o}=Ua(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=za(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let u=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(L=t==null?void 0:t.copy)==null?void 0:L.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),m=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(O=t==null?void 0:t.copy)==null?void 0:O.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),g=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,m),f=y("div","persona-flex persona-flex-col persona-gap-3"),w=($=t==null?void 0:t.layout)==null?void 0:$.contentMaxWidth;w&&(f.style.maxWidth=w,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=t==null?void 0:t.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let M=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),W=om({config:t}),{root:T,textNode:k}=rm();return n.append(d,o,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:f,composerOverlay:M,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:u,introSubtitle:m,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:T,peekTextNode:k}},am=(t,e=!0)=>{var M,W,T,k,E,P,C,L,F;if(Js(t))return Tb(t,e);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(M=t==null?void 0:t.layout)==null?void 0:M.header,o=((W=t==null?void 0:t.layout)==null?void 0:W.showHeader)!==!1,s=r?qa(t,r,{showClose:e}):Ho({config:t,showClose:e}),a=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:yn(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),m=(C=t==null?void 0:t.layout)==null?void 0:C.contentMaxWidth;m&&(u.style.maxWidth=m,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((L=t==null?void 0:t.copy)==null?void 0:L.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let f=Ja({config:t}),w=((F=t==null?void 0:t.layout)==null?void 0:F.showFooter)!==!1;o?Ys(n,s,t):(s.header.style.display="none",Ys(n,s,t)),n.append(a);let v=Et("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 w||(f.footer.style.display="none"),n.append(f.footer),n.append(v),{container:n,body:a,messagesWrapper:u,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var _i=(t,e)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
19
|
+
`);return s<0?"":t.slice(0,s)}return t},ub=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},mb=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Hi=/\s/,gb=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(e.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},fb=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Hi.test(s[i])){let c=i;for(;c<s.length&&Hi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Hi.test(s[u]);)c.appendChild(ub(r,s[u],e,n.value)),n.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,t)},hb=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(mb(r,c,e,n.value)),n.value+=1));o.replaceChild(a,t)},Ks=(t,e,n,r)=>{var m,g;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=r==null?void 0:r.skipTags)!=null?m:db).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)gb(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},u=e==="char"?fb:hb;for(let f of i)u(f,n,c);return o.innerHTML},$a=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Gs=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Yu=new WeakMap,yb=(t,e)=>{var s;if(!t.styles)return;let n=Yu.get(e);if(n||(n=new Set,Yu.set(e,n)),n.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(t.name)}n.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Bi=new WeakMap,bb=(t,e)=>{if(!t.onAttach)return;let n=Bi.get(e);if(n||(n=new Map,Bi.set(e,n)),n.has(t.name))return;let r=t.onAttach(e);n.set(t.name,r)},em=t=>{let e=Bi.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Di=(t,e)=>{yb(t,e),bb(t,e)};function Ni(t,e=Cn){let n=t.style.position,r=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=r,t.style.isolation=o}}var Qs=0,uo=null;function Fi(t=document){var n;if(Qs++,Qs===1){let r=t.body,s=((n=t.defaultView)!=null?n:window).scrollY||t.documentElement.scrollTop;uo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,Qs=Math.max(0,Qs-1),Qs===0&&uo)){let o=t.body,s=(r=t.defaultView)!=null?r:window;o.style.overflow=uo.originalOverflow,o.style.position=uo.originalPosition,o.style.top=uo.originalTop,o.style.width=uo.originalWidth,s.scrollTo(0,uo.scrollY),uo=null}}}var Xs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},yn=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="docked"},Js=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="composer-bar"},gr=t=>{var n,r,o,s,a,i;let e=(n=t==null?void 0:t.launcher)==null?void 0:n.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Xs.side,width:(o=e==null?void 0:e.width)!=null?o:Xs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Xs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Xs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Xs.maxHeight}};var fr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(t,e={})=>{var M,W,T,k,E,P;let{showClose:n=!0,wrapperClassName:r=vb,buttonSize:o,iconSize:s="28px"}=e,a=(M=t==null?void 0:t.launcher)!=null?M:{},i=(W=o!=null?o:a.closeButtonSize)!=null?W:"32px",d=y("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(k=a.closeButtonShowTooltip)!=null?k:!0,m=(E=a.closeButtonIconName)!=null?E:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),w=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||In.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=fe(m,s,"currentColor",1);if(v?(v.style.display="block",w.appendChild(v)):w.textContent=g,d.appendChild(w),u&&c){let C=null,L=()=>{if(C)return;let O=w.ownerDocument,R=O.body;if(!R)return;C=Pr(O,"div","persona-clear-chat-tooltip"),C.textContent=c;let $=Pr(O,"div");$.className="persona-clear-chat-tooltip-arrow",C.appendChild($);let N=w.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(po),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",F),w.addEventListener("focus",L),w.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",F),w.removeEventListener("focus",L),w.removeEventListener("blur",F)}}return{button:w,wrapper:d}},wb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",za=(t,e={})=>{var C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie;let{wrapperClassName:n=wb,buttonSize:r,iconSize:o="20px"}=e,a=(L=((C=t==null?void 0:t.launcher)!=null?C:{}).clearChat)!=null?L:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(O=a.iconName)!=null?O:"refresh-cw",c=(R=a.iconColor)!=null?R:"",u=($=a.backgroundColor)!=null?$:"",m=(N=a.borderWidth)!=null?N:"",g=(Z=a.borderColor)!=null?Z:"",f=(Se=a.borderRadius)!=null?Se:"",w=(pe=a.paddingX)!=null?pe:"",v=(ee=a.paddingY)!=null?ee:"",M=(ve=a.tooltipText)!=null?ve:"Clear chat",W=(Ie=a.showTooltip)!=null?Ie:!0,T=y("div",n),k=!!(m||g),E=Et("button",{className:Is("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||In.actionIconColor,backgroundColor:u||void 0,border:k?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:w||void 0,paddingRight:w||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),P=fe(d,o,"currentColor",1);if(P&&(P.style.display="block",E.appendChild(P)),T.appendChild(E),W&&M){let ce=null,ue=()=>{if(ce)return;let se=E.ownerDocument,de=se.body;if(!de)return;ce=Pr(se,"div","persona-clear-chat-tooltip"),ce.textContent=M;let $e=Pr(se,"div");$e.className="persona-clear-chat-tooltip-arrow",ce.appendChild($e);let Ne=E.getBoundingClientRect();ce.style.position="fixed",ce.style.zIndex=String(po),ce.style.left=`${Ne.left+Ne.width/2}px`,ce.style.top=`${Ne.top-8}px`,ce.style.transform="translate(-50%, -100%)",de.appendChild(ce)},oe=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};T.addEventListener("mouseenter",ue),T.addEventListener("mouseleave",oe),E.addEventListener("focus",ue),E.addEventListener("blur",oe),T._cleanupTooltip=()=>{oe(),T.removeEventListener("mouseenter",ue),T.removeEventListener("mouseleave",oe),E.removeEventListener("focus",ue),E.removeEventListener("blur",oe)}}return{button:E,wrapper:T}};var In={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Ho=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue;let{config:e,showClose:n=!0}=t,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=e==null?void 0:e.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let oe=parseFloat(s)||24,se=fe(d,oe*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=(O=e==null?void 0:e.launcher)==null?void 0:O.agentIconText)!=null?R:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let oe=y("img");oe.src=e.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(Z=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?Z:"\u{1F4AC}";let u=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Et("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Se=e==null?void 0:e.launcher)==null?void 0:Se.title)!=null?pe:"Chat Assistant",style:{color:In.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(ve=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?ve:"Here to help you get answers fast",style:{color:In.subtitleColor}});u.append(m,g),i?r.append(u):r.append(c,u);let f=(Ie=o.clearChat)!=null?Ie:{},w=(ce=f.enabled)!=null?ce:!0,v=(ue=f.placement)!=null?ue:"inline",M=null,W=null;if(w){let se=za(e,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=se.button,W=se.wrapper,v==="top-right"&&(W.style.right="48px"),v==="inline"&&r.appendChild(W)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&v==="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:E}=Ua(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:g,closeButton:k,closeButtonWrapper:E,clearChatButton:M,clearChatButtonWrapper:W}},Ys=(t,e,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function ds(t){let{items:e,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=t,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(po)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",f.id),f.destructive&&w.setAttribute("data-destructive",""),f.icon){let M=fe(f.icon,16,"currentColor",1.5);M&&w.appendChild(M)}let v=document.createElement("span");v.textContent=f.label,w.appendChild(v),w.addEventListener("click",M=>{M.stopPropagation(),u(),n(f.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=w=>{!a.contains(w.target)&&!r.contains(w.target)&&u()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:m,destroy:g}}function An(t){let{icon:e,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=fe(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,m]of Object.entries(i))d.setAttribute(u,m);return d}function Oi(t){let{icon:e,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=y("button",c);if(u.type="button",u.setAttribute("aria-label",n),e){let g=fe(e,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let m=y("span");if(m.textContent=n,u.appendChild(m),i&&u.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))u.setAttribute(g,f);return u}function tm(t){var f,w;let{label:e,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=y("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let m=fe(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",c.style.padding=(w=d.padding)!=null?w:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=ds({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{u.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var xb=t=>{var r;let e=Ho({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=(r=t.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function Cb(t,e,n){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=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(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=fe(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ds({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),t.appendChild(i)}}var Ab=t=>{var T,k,E,P,C,L,F,O,R;let{config:e,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=tm({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=In.titleColor,u=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=y("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=In.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(u),Cb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let N=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||N()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),N())})}let $=o==null?void 0:o.titleRowHover;$&&(c.style.borderRadius=(L=$.borderRadius)!=null?L:"10px",c.style.padding=(F=$.padding)!=null?F:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var N,Z;c.style.backgroundColor=(N=$.background)!=null?N:"",c.style.borderColor=(Z=$.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(O=a.closeButtonSize)!=null?O:"32px",g=y("div",""),f=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");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||In.actionIconColor;let w=(R=a.closeButtonIconName)!=null?R:"x",v=fe(w,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let M=y("div");M.style.display="none";let W=y("span");return W.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:W,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},nm={default:xb,minimal:Ab},Sb=t=>{var e;return(e=nm[t])!=null?e:nm.default},qa=(t,e,n)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:t,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=y("div");u.style.display="none";let m=y("span"),g=y("span"),f=y("button");f.style.display="none";let w=y("div");return w.style.display="none",{header:c,iconHolder:u,headerTitle:m,headerSubtitle:g,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Sb(r)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ja=t=>{var a,i;let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;e.style.maxHeight=`${n*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Va=t=>{var P,C,L,F,O,R,$,N,Z,Se,pe,ee;let e=(P=t==null?void 0:t.sendButton)!=null?P:{},n=(C=e.useIcon)!=null?C:!1,r=(L=e.iconText)!=null?L:"\u2191",o=e.iconName,s=(F=e.stopIconName)!=null?F:"square",a=(O=e.tooltipText)!=null?O:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(N=($=t==null?void 0:t.copy)==null?void 0:$.sendButtonLabel)!=null?N:"Send",c=(Se=(Z=t==null?void 0:t.copy)==null?void 0:Z.stopButtonLabel)!=null?Se:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,m=(ee=e.size)!=null?ee:"40px",g=e.backgroundColor,f=e.textColor,w=y("div","persona-send-button-wrapper"),v=Et("button",{className:Is("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&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),M=null,W=null;if(n){let ve=parseFloat(m)||24,Ie=(f==null?void 0:f.trim())||"currentColor";o?(M=fe(o,ve,Ie,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,W=fe(s,ve,Ie,2)}else v.textContent=d;let T=null;u&&a&&(T=y("div","persona-send-button-tooltip"),T.textContent=a,w.appendChild(T)),v.setAttribute("aria-label",a),w.appendChild(v);let k="send";return{button:v,wrapper:w,setMode:ve=>{if(ve===k)return;k=ve;let Ie=ve==="stop"?i:a;if(v.setAttribute("aria-label",Ie),T&&(T.textContent=Ie),n){if(M&&W){let ce=ve==="stop"?W:M;v.replaceChildren(ce)}}else v.textContent=ve==="stop"?c:d}}},Ka=t=>{var T,k,E,P,C,L,F,O,R,$,N,Z;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(E=t==null?void 0:t.sendButton)==null?void 0:E.size)!=null?P:"40px",i=(C=e.iconName)!=null?C:"mic",d=(L=e.iconSize)!=null?L:a,c=parseFloat(d)||24,u=(O=e.backgroundColor)!=null?O:(F=t==null?void 0:t.sendButton)==null?void 0:F.backgroundColor,m=($=e.iconColor)!=null?$:(R=t==null?void 0:t.sendButton)==null?void 0:R.textColor,g=y("div","persona-send-button-wrapper"),f=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),v=fe(i,c,m||"currentColor",1.5);v?f.appendChild(v):f.textContent="\u{1F3A4}",g.appendChild(f);let M=(N=e.tooltipText)!=null?N:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&M){let Se=y("div","persona-send-button-tooltip");Se.textContent=M,g.appendChild(Se)}return{button:f,wrapper:g}},Ga=t=>{var w,v,M,W,T,k,E,P;let e=(w=t==null?void 0:t.attachments)!=null?w:{};if(e.enabled!==!0)return null;let n=(M=(v=t==null?void 0:t.sendButton)==null?void 0:v.size)!=null?M:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((W=e.allowedTypes)!=null?W:qr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=e.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),u=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=e.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let m=fe(s,d,"currentColor",1.5);m?u.appendChild(m):u.textContent="\u{1F4CE}",u.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(u);let g=(P=e.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:u,wrapper:c,input:o,previewsContainer:r}},Qa=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=y("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Xa=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=t=>{var w,v,M,W,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa(),o=Et("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),u=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let m=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(g,f),o.append(m),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,u),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var rm=()=>{let t=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=y("span","persona-pill-peek__icon"),n=fe("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=fe("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,r,o),{root:t,textNode:r}},om=t=>{var w,v,M,W,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(m,s,g),c&&n.append(c.previewsContainer),n.append(u,r,o);let f=u;return{footer:n,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:f,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var sm=t=>{var u,m,g,f,w,v,M,W,T,k,E,P,C,L,F,O,R;let e=(m=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?m:!0,n=yn(t);if(Js(t)){let $=(f=(g=t==null?void 0:t.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(w=$.expandedSize)!=null?w:"anchored",N.style.zIndex=String((M=(v=t==null?void 0:t.launcher)==null?void 0:v.zIndex)!=null?M:Cn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Se=y("div","persona-widget-pill-root");return Se.setAttribute("data-persona-composer-bar",""),Se.dataset.state="collapsed",Se.dataset.expandedSize=(W=$.expandedSize)!=null?W:"anchored",Se.style.zIndex=String((k=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?k:Cn),{wrapper:N,panel:Z,pillRoot:Se}}if(n){let $=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(N),{wrapper:$,panel:N}}if(!e){let $=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.width)!=null?P:"100%";return $.style.width=Z,N.style.width="100%",$.appendChild(N),{wrapper:$,panel:N}}let o=(C=t==null?void 0:t.launcher)!=null?C:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(L=t==null?void 0:t.launcher)==null?void 0:L.zIndex)!=null?F:Cn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(O=t==null?void 0:t.launcher)==null?void 0:O.width)!=null?R:t==null?void 0:t.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Tb=(t,e)=>{var E,P,C,L,F,O,R,$,N;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:r,wrapper:o}=Ua(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(E=t==null?void 0:t.launcher)==null?void 0:E.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=za(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let u=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(L=t==null?void 0:t.copy)==null?void 0:L.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),m=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(O=t==null?void 0:t.copy)==null?void 0:O.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),g=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,m),f=y("div","persona-flex persona-flex-col persona-gap-3"),w=($=t==null?void 0:t.layout)==null?void 0:$.contentMaxWidth;w&&(f.style.maxWidth=w,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=t==null?void 0:t.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let M=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),W=om({config:t}),{root:T,textNode:k}=rm();return n.append(d,o,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:f,composerOverlay:M,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:u,introSubtitle:m,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:T,peekTextNode:k}},am=(t,e=!0)=>{var M,W,T,k,E,P,C,L,F;if(Js(t))return Tb(t,e);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(M=t==null?void 0:t.layout)==null?void 0:M.header,o=((W=t==null?void 0:t.layout)==null?void 0:W.showHeader)!==!1,s=r?qa(t,r,{showClose:e}):Ho({config:t,showClose:e}),a=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:yn(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),m=(C=t==null?void 0:t.layout)==null?void 0:C.contentMaxWidth;m&&(u.style.maxWidth=m,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((L=t==null?void 0:t.copy)==null?void 0:L.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let f=Ja({config:t}),w=((F=t==null?void 0:t.layout)==null?void 0:F.showFooter)!==!1;o?Ys(n,s,t):(s.header.style.display="none",Ys(n,s,t)),n.append(a);let v=Et("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 w||(f.footer.style.display="none"),n.append(f.footer),n.append(v),{container:n,body:a,messagesWrapper:u,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var _i=(t,e)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
20
20
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
21
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
22
22
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -24,7 +24,7 @@ _Details: ${n.message}_`:r}var Us=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
24
24
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
25
25
|
</span>
|
|
26
26
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
27
|
-
`,n.addEventListener("click",e);let r=s=>{var k,E,P,C,L,F,O,R,$,N,Z,Se,pe;let a=(k=s.launcher)!=null?k:{},i=yn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(m.style.height=ee,m.style.width=ee,m.innerHTML="",a.agentIconName){let ve=parseFloat(ee)||24,Ie=fe(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(m.appendChild(Ie),m.style.display=""):(m.textContent=(L=a.agentIconText)!=null?L:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(O=a.agentIconSize)!=null?O:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(R=a.callToActionIconSize)!=null?R:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ve=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,ve=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ie=parseFloat(ee)||24,ce=Math.max(Ie-ve,8),ue=fe(a.callToActionIconName,ce,"currentColor",2);ue?f.appendChild(ue):f.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let w=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],v="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",M="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=i?M:`${v} ${w}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:Cn));let W="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Se=a.border)!=null?Se:W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,i?(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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",e),n.remove()};return t&&r(t),{element:n,update:r,destroy:o}};var im=({config:t,showClose:e})=>{let{wrapper:n,panel:r,pillRoot:o}=sm(t),s=am(t,e),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},$i=({config:t,plugins:e,onToggle:n})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:t,defaultRenderer:()=>_i(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=_i(t,n);return{instance:o,element:o.element}};var Eb=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Mb=(t,e)=>{if(!t)return null;let n=Eb(t);if(n===null)return null;let r=e==null?void 0:e[t],o=r!==void 0?r:n;return o||null},kb=(t,e)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Lb=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Ui=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},zi=320,cm=320,Pb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Ib=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Wb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Rb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Hb=(t,e,n)=>{if(t.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return t.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${zi}px`,c.style.maxHeight=`${cm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Lb(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Bb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(r=>{if(!Ui(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Db=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(r=>{if(!Ui(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,o.style.maxHeight=`${cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Nb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(r=>{if(!Ui(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Zs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(r),t.appendChild(o),t},Fb=(t,e,n)=>{let r={config:n!=null?n:{},streaming:!0,location:t,defaultRenderer:Zs};if(e){let o=e(r);if(o!==null)return o}return Zs()},Ob=(t,e)=>{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"),r=e==="user"?t.userAvatar:t.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},lm=(t,e,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(t.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},_b=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},$b=(t,e,n)=>{var w,v,M,W,T,k,E;let r=(w=e.showCopy)!=null?w:!0,o=(v=e.showUpvote)!=null?v:!0,s=(M=e.showDownvote)!=null?M:!0,a=(W=e.showReadAloud)!=null?W:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${t.id}`,P.setAttribute("data-actions-for",t.id),P}let i=(T=e.visibility)!=null?T:"hover",d=(k=e.align)!=null?k:"right",c=(E=e.layout)!=null?E:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${t.id}`,g.setAttribute("data-actions-for",t.id);let f=(P,C,L)=>{let F=An({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",L),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},qi=(t,e,n,r,o,s)=>{var oe,se,de,$e,Ne,V,G,be,X,le,Ee,Xe,Ze,xt,dt,Ye,He;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,u=(se=d==null?void 0:d.show)!=null?se:!1,m=(de=c==null?void 0:c.show)!=null?de:!1,g=($e=d==null?void 0:d.position)!=null?$e:"left",f=(Ne=c==null?void 0:c.position)!=null?Ne:"below",w=_b(t.role,i),v=y("div",w.join(" "));v.id=`bubble-${t.id}`,v.setAttribute("data-message-id",t.id),v.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Pb(t),W=(G=(V=t.content)==null?void 0:V.trim())!=null?G:"",k=M.length>0&&W===Ea,E=Oa((X=(be=s==null?void 0:s.widgetConfig)==null?void 0:be.features)==null?void 0:X.streamAnimation),P=(Xe=(Ee=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ee.streamAnimation)==null?void 0:Xe.plugins,C=t.role==="assistant"&&E.type!=="none"?Vs(E.type,P):null,L=t.role==="assistant"&&((Ze=C==null?void 0:C.isAnimating)==null?void 0:Ze.call(C,t))===!0,F=t.role==="assistant"&&C!==null&&(!!t.streaming||L);F&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),t.streaming&&O.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&O.classList.add(C.containerClass),O.style.setProperty("--persona-stream-step",`${E.speed}ms`),O.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=F?_a((xt=t.content)!=null?xt:"",E.buffer,C,t,!!t.streaming):(dt=t.content)!=null?dt:"",$=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),N=$;F&&(C==null?void 0:C.wrap)==="char"?N=Ks($,"char",t.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=Ks($,"word",t.id,{skipTags:C.skipTags}));let Z=null;if(k?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",O.appendChild(Z)):O.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&W){let K=$a(),qe=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=qe[qe.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(K,ze.nextSibling);else{let we=O.lastElementChild;we?we.appendChild(K):O.appendChild(K)}}if(m&&f==="inline"&&t.createdAt){let K=lm(t,c,"span");K.classList.add("persona-timestamp-inline");let qe=O.lastElementChild;qe?qe.appendChild(K):O.appendChild(K)}if(M.length>0){let K=Hb(M,!k&&!!W,()=>{k&&Z&&(Z.style.display="")});K?v.appendChild(K):k&&Z&&(Z.style.display="")}let Se=Ib(t);if(Se.length>0){let K=Bb(Se);K&&v.appendChild(K)}let pe=Wb(t);if(pe.length>0){let K=Db(pe);K&&v.appendChild(K)}let ee=Rb(t);if(ee.length>0){let K=Nb(ee);K&&v.appendChild(K)}if(v.appendChild(O),m&&f==="below"&&t.createdAt){let K=lm(t,c);K.classList.add("persona-mt-1"),v.appendChild(K)}let ve=t.role==="assistant"?Mb(t.stopReason,(He=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:He.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let K=!!(R&&R.trim()),qe=E.placeholder==="skeleton",ze=qe&&E.buffer==="line"&&K;if(K)ze&&v.appendChild(Gs());else if(qe)v.appendChild(Gs());else{let we=Fb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&v.appendChild(we)}}if(ve&&t.stopReason&&!t.streaming&&(W||(O.style.display="none"),v.appendChild(kb(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let K=$b(t,r,o);v.appendChild(K)}if(!u||t.role==="system")return v;let ce=y("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ue=Ob(d,t.role);return g==="right"||g==="left"&&t.role==="user"?ce.append(v,ue):ce.append(ue,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ce};var ps=new Set,Ub=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),zb=(t,e)=>{var r,o;let n=(o=(r=t.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
27
|
+
`,n.addEventListener("click",e);let r=s=>{var k,E,P,C,L,F,O,R,$,N,Z,Se,pe;let a=(k=s.launcher)!=null?k:{},i=yn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(m.style.height=ee,m.style.width=ee,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let ve=parseFloat(ee)||24,Ie=fe(a.agentIconName,ve*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(m.appendChild(Ie),m.style.display=""):(m.textContent=(L=a.agentIconText)!=null?L:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(O=a.agentIconSize)!=null?O:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(R=a.callToActionIconSize)!=null?R:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let ve=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,ve=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Ie=parseFloat(ee)||24,ce=Math.max(Ie-ve,8),ue=fe(a.callToActionIconName,ce,"currentColor",2);ue?f.appendChild(ue):f.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let w=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],v="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",M="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=i?M:`${v} ${w}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:Cn));let W="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Se=a.border)!=null?Se:W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,i?(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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",e),n.remove()};return t&&r(t),{element:n,update:r,destroy:o}};var im=({config:t,showClose:e})=>{let{wrapper:n,panel:r,pillRoot:o}=sm(t),s=am(t,e),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},$i=({config:t,plugins:e,onToggle:n})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:t,defaultRenderer:()=>_i(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=_i(t,n);return{instance:o,element:o.element}};var Eb=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Mb=(t,e)=>{if(!t)return null;let n=Eb(t);if(n===null)return null;let r=e==null?void 0:e[t],o=r!==void 0?r:n;return o||null},kb=(t,e)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Lb=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Ui=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},zi=320,cm=320,Pb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Ib=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Wb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Rb=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Hb=(t,e,n)=>{if(t.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return t.forEach((i,d)=>{var m;let c=y("img");c.alt=((m=i.alt)==null?void 0:m.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${zi}px`,c.style.maxHeight=`${cm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Lb(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Bb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(r=>{if(!Ui(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Db=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(r=>{if(!Ui(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${zi}px`,o.style.maxHeight=`${cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Nb=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(r=>{if(!Ui(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Zs=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(r),t.appendChild(o),t},Fb=(t,e,n)=>{let r={config:n!=null?n:{},streaming:!0,location:t,defaultRenderer:Zs};if(e){let o=e(r);if(o!==null)return o}return Zs()},Ob=(t,e)=>{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"),r=e==="user"?t.userAvatar:t.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},lm=(t,e,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(t.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},_b=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},$b=(t,e,n)=>{var w,v,M,W,T,k,E;let r=(w=e.showCopy)!=null?w:!0,o=(v=e.showUpvote)!=null?v:!0,s=(M=e.showDownvote)!=null?M:!0,a=(W=e.showReadAloud)!=null?W:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${t.id}`,P.setAttribute("data-actions-for",t.id),P}let i=(T=e.visibility)!=null?T:"hover",d=(k=e.align)!=null?k:"right",c=(E=e.layout)!=null?E:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${t.id}`,g.setAttribute("data-actions-for",t.id);let f=(P,C,L)=>{let F=An({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",L),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},qi=(t,e,n,r,o,s)=>{var oe,se,de,$e,Ne,V,G,be,X,le,Ee,Xe,Ze,xt,dt,Ye,He;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,u=(se=d==null?void 0:d.show)!=null?se:!1,m=(de=c==null?void 0:c.show)!=null?de:!1,g=($e=d==null?void 0:d.position)!=null?$e:"left",f=(Ne=c==null?void 0:c.position)!=null?Ne:"below",w=_b(t.role,i),v=y("div",w.join(" "));v.id=`bubble-${t.id}`,v.setAttribute("data-message-id",t.id),v.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Pb(t),W=(G=(V=t.content)==null?void 0:V.trim())!=null?G:"",k=M.length>0&&W===Ea,E=Oa((X=(be=s==null?void 0:s.widgetConfig)==null?void 0:be.features)==null?void 0:X.streamAnimation),P=(Xe=(Ee=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ee.streamAnimation)==null?void 0:Xe.plugins,C=t.role==="assistant"&&E.type!=="none"?Vs(E.type,P):null,L=t.role==="assistant"&&((Ze=C==null?void 0:C.isAnimating)==null?void 0:Ze.call(C,t))===!0,F=t.role==="assistant"&&C!==null&&(!!t.streaming||L);F&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),t.streaming&&O.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&O.classList.add(C.containerClass),O.style.setProperty("--persona-stream-step",`${E.speed}ms`),O.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=F?_a((xt=t.content)!=null?xt:"",E.buffer,C,t,!!t.streaming):(dt=t.content)!=null?dt:"",$=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent}),N=$;F&&(C==null?void 0:C.wrap)==="char"?N=Ks($,"char",t.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=Ks($,"word",t.id,{skipTags:C.skipTags}));let Z=null;if(k?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",O.appendChild(Z)):O.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&W){let K=$a(),qe=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=qe[qe.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(K,ze.nextSibling);else{let we=O.lastElementChild;we?we.appendChild(K):O.appendChild(K)}}if(m&&f==="inline"&&t.createdAt){let K=lm(t,c,"span");K.classList.add("persona-timestamp-inline");let qe=O.lastElementChild;qe?qe.appendChild(K):O.appendChild(K)}if(M.length>0){let K=Hb(M,!k&&!!W,()=>{k&&Z&&(Z.style.display="")});K?v.appendChild(K):k&&Z&&(Z.style.display="")}let Se=Ib(t);if(Se.length>0){let K=Bb(Se);K&&v.appendChild(K)}let pe=Wb(t);if(pe.length>0){let K=Db(pe);K&&v.appendChild(K)}let ee=Rb(t);if(ee.length>0){let K=Nb(ee);K&&v.appendChild(K)}if(v.appendChild(O),m&&f==="below"&&t.createdAt){let K=lm(t,c);K.classList.add("persona-mt-1"),v.appendChild(K)}let ve=t.role==="assistant"?Mb(t.stopReason,(He=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:He.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let K=!!(R&&R.trim()),qe=E.placeholder==="skeleton",ze=qe&&E.buffer==="line"&&K;if(K)ze&&v.appendChild(Gs());else if(qe)v.appendChild(Gs());else{let we=Fb("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&v.appendChild(we)}}if(ve&&t.stopReason&&!t.streaming&&(W||(O.style.display="none"),v.appendChild(kb(t.stopReason,ve))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let K=$b(t,r,o);v.appendChild(K)}if(!u||t.role==="system")return v;let ce=y("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ue=Ob(d,t.role);return g==="right"||g==="left"&&t.role==="user"?ce.append(v,ue):ce.append(ue,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ce};var ps=new Set,Ub=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),zb=(t,e)=>{var r,o;let n=(o=(r=t.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
28
|
`):""},dm=(t,e)=>{let n=ps.has(t),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ji=(t,e)=>{var pe,ee,ve,Ie,ce,ue,oe,se,de,$e,Ne;let n=t.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let o=(ee=(pe=e==null?void 0:e.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&ps.has(t.id),i=n.status!=="complete",d=zb(t,(ve=o.previewMaxLines)!=null?ve:3),c=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let u=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Ie=e==null?void 0:e.reasoning)!=null?Ie:{},w=String((ce=n.startedAt)!=null?ce:Date.now()),v=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",w),V.textContent=Ca(n),V},M=(ue=f.renderCollapsedSummary)==null?void 0:ue.call(f,{message:t,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ca(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,u.appendChild(m)):M instanceof HTMLElement?u.appendChild(M):(m.textContent=g,u.appendChild(m));let W=y("span","persona-text-xs persona-text-persona-primary");W.textContent=du(n),u.appendChild(W);let T=(oe=o.loadingAnimation)!=null?oe:"none",k=f.activeTextTemplate,E=f.completeTextTemplate,P=i?k:E,C=M instanceof HTMLElement,L=(V,G,be)=>{let X=be;for(let le of G){let Ee=y("span","persona-tool-char");Ee.style.setProperty("--char-index",String(X)),Ee.textContent=le===" "?"\xA0":le,V.appendChild(Ee),X++}return X},F=(V,G)=>{m.textContent="";let be=Aa(V,""),X=0;for(let le of be){let Ee=le.styles.length>0?(()=>{let Xe=y("span",le.styles.map(Ze=>`persona-tool-text-${Ze}`).join(" "));return m.appendChild(Xe),Xe})():m;if(le.isDuration&&i)Ee.appendChild(v());else{let Xe=le.isDuration?Ca(n):le.text;G?X=L(Ee,Xe,X):Ee.appendChild(document.createTextNode(Xe))}}};if(!C&&P)if(W.style.display="none",m.style.display="",i&&T!=="none"){let V=(se=f.loadingAnimationDuration)!=null?se:2e3;m.setAttribute("data-preserve-animation","true"),T==="pulse"?(m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&T!=="none"){m.style.display="";let V=(de=f.loadingAnimationDuration)!=null?de:2e3;if(m.setAttribute("data-preserve-animation","true"),T==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{m.classList.add(`persona-tool-loading-${T}`),m.style.setProperty("--persona-tool-anim-duration",`${V}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let G=m.textContent||g;m.textContent="",L(m,G,0)}n.status==="complete"&&(m.style.display="none")}else C||(n.status==="complete"?m.style.display="none":m.style.display="");let O=null;if(s){O=y("div","persona-flex persona-items-center");let G=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);G?O.appendChild(G):O.textContent=a?"Hide":"Show";let be=y("div","persona-flex persona-items-center persona-ml-auto");be.append(O),c.append(u,be)}else c.append(u);let R=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(Ne=($e=e==null?void 0:e.reasoning)==null?void 0:$e.renderCollapsedPreview)==null?void 0:Ne.call($e,{message:t,reasoning:n,defaultPreview:d,isActive:i,config:e!=null?e:{}});Ub(R,V)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,R),r;let $=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=a?"":"none";let N=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),O){O.innerHTML="";let G=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);G?O.appendChild(G):O.textContent=a?"Hide":"Show"}$.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(c,R,$),r};var us=new Set,qb=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),jb=(t,e)=>{var s;let n=t.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
|
|
29
29
|
`);let o=co(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
30
30
|
`):""},Vi=(t,e)=>{var n,r,o;t.style.backgroundColor=(n=e.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",t.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",t.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Vb=(t,e)=>{var u,m,g,f,w;let n=t.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",s=jb(t,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?pu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},c=a;return o==="tool-name"?c=((w=n.name)==null?void 0:w.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ei(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ei(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},pm=(t,e,n)=>{var u;let r=us.has(t),o=(u=n==null?void 0:n.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let m=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=fe(r?"chevron-up":"chevron-down",16,m,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ki=(t,e)=>{var N,Z,Se,pe,ee,ve,Ie,ce,ue;let n=t.toolCall,r=(N=e==null?void 0:e.toolCall)!=null?N:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Se=(Z=e==null?void 0:e.features)==null?void 0:Z.toolCallDisplay)!=null?Se:{},a=s.expandable!==!1,i=a&&us.has(t.id),{summary:d,previewText:c,isActive:u}=Vb(t,e),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let w=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let oe=y("span","");return oe.setAttribute("data-tool-elapsed",w),oe.textContent=Bs(n),oe},M=(ve=r.renderCollapsedSummary)==null?void 0:ve.call(r,{message:t,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Bs(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(f.textContent=M,g.appendChild(f)):M instanceof HTMLElement?g.appendChild(M):(f.textContent=d,g.appendChild(f));let W=(Ie=s.loadingAnimation)!=null?Ie:"none",T=r.activeTextTemplate,k=r.completeTextTemplate,E=u?T:k,P=M instanceof HTMLElement,C=(oe,se,de)=>{let $e=de;for(let Ne of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String($e)),V.textContent=Ne===" "?"\xA0":Ne,oe.appendChild(V),$e++}return $e},L=(oe,se)=>{var V;f.textContent="";let de=((V=n.name)==null?void 0:V.trim())||"tool",$e=Aa(oe,de),Ne=0;for(let G of $e){let be=G.styles.length>0?(()=>{let X=y("span",G.styles.map(le=>`persona-tool-text-${le}`).join(" "));return f.appendChild(X),X})():f;if(G.isDuration&&u)be.appendChild(v());else{let X=G.isDuration?Bs(n):G.text;se?Ne=C(be,X,Ne):be.appendChild(document.createTextNode(X))}}};if(!P)if(u&&W!=="none"){let oe=(ce=r.loadingAnimationDuration)!=null?ce:2e3;if(f.setAttribute("data-preserve-animation","true"),W==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),E&&L(E,!1);else if(f.classList.add(`persona-tool-loading-${W}`),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),W==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)L(E,!0);else{let se=f.textContent||d;f.textContent="",C(f,se,0)}}else E&&L(E,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,oe,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show";let de=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(F),m.append(g,de)}else m.append(g);let O=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&c){let oe=(ue=r.renderCollapsedPreview)==null?void 0:ue.call(r,{message:t,toolCall:n,defaultPreview:c,isActive:u,config:e!=null?e:{}});qb(O,oe)||(O.textContent=c),O.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,O),o;let R=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let oe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=n.name,R.appendChild(oe)}if(n.args!==void 0){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=co(n.args),oe.append(se,de),R.appendChild(oe)}if(n.chunks&&n.chunks.length){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=n.chunks.join(""),oe.append(se,de),R.appendChild(oe)}if(n.status==="complete"&&n.result!==void 0){let oe=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Vi(de,r),de.textContent=co(n.result),oe.append(se,de),R.appendChild(oe)}if(n.status==="complete"&&typeof n.duration=="number"){let oe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${n.duration}ms`,R.appendChild(oe)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=fe(i?"chevron-up":"chevron-down",16,oe,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",O.style.display=i?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(m,O,R),o};var Bo=new Map,Ya=t=>{let n=(t.startsWith(Ur)?t.slice(Ur.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},um=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,mm=(t,e)=>{var r,o,s;let n=(o=(r=um(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Bo.get(t))!=null?s:n==="expanded"},gm=(t,e,n)=>{var a,i;let r=um(n);t.setAttribute("aria-expanded",e?"true":"false");let o=t.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=fe(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},fm=(t,e,n)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=mm(t,n);gm(r,s,n),o.style.display=s?"":"none"};var Za=(t,e)=>{var L,F,O,R,$,N,Z,Se,pe,ee,ve,Ie,ce,ue,oe;let n=t.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(L=r==null?void 0:r.backgroundColor)!=null?L:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=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=r==null?void 0:r.titleColor)!=null?O:"currentColor",u=fe(d,20,c,2);u&&i.appendChild(u);let m=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",g.appendChild(f),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),g.appendChild(se)}m.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Ur)?Ps(n.toolName):void 0,M=($=r==null?void 0:r.formatDescription)==null?void 0:$.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),W=!n.toolName,T=M||(W?n.description:`The assistant wants to use \u201C${v!=null?v:Ya(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=T,m.appendChild(k),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let de=y("span","persona-font-medium");de.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,se.appendChild(de),se.appendChild(document.createTextNode(n.reason)),m.appendChild(se)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",P=!!n.description&&!W,C=P||!!n.parameters;if(E!=="hidden"&&C){let se=mm(t.id,e),de=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");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let $e=y("span");$e.setAttribute("data-approval-details-label","true");let Ne=y("span","persona-inline-flex persona-items-center");Ne.setAttribute("data-approval-details-chevron","true"),de.append($e,Ne),gm(de,se,e),m.appendChild(de);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",P){let G=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(G.style.color=r.descriptionColor),G.textContent=n.description,V.appendChild(G)}if(n.parameters){let G=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");r!=null&&r.parameterBackgroundColor&&(G.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(G.style.color=r.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=co(n.parameters),V.appendChild(G)}m.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let de=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");de.type="button",de.style.backgroundColor=(Se=r==null?void 0:r.approveButtonColor)!=null?Se:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let $e=fe("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);$e&&($e.style.marginRight="4px",de.appendChild($e));let Ne=document.createTextNode((ve=r==null?void 0:r.approveLabel)!=null?ve:"Approve");de.appendChild(Ne);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-cursor-pointer");V.type="button",V.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",V.style.color=(ce=r==null?void 0:r.denyButtonTextColor)!=null?ce:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let G=fe("shield-x",14,(ue=r==null?void 0:r.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",V.appendChild(G));let be=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");V.appendChild(be),se.append(de,V),m.appendChild(se)}return a.append(i,m),s.appendChild(a),s};function Kb(t){var n,r;let e=(n=t.getRootNode)==null?void 0:n.call(t);return e instanceof ShadowRoot?e:((r=t.ownerDocument)!=null?r:document).body}function hm(t){var v;let{anchor:e,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=t,c=(v=t.container)!=null?v:Kb(e),u=!1,m=null,g=()=>{if(!u)return;let M=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`);let W=r==="top-start"||r==="top-end"?M.top-o-n.getBoundingClientRect().height:M.bottom+o,T=r==="bottom-end"||r==="top-end"?M.right-n.getBoundingClientRect().width:M.left;n.style.top=`${W}px`,n.style.left=`${T}px`},f=()=>{u&&(u=!1,m&&(m(),m=null),n.remove())},w=()=>{var P,C,L;if(u)return;u=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),g();let M=(C=((P=e.ownerDocument)!=null?P:document).defaultView)!=null?C:window,W=(L=e.ownerDocument)!=null?L:document,T=()=>{if(!e.isConnected){f(),d==null||d("anchor-removed");return}g()},k=F=>{let O=typeof F.composedPath=="function"?F.composedPath():[];O.includes(n)||O.includes(e)||(f(),d==null||d("outside"))},E=M.setTimeout(()=>{W.addEventListener("pointerdown",k,!0)},0);M.addEventListener("scroll",T,!0),M.addEventListener("resize",T),m=()=>{M.clearTimeout(E),W.removeEventListener("pointerdown",k,!0),M.removeEventListener("scroll",T,!0),M.removeEventListener("resize",T)},i==null||i()};return{get isOpen(){return u},open:w,close:f,toggle:()=>u?f():w(),reposition:g,destroy:f}}function ym(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Gb=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),bm=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let r=t.popovers.get(e);r&&(r.destroy(),t.popovers.delete(e))},Do=(t,e)=>{bm(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Qb=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Xb=(t,e)=>{var r,o;let n=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=Bo.get(t))!=null?o:n==="expanded"},Gi=t=>{let e=y("span","persona-approval-kbd");return e.textContent=t,e},Jb=(t,e)=>{var c,u;let n=y("span","persona-approval-title");e!=null&&e.titleColor&&(n.style.color=e.titleColor);let o=t.toolType==="webmcp"||t.toolName.startsWith(Ur)?Ps(t.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:t.toolName,toolType:t.toolType,description:(c=t.description)!=null?c:"",parameters:t.parameters,...o?{displayTitle:o}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ya(t.toolName),i=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let m=document.createElement("strong");m.textContent=i,n.appendChild(m)}return n},Yb=t=>{let e=y("div","persona-approval-resolved"),n=fe("ban",15,"currentColor",2);n&&e.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=t.toolName?Ya(t.toolName):"Tool",e.append(r,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Zb=(t,e,n,r,o,s,a)=>{var F,O,R,$,N,Z,Se;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",c=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",m=c||u,g=m&&Xb(e.id,r),f=(O=r==null?void 0:r.showDetailsLabel)!=null?O:"Show details",w=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",v=y("button","persona-approval-head");v.type="button",m?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",g?"true":"false"),v.setAttribute("aria-label",g?w:f)):v.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),W=fe("shield-check",16,"currentColor",2);W&&M.appendChild(W),v.appendChild(M);let T=Jb(n,r);if(m){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=fe("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),T.append(" "),T.appendChild(pe)}v.appendChild(T),i.appendChild(v);let k=y("div","persona-approval-body");if(m){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,c){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,pe.appendChild(ee)}if(u){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=co(n.parameters),pe.appendChild(ee)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${($=r==null?void 0:r.reasonLabel)!=null?$:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(n.reason)),k.appendChild(pe)}let E=y("div","persona-approval-actions"),P=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},L=y("button","persona-approval-deny");if(L.type="button",L.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(L.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(L.style.color=r.denyButtonTextColor),L.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let pe=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Gi("\u23CE"));let ve=y("button","persona-approval-caret");ve.type="button",ve.setAttribute("data-action","toggle-menu"),ve.setAttribute("aria-label","More options"),C(ve);let Ie=fe("chevron-down",15,"currentColor",2);Ie&&ve.appendChild(Ie),pe.append(ee,ve),E.append(pe,L),L.append(Gi("Esc"));let ce=y("div","persona-approval-menu"),ue=y("button","persona-approval-menu-item");ue.type="button",ue.append("Allow once",Gi("\u2318\u23CE")),ce.appendChild(ue),P=hm({anchor:pe,content:ce,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,P),ue.addEventListener("click",()=>{Do(t,e.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((Se=r==null?void 0:r.approveLabel)!=null?Se:"Allow"),E.append(pe,L)}return k.appendChild(E),i.appendChild(k),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let ve=ee.getAttribute("data-action");if(ve==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let ce=Ie.hidden;Ie.hidden=!ce,v.setAttribute("aria-expanded",ce?"true":"false"),v.setAttribute("aria-label",ce?w:f),Bo.set(e.id,ce)}return}if(ve==="toggle-menu"){P==null||P.toggle();return}if(ve==="always"){Do(t,e.id),o({remember:!0});return}if(ve==="allow"){Do(t,e.id),o();return}if(ve==="deny"){Do(t,e.id),s();return}}),i},vm=()=>{let t=Gb();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Qb(a);if(i.status!=="pending"){if(Do(t,r.id),i.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return Yb(i)}bm(t,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=Zb(t,r,i,d,o,s,c);if(c){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let m=g=>{ym(g)||r.id===t.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Do(t,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};t.keyHandlers.set(r.id,m),document.addEventListener("keydown",m)}return u}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Do(t,r);t.latestPendingApprovalId=null}}};var wm=t=>{let e=[],n=null;return{buttons:e,render:(o,s,a,i,d,c)=>{t.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(n=null),!o||!o.length||!u&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let m=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(w=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=w,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:w},bubbles:!0,composed:!0})),s.sendMessage(w))}),m.appendChild(v),e.push(v)}),t.appendChild(m),u){let w=JSON.stringify(o);w!==n&&(n=w,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ea=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){var n;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(n=this.store)==null||n.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ta=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var ev=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),tv=new Set(["step_start","execution_start"]),nv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),rv=new Set(["step_complete","agent_turn_complete"]),ov=new Set(["flow_complete","agent_complete"]),xm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Am=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Qn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,No=(t,e)=>{let n=t[e];return Am(n)?n:void 0};function Qi(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ei(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function sv(t,e){return typeof e.type=="string"?e.type:t}function av(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function iv(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Cm(t){var r,o,s,a,i;let e=No(t,"result"),n=[No(t,"tokens"),No(t,"totalTokens"),e?No(e,"tokens"):void 0,No(t,"usage"),e?No(e,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Qn(d.output))!=null?r:Qn(d.outputTokens))!=null?o:Qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Qn(t.outputTokens))!=null?s:Qn(t.completionTokens))!=null?i:e?(a=Qn(e.outputTokens))!=null?a:Qn(e.completionTokens):void 0}function lv(t){var n,r,o,s,a;let e=No(t,"result");return(a=(o=(r=(n=Qn(t.executionTime))!=null?n:Qn(t.executionTimeMs))!=null?r:Qn(t.execution_time))!=null?o:Qn(t.duration))!=null?a:e?(s=Qn(e.executionTime))!=null?s:Qn(e.executionTimeMs):void 0}function cv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var na=class{constructor(e=cv){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ei(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){var s;if(!Am(n)){xm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=sv(e,n),o=this.now();if(ev.has(r)){this.startRun(o);return}if(tv.has(r)){this.run||this.startRun(o);return}if(nv.has(r)){if(!iv(r,n))return;let a=av(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Qi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ei(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(rv.has(r)){if(!this.run)return;let a=this.run,i=Cm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Qi(a.visibleCharCount),u=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:ei(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(ov.has(r)){if(!this.run)return;let a=this.run,i=Cm(n),d=i!=null?i:a.exactOutputTokens+Qi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:ei(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(xm.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=lv(n);return s!=null?s:r-e.startedAt}};function ms(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var dv={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)"}},pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},uv=["flowName","stepName","reasoningText","text","name","tool","toolName"],mv=100;function gv(t,e){let n={...dv,...e};if(n[t])return n[t];for(let r of Object.keys(n))if(r.endsWith("_")&&t.startsWith(r))return n[r];return pv}function fv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function hv(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function yv(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let r of e){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function bv(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(n=>{let r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function vv(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function wv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function xv(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Cv(t,e,n){let r,o;try{o=JSON.parse(t.payload),r=JSON.stringify(o,null,2)}catch{o=t.payload,r=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=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]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Xi(t,e,n,r,o,s,a,i){var g;let d=o.has(t.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ms(c,(g=r.classNames)==null?void 0:g.eventRow);let u=a.find(f=>f.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let f=u.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return c.appendChild(f),c}return c.appendChild(m()),c;function m(){var N,Z;let f=y("div",""),w=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");w.setAttribute("data-event-id",t.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"),M=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let W=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(N=r.timestampFormat)!=null?N:"relative";W.textContent=T==="relative"?fv(t.timestamp,n):hv(t.timestamp);let k=null;r.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(e+1));let E=gv(t.type,r.badgeColors),P=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");P.style.backgroundColor=E.bg,P.style.color=E.text,P.style.borderColor=E.text+"50",P.textContent=t.type;let C=(Z=r.descriptionFields)!=null?Z:uv,L=yv(t.payload,C),F=null;L&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=L);let O=y("div","persona-flex-1 persona-min-w-0"),R=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"),$=fe("clipboard","12px","currentColor",1.5);return $&&R.appendChild($),R.addEventListener("click",async Se=>{Se.stopPropagation(),await bv(vv(t)),R.innerHTML="";let pe=fe("check","12px","currentColor",1.5);pe&&R.appendChild(pe),setTimeout(()=>{R.innerHTML="";let ee=fe("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),w.appendChild(v),w.appendChild(W),k&&w.appendChild(k),w.appendChild(P),F&&w.appendChild(F),w.appendChild(O),w.appendChild(R),f.appendChild(w),d&&f.appendChild(Cv(t,a,i)),f}}function Sm(t){var w,v,M,W,T;let{buffer:e,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=t,i=(w=o==null?void 0:o.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",m=(T=(W=o==null?void 0:o.features)==null?void 0:W.eventStream)!=null?T:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=m.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ms(E,k==null?void 0:k.panel);let P=[],C="",L="",F=null,O=[],R={},$=0,N=Da(),Z=0,Se=0,pe=!1,ee=null,ve=!1,Ie=0,ce=new Set,ue=new Map,oe="",se="",de=null,$e,Ne,V,G,be,X=null,le=null,Ee=null;function Xe(){let H=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),J=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");ms(J,k==null?void 0:k.headerBar);let Ae=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ae.textContent="Events",$e=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"),$e.textContent="0",a){le=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let _t=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_t.textContent="Throughput",X=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"),X.textContent="-- tok/s",Ee=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"),Ee.style.display="none",Ee.style.pointerEvents="none";let Nn=le,Sn=Ee,Tn=()=>{if(!Sn.textContent)return;let En=Nn.getBoundingClientRect(),ar=H.getBoundingClientRect();Sn.style.left=`${En.left-ar.left}px`,Sn.style.top=`${En.bottom-ar.top+4}px`,Sn.style.display="block"},bn=()=>{Sn.style.display="none"};le.addEventListener("mouseenter",Tn),le.addEventListener("mouseleave",bn),le.appendChild(_t),le.appendChild(X)}let it=y("div","persona-flex-1");Ne=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 Qe=y("option","");Qe.value="",Qe.textContent="All events",Ne.appendChild(Qe),V=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"),V.type="button",V.title="Copy All";let fn=fe("clipboard-copy","12px","currentColor",1.5);fn&&V.appendChild(fn);let vt=y("span","persona-text-xs");vt.textContent="Copy All",V.appendChild(vt),J.appendChild(Ae),J.appendChild($e),le&&J.appendChild(le),J.appendChild(it),J.appendChild(Ne),J.appendChild(V);let wt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ms(wt,k==null?void 0:k.searchBar);let It=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),Ct=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");It&&Ct.appendChild(It),G=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"),ms(G,k==null?void 0:k.searchInput),G.type="text",G.placeholder="Search event payloads...",be=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"),be.type="button",be.style.display="none";let ln=fe("x","12px","currentColor",2);return ln&&be.appendChild(ln),wt.appendChild(Ct),wt.appendChild(G),wt.appendChild(be),H.appendChild(J),H.appendChild(wt),Ee&&H.appendChild(Ee),H}let Ze,xt=s.find(H=>H.renderEventStreamToolbar);if(xt!=null&&xt.renderEventStreamToolbar&&o){let H=xt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Xe(),eventCount:e.getSize(),filteredCount:0,onFilterChange:J=>{C=J,Oe(),Xt()},onSearchChange:J=>{L=J,Oe(),Xt()}});Ze=H!=null?H:Xe()}else Ze=Xe();let dt=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");dt.style.display="none";function Ye(){if(!a||!X||!le)return;let H=a();X.textContent=wv(H);let J=xv(H);Ee&&(Ee.textContent=J,J||(Ee.style.display="none")),J?le.setAttribute("aria-label",J):le.removeAttribute("aria-label")}let He=y("div","persona-flex-1 persona-min-h-0 persona-relative"),K=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");K.style.height="100%";let qe=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");ms(qe,k==null?void 0:k.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let ze=fe(c,"14px","currentColor",2);ze&&qe.appendChild(ze);let we=y("span","");we.textContent=u,qe.appendChild(we);let Ce=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",He.appendChild(K),He.appendChild(Ce),He.appendChild(qe),E.setAttribute("tabindex","0"),E.appendChild(Ze),E.appendChild(dt),E.appendChild(He);function tt(){let H=e.getAll(),J={};for(let vt of H)J[vt.type]=(J[vt.type]||0)+1;let Ae=Object.keys(J).sort(),it=Ae.length!==O.length||!Ae.every((vt,wt)=>vt===O[wt]),Qe=!it&&Ae.some(vt=>J[vt]!==R[vt]),Ut=H.length!==Object.values(R).reduce((vt,wt)=>vt+wt,0);if(!it&&!Qe&&!Ut||(O=Ae,R=J,!Ne))return;let fn=Ne.value;if(Ne.options[0].textContent="All events",it){for(;Ne.options.length>1;)Ne.remove(1);for(let vt of Ae){let wt=y("option","");wt.value=vt,wt.textContent=`${vt} (${J[vt]||0})`,Ne.appendChild(wt)}fn&&Ae.includes(fn)?Ne.value=fn:fn&&(Ne.value="",C="")}else for(let vt=1;vt<Ne.options.length;vt++){let wt=Ne.options[vt];wt.textContent=`${wt.value} (${J[wt.value]||0})`}}function Ot(){let H=e.getAll();if(C&&(H=H.filter(J=>J.type===C)),L){let J=L.toLowerCase();H=H.filter(Ae=>Ae.type.toLowerCase().includes(J)||Ae.payload.toLowerCase().includes(J))}return H}function ne(){return C!==""||L!==""}function Oe(){$=0,Z=0,N.resume(),qe.style.display="none"}function gn(H){ce.has(H)?ce.delete(H):ce.add(H),de=H;let J=K.scrollTop,Ae=N.isFollowing();ve=!0,N.pause(),Xt(),K.scrollTop=J,Ae&&N.resume(),ve=!1}function Bt(){return Ro(K,50)}function Xt(){Se=Date.now(),pe=!1,Ye(),tt();let H=e.getEvictedCount();H>0?(dt.textContent=`${H.toLocaleString()} older events truncated`,dt.style.display=""):dt.style.display="none",P=Ot();let J=P.length,Ae=e.getSize()>0;$e&&($e.textContent=String(e.getSize())),J===0&&Ae&&ne()?(Ce.textContent=L?`No events matching '${L}'`:"No events matching filter",Ce.style.display="",K.style.display="none"):(Ce.style.display="none",K.style.display=""),V&&(V.title=ne()?`Copy Filtered (${J})`:"Copy All"),d&&!N.isFollowing()&&J>$&&(Z+=J-$,we.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",qe.style.display=""),$=J;let it=e.getAll(),Qe=it.length>0?it[0].timestamp:0,Ut=new Set(P.map(wt=>wt.id));for(let wt of ce)Ut.has(wt)||ce.delete(wt);let fn=C!==oe||L!==se,vt=ue.size===0&&P.length>0;if(fn||vt||P.length===0){K.innerHTML="",ue.clear();let wt=document.createDocumentFragment();for(let It=0;It<P.length;It++){let Ct=Xi(P[It],It,Qe,m,ce,gn,s,o);ue.set(P[It].id,Ct),wt.appendChild(Ct)}K.appendChild(wt),oe=C,se=L,de=null}else{if(de!==null){let It=ue.get(de);if(It&&It.parentNode===K){let Ct=P.findIndex(ln=>ln.id===de);if(Ct>=0){let ln=Xi(P[Ct],Ct,Qe,m,ce,gn,s,o);K.insertBefore(ln,It),It.remove(),ue.set(de,ln)}}de=null}let wt=new Set(P.map(It=>It.id));for(let[It,Ct]of ue)wt.has(It)||(Ct.remove(),ue.delete(It));for(let It=0;It<P.length;It++){let Ct=P[It];if(!ue.has(Ct.id)){let ln=Xi(Ct,It,Qe,m,ce,gn,s,o);ue.set(Ct.id,ln),K.appendChild(ln)}}}N.isFollowing()&&(K.scrollTop=K.scrollHeight)}function Ir(){if(Date.now()-Se>=mv){ee!==null&&(cancelAnimationFrame(ee),ee=null),Xt();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,Xt()}))}let hr=(H,J)=>{if(!V)return;V.innerHTML="";let Ae=fe(H,"12px","currentColor",1.5);Ae&&V.appendChild(Ae);let it=y("span","persona-text-xs");it.textContent="Copy All",V.appendChild(it),setTimeout(()=>{V.innerHTML="";let Qe=fe("clipboard-copy","12px","currentColor",1.5);Qe&&V.appendChild(Qe);let Ut=y("span","persona-text-xs");Ut.textContent="Copy All",V.appendChild(Ut),V.disabled=!1},J)},A=async()=>{if(V){V.disabled=!0;try{let H;ne()?H=P:n?(H=await n(),H.length===0&&(H=e.getAll())):H=e.getAll();let J=H.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),hr("check",1500)}catch{hr("x",1500)}}},te=()=>{Ne&&(C=Ne.value,Oe(),Xt())},Te=()=>{!G||!be||(be.style.display=G.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{L=G.value,Oe(),Xt()},150))},Re=()=>{!G||!be||(G.value="",L="",be.style.display="none",F&&clearTimeout(F),Oe(),Xt())},ke=()=>{if(ve)return;let H=K.scrollTop,{action:J,nextLastScrollTop:Ae}=Na({following:N.isFollowing(),currentScrollTop:H,lastScrollTop:Ie,nearBottom:Bt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=Ae,J==="resume"?(N.resume(),Z=0,qe.style.display="none"):J==="pause"&&(N.pause(),d&&(we.textContent=u,qe.style.display=""))},Be=H=>{let J=Fa({following:N.isFollowing(),deltaY:H.deltaY,nearBottom:Bt(),resumeWhenNearBottom:!0});J==="pause"?(N.pause(),d&&(we.textContent=u,qe.style.display="")):J==="resume"&&(N.resume(),Z=0,qe.style.display="none")},Ve=()=>{d&&(K.scrollTop=K.scrollHeight,N.resume(),Z=0,qe.style.display="none")},at=H=>{let J=H.target;if(!J||J.closest("button"))return;let Ae=J.closest("[data-event-id]");if(!Ae)return;let it=Ae.getAttribute("data-event-id");it&&gn(it)},Pt=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),G==null||G.focus(),G==null||G.select();return}H.key==="Escape"&&(G&&document.activeElement===G?(Re(),G.blur(),E.focus()):r&&r())};V&&V.addEventListener("click",A),Ne&&Ne.addEventListener("change",te),G&&G.addEventListener("input",Te),be&&be.addEventListener("click",Re),K.addEventListener("scroll",ke),K.addEventListener("wheel",Be,{passive:!0}),K.addEventListener("click",at),qe.addEventListener("click",Ve),E.addEventListener("keydown",Pt);function bt(){F&&clearTimeout(F),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,ue.clear(),V&&V.removeEventListener("click",A),Ne&&Ne.removeEventListener("change",te),G&&G.removeEventListener("input",Te),be&&be.removeEventListener("click",Re),K.removeEventListener("scroll",ke),K.removeEventListener("wheel",Be),K.removeEventListener("click",at),qe.removeEventListener("click",Ve),E.removeEventListener("keydown",Pt)}return{element:E,update:Ir,destroy:bt}}}function Tm(t,e){let n=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(c.append(u,m),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Em=(t,e)=>{var r,o,s;let n=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",c=typeof t.artifactType=="string"?t.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Tm(t,e)});if(u)return u}return Tm(t,e)};var Ji=class{constructor(){this.components=new Map}register(e,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([n,r])=>{this.register(n,r)})}},Fo=new Ji;Fo.register("PersonaArtifactCard",Em);function Av(t){var o;let e=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=t.component?`Component: ${t.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(n),e.appendChild(r),e}function Mm(t,e){var Ne,V,G,be;let n=(V=(Ne=t.features)==null?void 0:Ne.artifacts)==null?void 0:V.layout,o=((G=n==null?void 0:n.toolbarPreset)!=null?G:"default")==="document",s=(be=n==null?void 0:n.panePadding)==null?void 0:be.trim(),a=t.markdown?ga(t.markdown):null,i=fa(t.sanitize),d=X=>{let le=a?a(X):ao(X);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let w=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let v="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=o?An({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):An({icon:"eye",label:"Rendered view"}),T=o?An({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):An({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,L=!!(P&&C&&C.length>0),F=null,O,R=null,$=null;if(o&&(E||P)&&!L){if(O=E?Oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):An({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let X=fe("chevron-down",14,"currentColor",2);X&&O.appendChild(X)}}else o&&L?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),O=E?Oi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):An({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=An({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"}}),F.append(O,R)):o?O=An({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):O=An({icon:"copy",label:"Copy"});let N=o?An({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):An({icon:"refresh-cw",label:"Refresh"}),Z=o?An({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):An({icon:"x",label:"Close"}),Se=()=>{var Ze,xt,dt;let X=(Ze=ue.find(Ye=>Ye.id===oe))!=null?Ze:ue[ue.length-1],le=(xt=X==null?void 0:X.id)!=null?xt:null,Ee=(X==null?void 0:X.artifactType)==="markdown"&&(dt=X.markdown)!=null?dt:"",Xe=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:Ee,jsonPayload:Xe,id:le}},pe=async()=>{var Ze;let{markdown:X,jsonPayload:le}=Se(),Ee=(Ze=ue.find(xt=>xt.id===oe))!=null?Ze:ue[ue.length-1],Xe=(Ee==null?void 0:Ee.artifactType)==="markdown"?X:Ee?le:"";try{await navigator.clipboard.writeText(Xe)}catch{}};if(O.addEventListener("click",async()=>{let X=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(X&&L){let{markdown:le,jsonPayload:Ee,id:Xe}=Se();try{await X({actionId:"primary",artifactId:Xe,markdown:le,jsonPayload:Ee})}catch{}return}await pe()}),R&&(C!=null&&C.length)){let X=()=>{var Ee;return(Ee=m.closest("[data-persona-root]"))!=null?Ee:document.body},le=()=>{$=ds({items:C.map(Ee=>({id:Ee.id,label:Ee.label})),onSelect:async Ee=>{let{markdown:Xe,jsonPayload:Ze,id:xt}=Se(),dt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{dt?await dt({actionId:Ee,artifactId:xt,markdown:Xe,jsonPayload:Ze}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Xe):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(Ze):await navigator.clipboard.writeText(Xe||Ze)}catch{}},anchor:F!=null?F:R,position:"bottom-right",portal:X()})};m.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Ee=>{Ee.stopPropagation(),$==null||$.toggle()})}N.addEventListener("click",async()=>{var X;try{await((X=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:X.call(n))}catch{}de()}),Z.addEventListener("click",()=>{var X;u(),(X=e.onDismiss)==null||X.call(e)});let ee=()=>{o&&(W.setAttribute("aria-pressed",v==="rendered"?"true":"false"),T.setAttribute("aria-pressed",v==="source"?"true":"false"))};W.addEventListener("click",()=>{v="rendered",ee(),de()}),T.addEventListener("click",()=>{v="source",ee(),de()});let ve=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");o?(g.replaceChildren(),M.append(W,T),F?k.append(F,N,Z):k.append(O,N,Z),g.append(M,ve,k),ee()):(g.appendChild(f),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Ie=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"),ce=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,ce.style.padding=s),m.appendChild(g),m.appendChild(Ie),m.appendChild(ce);let ue=[],oe=null,se=!1,de=()=>{var Xe,Ze,xt,dt;let X=o&&ue.length<=1;Ie.classList.toggle("persona-hidden",X),Ie.replaceChildren();for(let Ye of ue){let He=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");He.type="button",He.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===oe&&He.classList.add("persona-bg-persona-container","persona-border-persona-border"),He.addEventListener("click",()=>e.onSelect(Ye.id)),Ie.appendChild(He)}ce.replaceChildren();let le=oe&&ue.find(Ye=>Ye.id===oe)||ue[ue.length-1];if(!le)return;if(o){let Ye=le.artifactType==="markdown"?"MD":(Xe=le.component)!=null?Xe:"Component",K=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ve.textContent=`${K} \xB7 ${Ye}`}else f.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let He=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");He.textContent=(Ze=le.markdown)!=null?Ze:"",ce.appendChild(He);return}let Ye=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=d((xt=le.markdown)!=null?xt:""),ce.appendChild(Ye);return}let Ee=le.component?Fo.get(le.component):void 0;if(Ee){let He={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let K=Ee((dt=le.props)!=null?dt:{},He);if(K){ce.appendChild(K);return}}catch{}}ce.appendChild(Av(le))},$e=()=>{var le;let X=ue.length>0;if(m.classList.toggle("persona-hidden",!X),c){let Ee=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,Ze=((le=Ee==null?void 0:Ee.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;X&&Ze&&se?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(X){var le,Ee,Xe;ue=X.artifacts,oe=(Xe=(Ee=X.selectedId)!=null?Ee:(le=X.artifacts[X.artifacts.length-1])==null?void 0:le.id)!=null?Xe:null,ue.length>0&&(se=!0),de(),$e()},setMobileOpen(X){se=X,!X&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):$e()}}}function sr(t){var e,n;return((n=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:n.enabled)===!0}function km(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!sr(e))return;let n=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",r)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Sv(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(t,e){var d,c,u,m,g,f,w,v,M,W;if(!sr(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Sv(t),km(t,e);return}let n=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;t.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let o=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(W=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:W.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),km(t,e)}var Lm=["panel","seamless"];function ni(t,e){var i,d,c,u,m,g;for(let f of Lm)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!sr(e))return;let n=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Lm.includes(r)?r:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Pm(t,e){var n,r,o;return!e||!sr(t)?!1:((o=(r=(n=t.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Tv(t,e){if(!(t!=null&&t.trim()))return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Ev(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Mv(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function kv(t,e,n,r){let o=t-r-2*e-n;return Math.max(0,o)}function Im(t,e){var a;let r=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Wm(t,e,n,r,o,s){let a=Tv(o,200),i=kv(e,n,r,200);i=Math.max(a,i);let d=Ev(s);return d!==null&&(i=Math.min(i,d)),Mv(t,a,i)}var Rm={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"}},Yi=(t,e,n,r)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,v,M;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(v=Rm[a])!=null?v:Rm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let W=y("p","persona-text-sm persona-text-persona-muted");W.textContent=i.description,d.appendChild(W)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(W=>{var C,L;let T=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${W.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=W.label,T.appendChild(k);let E=(C=W.type)!=null?C:"text",P;E==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=E),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${e.id}-${a}-${W.name}`,P.name=W.name,P.placeholder=(L=W.placeholder)!=null?L:"",W.required&&(P.required=!0),T.appendChild(P),u.appendChild(T)});let m=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(M=i.submitLabel)!=null?M:"Submit",m.appendChild(g),m.appendChild(f),u.appendChild(m),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var P,C;W.preventDefault();let T=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(u),E={};k.forEach((L,F)=>{E[F]=L}),E.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let L=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let F=await L.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(L){g.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Zi=class{constructor(){this.plugins=new Map}register(e){var n;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(n=e.onRegister)==null||n.call(e)}unregister(e){var r;let n=this.plugins.get(e);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let r=new Set(e.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var n;return(n=e.onUnregister)==null?void 0:n.call(e)}),this.plugins.clear()}},el=new Zi;var Hm=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:n,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Lv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Pv=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(n,o+1)}return null},nl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Lv(t),n=Pv(e);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},tl=t=>typeof t=="string"?t:t==null?"":String(t),ra={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:tl(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let n=t.payload,r=tl(n.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:tl(n.text)}}},Bm=t=>Array.isArray(t)?t.map(e=>String(e)):[],rl=t=>{let e=new Set(Bm(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Bm(t.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};t.emit("action:detected",d);for(let c of t.handlers)if(c)try{let u=()=>{t.emit("action:resubmit",d)},m=c(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Iv=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Wv=t=>t.map(e=>({...e,streaming:!1})),Rv=t=>t.map(e=>({...e,status:"complete"})),Dm=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Iv(n.getItem(t)):null},save:n=>{let r=e();if(r)try{let o={...n,messages:n.messages?Wv(n.messages):void 0,artifacts:n.artifacts?Rv(n.artifacts):void 0};r.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as YA,STR as ZA,OBJ as eS}from"partial-json";function Nm(t,e){let{config:n,message:r,onPropsUpdate:o}=e,s=Fo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Fm(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Om(t){let e=Fm(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function _m(t){let e=Fm(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var Hv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function $m(t){let{onSubmit:e,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Hv}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,f.appendChild(w);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,f.appendChild(v),g.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let C=1;C<=5;C++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),L.title=c[C-1],L.dataset.rating=String(C),L.innerHTML=`
|