@runtypelabs/persona 4.6.0 → 4.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-8RICZWQe.d.cts → types-CSmiKRVa.d.cts} +5 -0
- package/dist/animations/{types-8RICZWQe.d.ts → types-CSmiKRVa.d.ts} +5 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -1
- package/dist/index.d.ts +10 -1
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +5 -0
- package/dist/smart-dom-reader.d.ts +5 -0
- package/dist/theme-editor-preview.cjs +2 -2
- package/dist/theme-editor-preview.d.cts +5 -0
- package/dist/theme-editor-preview.d.ts +5 -0
- package/dist/theme-editor-preview.js +2 -2
- package/dist/theme-editor.d.cts +5 -0
- package/dist/theme-editor.d.ts +5 -0
- package/package.json +4 -2
- package/src/client.ts +7 -2
- package/src/generated/runtype-openapi-contract.ts +10 -1
- package/src/utils/morph.test.ts +47 -0
- package/src/utils/morph.ts +18 -0
package/dist/index.js
CHANGED
|
@@ -8,14 +8,14 @@ ${t}`:"")+(e.description?`
|
|
|
8
8
|
${e.description}`:"");return window.confirm(n)},Eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Mh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},kh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Lh="agent_",Ph="flow_";function lm(e){return e.startsWith(Lh)?{kind:"agentId",agentId:e}:e.startsWith(Ph)?{kind:"flowId",flowId:e}:null}function cm(e,t){let n=e.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=lm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[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=lm(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Ih,ARR as Rh,OBJ as Wh,STR as Hh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.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},Zs=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",ea=8,ws="data-persona-ask-sheet-for",Bh="Other",Dh="Other\u2026",pm="Type your own answer here",um="Send",Nh="Next",Oh="Back",Fh="Submit all",_h="Skip",$h=3,Xi="data-ask-current-index",Qi="data-ask-question-count",mm="data-ask-answers",Yi="data-ask-grouped",gm="data-ask-layout",jh=e=>e.layout==="pills"?"pills":"rows",Uh=e=>e.getAttribute(gm)==="pills"?"pills":"rows",dm=!1,fm=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},bo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Ih(o,Hh|Wh|Rh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ta=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!dm&&(dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},qh=e=>{var t;return(t=ta(e)[0])!=null?t:null},zh=(e,t)=>{var n;return(n=ta(e)[t])!=null?n:null},hm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ym=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){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},Vh=(e,t,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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=ym(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Kh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Gh=(e,t,n,r)=>{var p,u,f;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=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<$h;g++)s.appendChild(Kh(r));return s}if(d.forEach((g,b)=>{s.appendChild(Vh(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Bh:Dh;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=t.freeTextPlaceholder)!=null?p:pm,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(S),b.appendChild(v);let T=ym(r,a,d.length);T&&b.appendChild(T),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},bm=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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=e.freeTextPlaceholder)!=null?s:pm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:um,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Jh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Xh=(e,t,n)=>{var c,p,u,f;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:Oh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===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=(p=n.skipLabel)!=null?p:_h,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=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Fh:(f=n.nextLabel)!=null?f:Nh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(mm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(mm,JSON.stringify(t))},er=e=>{var n;let t=Number((n=e.getAttribute(Xi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Qh=(e,t)=>{e.setAttribute(Xi,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(Qi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(Yi)==="true",Yh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.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},Zh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=bo(t),r=ta(n),o=Go(e),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},vm=e=>{let t=Go(e),n=er(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.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=""},wm=e=>{if(!xo(e))return;let t=Go(e),n=er(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Zi=(e,t,n)=>{let r=Da(n),o=Uh(e),{payload:s,complete:a}=bo(t),i=xo(e),d=er(e),c=Cs(e),p=i?zh(s,d):qh(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=L,b.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=Gh(p,r,a,o);v.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(bm(r,o))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?e.appendChild(Jh(r)):(!u||i)&&S&&S.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Xh(d,c,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();vm(e),wm(e)},ey=(e,t,n)=>{let r=Da(t),o=jh(r),s=e.toolCall.id,a=ta(n),i=Math.max(1,a.length),d=i>1,c=Yh(e,a),p=d?Zh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Qi,String(i)),u.setAttribute(Xi,String(p)),u.setAttribute(Yi,d?"true":"false"),u.setAttribute(gm,o),xm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),hm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let S=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),u.appendChild(S),o!=="rows"&&u.appendChild(bm(r,o)),Zi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ty=(e,t,n)=>{let{payload:r}=bo(t),o=Math.max(1,ta(r).length);o>Cs(e)&&(e.setAttribute(Qi,String(o)),o>1&&!xo(e)&&e.setAttribute(Yi,"true")),Zi(e,t,n)},ny=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Da(t);hm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=bo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},na=(e,t,n)=>{if(!n||!yo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(c=>{c.getAttribute(ws)!==o&&c.remove()});let a=n.querySelector(`[${ws}="${fm(o)}"]`);if(a){ty(a,e,t);return}let{payload:i}=bo(e),d=ey(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${fm(t)}"]`:`[${ws}]`;e.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)})},el=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),vo=(e,t)=>{let n=Go(e),r=er(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,xm(e,n),vm(e),wm(e)},Oa=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Qh(e,s),Zi(e,t,n)};var Hr="suggest_replies";var Cm={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},tl={name:Hr,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:Cm,origin:"sdk",annotations:{readOnlyHint:!0}},nl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Am=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.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},rl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=Am((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Sm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Tm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,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},Em={name:Ba,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:Tm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Em),Sm(e)&&t.push(tl),t};import{parse as Mm,STR as km,OBJ as Lm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},ry=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Pm=e=>e.status==="complete"?ry(e):e.status==="pending"?"Waiting":"",oy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.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 Im=e=>e.status==="complete"?oy(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},oa=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},Ua=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},ol=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=oa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ra(r,n.slice(s,a.index),[]),a[1]!==void 0?ra(r,a[1],["bold"]):a[2]!==void 0?ra(r,a[2],["italic"]):a[3]!==void 0&&ra(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ra(r,n.slice(s),[]),r},ra=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},sy=()=>{let e=null,t=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:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},al=()=>{var t;let e=sy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},il=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Mm(n,km|Lm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ay=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Mm(s,km|Lm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ll=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Rm="4.6.0";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.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 cl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(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(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,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=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((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},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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$/,""))||za}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},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(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.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(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.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(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.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(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.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(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/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:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!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(t){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=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f: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=[..._a(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 p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u: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=[..._a(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 p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),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(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);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 p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}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(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},al=()=>{var t;let e=sy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},il=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Mm(n,km|Lm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ay=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Mm(s,km|Lm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ll=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Rm="4.6.1";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.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 cl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(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(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,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=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((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},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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$/,""))||za}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},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(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.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(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.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(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.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(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.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(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/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:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!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(t){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=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f: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=[..._a(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 p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u: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=[..._a(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 p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),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(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);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 p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}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(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
|
|
12
12
|
|
|
13
13
|
`);i=(yr=Te.pop())!=null?yr:"";for(let ke of Te){let He=ke.split(`
|
|
14
14
|
`),nt="message",Qe="",ht=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Qe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(ht=ce.slice(3).trim());let me=()=>{ht!==null&&ht!==""&&n({type:"cursor",id:ht})};if(!Qe){me();continue}let B;try{B=JSON.parse(Qe)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let xe=nt!=="message"?nt:(br=B.type)!=null?br:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,xe,B),this.parseSSEEvent){S.current=b;let ce=await this.handleCustomSSEEvent(B,n,S,g,p,T);if(S.current&&S.current!==b&&(b=S.current),ce){me();continue}}it.push({payloadType:xe,payload:B}),Ve(),me()}}Ve()}};function uy(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function my(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gy(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function yy(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function by(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xy(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vy=["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"],Gr=[...Hm,...vy];function wy(e){return Hm.includes(e)||e.startsWith("image/")}function Ga(e){return wy(e.type)}async function Bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dm(e,t=Gr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Cy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nm(e,t){let n=Cy(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}dl();var Om=16e3,Ay=24e3,Sy=4096,Ty=1380533830;function Ey(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Ty?new Uint8Array(e,44):new Uint8Array(e)}function My(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ia=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(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(!t)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:Om,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Om});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ss(Ay);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${My(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let S=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Sy,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 p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Ey(t);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(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,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=((t=this.config)==null?void 0:t.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(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Yo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ia(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function pl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Yo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Yo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return pl(e),!0}catch{return!1}}function la(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Zo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.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(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):la(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ts=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"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(t,"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 t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function ul(e){if(!e)return"";let t=ky(e);return Fm(t!==null?t:e)}function ky(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Fm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),t=t.replace(/\n{2,}/g,`
|
|
16
16
|
`),t.trim()}var qm=null;var ml=()=>qm?qm():Promise.resolve().then(()=>(Um(),jm));var Wy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Hy(e,t){return Wy.some(n=>e[n]!==t[n])}function gl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let 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
|
-
_Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),Km=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gm=e=>Ko(e)||e===Hr,da=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ts(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ko(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.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 As(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.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||ml().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Zo.isSupported()?new Zo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.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,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return ml().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(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 p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.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(t){console.error("Failed to start voice:",t)}}}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,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Hy(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 As(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?aa():n==="assistant"?Xo():`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},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?aa():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,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(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=aa(),s=Xo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Va,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(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let S=gl(b,this.config.errorMessage);if(S){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Xo();this.activeAssistantMessageId=null,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:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=gl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(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(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,S,T,L,P,E,k;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,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=t.toolCall)==null?void 0:v.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let j=typeof((S=I[0])==null?void 0:S.question)=="string"?I[0].question:"";j&&(a={[j]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.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(([I,j])=>`${I}: ${Array.isArray(j)?j.join(", "):j}`).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((I,j)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let R=C[$],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${j}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${j}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(k=(E=this.callbacks).onError)==null||k.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var k,C,I,j,$,R,N;let g=(k=f.toolCall)==null?void 0:k.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),T=(j=(I=f.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?j:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:nl(),toolMessage:f,startedAt:S,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let P=this.client.executeWebMcpToolCall(g,($=f.toolCall)==null?void 0:$.args,L.signal),E;if(!P)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await P}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(N=(R=this.callbacks).onError)==null||N.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(f,ca(Z?"Aborted by cancel()":Km(O)),S),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ca("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:E,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,ca("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,S,T,L,P,E,k,C,I,j,$;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,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(N){(E=(P=this.callbacks).onError)==null||E.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Hr,p=(k=t.toolCall)==null?void 0:k.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let R;if(c?R=nl():u?R=await u:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),a);return}let N=(I=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;f="resume",await this.resumeWithToolOutput(n,N,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,R,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let N=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||N||d.aborted)&&this.markWebMcpToolComplete(t,ca(N||d.aborted?"Aborted by cancel()":Km(R)),a),N||($=(j=this.callbacks).onError)==null||$.call(j,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(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.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 t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.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(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Vm(),zm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>gl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=ul(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=ul(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let $=o.approval,R=n.approval;a.approval={...$,...R,executionId:R.executionId||$.executionId,toolName:R.toolName||$.toolName,description:R.description||$.description,toolType:(g=R.toolType)!=null?g:$.toolType,reason:(b=R.reason)!=null?b:$.reason,parameters:(v=R.parameters)!=null?v:$.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&Gm(i)&&d&&c&&((P=n.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let $=`${d}:${c}`,R=this.webMcpInflightKeys.has($),N=this.webMcpResolvedKeys.has($),O=(E=o.toolCall)==null?void 0:E.name,Z=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&O!==void 0&&Gm(O)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(R||N||Z)&&(a.agentMetadata={...(j=a.agentMetadata)!=null?j:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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 By,ArrowDown as Dy,ArrowUp as Ny,ArrowUpRight as Oy,Bot as Fy,ChevronDown as _y,ChevronUp as $y,ChevronRight as jy,ChevronLeft as Uy,Check as qy,Clipboard as zy,ClipboardCopy as Vy,Copy as Ky,File as Gy,FileCode as Jy,FileSpreadsheet as Xy,FileText as Qy,ImagePlus as Yy,Loader as Zy,LoaderCircle as eb,Mic as tb,Paperclip as nb,RefreshCw as rb,Search as ob,Send as sb,ShieldAlert as ab,ShieldCheck as ib,ShieldX as lb,Square as cb,ThumbsDown as db,ThumbsUp as pb,Upload as ub,Volume2 as mb,X as gb,User as fb,Mail as hb,Phone as yb,Calendar as bb,Clock as xb,Building as vb,MapPin as wb,Lock as Cb,Key as Ab,CreditCard as Sb,AtSign as Tb,Hash as Eb,Globe as Mb,Link as kb,CircleCheck as Lb,CircleX as Pb,TriangleAlert as Ib,Info as Rb,Ban as Wb,Shield as Hb,ArrowLeft as Bb,ArrowRight as Db,ExternalLink as Nb,Ellipsis as Ob,EllipsisVertical as Fb,Menu as _b,House as $b,Plus as jb,Minus as Ub,Pencil as qb,Trash as zb,Trash2 as Vb,Save as Kb,Download as Gb,Share as Jb,Funnel as Xb,Settings as Qb,RotateCw as Yb,Maximize as Zb,Minimize as ex,ShoppingCart as tx,ShoppingBag as nx,Package as rx,Truck as ox,Tag as sx,Gift as ax,Receipt as ix,Wallet as lx,Store as cx,DollarSign as dx,Percent as px,Play as ux,Pause as mx,VolumeX as gx,Camera as fx,Image as hx,Film as yx,Headphones as bx,MessageCircle as xx,MessageSquare as vx,Bell as wx,Heart as Cx,Star as Ax,Eye as Sx,EyeOff as Tx,Bookmark as Ex,CalendarDays as Mx,History as kx,Timer as Lx,Folder as Px,FolderOpen as Ix,Files as Rx,Sparkles as Wx,Zap as Hx,Sun as Bx,Moon as Dx,Flag as Nx,Monitor as Ox,Smartphone as Fx}from"lucide";var _x={activity:By,"arrow-down":Dy,"arrow-up":Ny,"arrow-up-right":Oy,bot:Fy,"chevron-down":_y,"chevron-up":$y,"chevron-right":jy,"chevron-left":Uy,check:qy,clipboard:zy,"clipboard-copy":Vy,copy:Ky,file:Gy,"file-code":Jy,"file-spreadsheet":Xy,"file-text":Qy,"image-plus":Yy,loader:Zy,"loader-circle":eb,mic:tb,paperclip:nb,"refresh-cw":rb,search:ob,send:sb,"shield-alert":ab,"shield-check":ib,"shield-x":lb,square:cb,"thumbs-down":db,"thumbs-up":pb,upload:ub,"volume-2":mb,x:gb,user:fb,mail:hb,phone:yb,calendar:bb,clock:xb,building:vb,"map-pin":wb,lock:Cb,key:Ab,"credit-card":Sb,"at-sign":Tb,hash:Eb,globe:Mb,link:kb,"circle-check":Lb,"circle-x":Pb,"triangle-alert":Ib,info:Rb,ban:Wb,shield:Hb,"arrow-left":Bb,"arrow-right":Db,"external-link":Nb,ellipsis:Ob,"ellipsis-vertical":Fb,menu:_b,house:$b,plus:jb,minus:Ub,pencil:qb,trash:zb,"trash-2":Vb,save:Kb,download:Gb,share:Jb,funnel:Xb,settings:Qb,"rotate-cw":Yb,maximize:Zb,minimize:ex,"shopping-cart":tx,"shopping-bag":nx,package:rx,truck:ox,tag:sx,gift:ax,receipt:ix,wallet:lx,store:cx,"dollar-sign":dx,percent:px,play:ux,pause:mx,"volume-x":gx,camera:fx,image:hx,film:yx,headphones:bx,"message-circle":xx,"message-square":vx,bell:wx,heart:Cx,star:Ax,eye:Sx,"eye-off":Tx,bookmark:Ex,"calendar-days":Mx,history:kx,timer:Lx,folder:Px,"folder-open":Ix,files:Rx,sparkles:Wx,zap:Hx,sun:Bx,moon:Dx,flag:Nx,monitor:Ox,smartphone:Fx},ye=(e,t=24,n="currentColor",r=2)=>{let o=_x[e];return o?$x(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function $x(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),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"),e.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,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ux(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Es=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ya.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Dm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Bm(c),f=Ga(c)?URL.createObjectURL(c):null,g={id:jx(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);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="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",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=Ux(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Nm(t.file.type,t.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=ye("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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Jm(s)&&Jm(o)?n[r]=pa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",fl="440px",qx={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:tr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:qx,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xm(e,t){if(!(!e&&!t))return e?t?pa(e,t):e:t}function hl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k;return e?{...Dt,...e,theme:Xm(Dt.theme,e.theme),darkTheme:Xm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let C=(re=Dt.features)==null?void 0:re.artifacts,I=(se=e.features)==null?void 0:se.artifacts,j=(ae=Dt.features)==null?void 0:ae.scrollToBottom,$=(fe=e.features)==null?void 0:fe.scrollToBottom,R=($e=Dt.features)==null?void 0:$e.scrollBehavior,N=(V=e.features)==null?void 0:V.scrollBehavior,O=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Le=j===void 0&&$===void 0?void 0:{...j,...$},Pe=R===void 0&&N===void 0?void 0:{...R,...N},ne=O===void 0&&Z===void 0?void 0:{...O,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Dt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(T=(S=e.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(E=Dt.markdown)==null?void 0:E.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var Qm={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ym={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Zm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},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:tr,maxWidth:fl,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 Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;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."))?Ms(e,r):r}function yl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[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(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function tg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=tg(s,o):n[r]=o}return n}function zx(e,t){return t?tg(e,t):e}function ua(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,S;let n={palette:Qm,semantic:Ym,components:Zm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:zx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=eg(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function bl(e){var v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,vn,Ct,fn,yr,br,Ue,M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro;let t=yl(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P: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"]=(k=n["--persona-semantic-colors-text"])!=null?k: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"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(j=n["--persona-semantic-colors-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$: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=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O: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"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de: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"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re: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"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(vn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?vn:"0.5rem",n["--persona-message-user-radius"]=(fn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te: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"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(xr=n["--persona-components-message-assistant-shadow"])!=null?xr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Xr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Xr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Qr=n["--persona-components-scrollToBottom-gap"])!=null?Qr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Yr=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(wr=n["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Cr=n["--persona-components-reasoningBubble-shadow"])!=null?Cr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Ar=(Lo=n["--persona-components-markdown-link-foreground"])!=null?Lo:n["--persona-accent"])!=null?Ar:"#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"]=(Po=n["--persona-components-markdown-codeBlock-background"])!=null?Po:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ss=n["--persona-components-markdown-codeBlock-textColor"])!=null?ss:"inherit",n["--persona-md-table-header-bg"]=(Zr=n["--persona-components-markdown-table-headerBackground"])!=null?Zr:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(eo=n["--persona-components-markdown-hr-color"])!=null?eo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(to=n["--persona-components-markdown-blockquote-borderColor"])!=null?to:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Io=n["--persona-components-markdown-blockquote-background"])!=null?Io:"transparent",n["--persona-md-blockquote-text-color"]=(Ro=n["--persona-components-markdown-blockquote-textColor"])!=null?Ro:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(no=n["--persona-components-collapsibleWidget-container"])!=null?no:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ce=b.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(wn=n["--persona-dropdown-bg"])!=null?wn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(b!=null&&b.tab){let Ce=b.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(b!=null&&b.pane){let Ce=b.pane;if(Ce.toolbarBackground){let $r=(ro=Ms(e,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var Vx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Kx={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"}}},ng=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Gx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},rg=e=>Gx(e),Jx=e=>ua(e),Xx=e=>{var n;let t=ua(void 0,{validate:!1});return ua({...e,palette:{...t.palette,colors:{...Kx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ma=e=>{let t=rg(e),n=ng(e==null?void 0:e.theme),r=ng(e==null?void 0:e.darkTheme);return t==="dark"?Xx(pa(n!=null?n:{},r!=null?r:{})):Jx(n)},Qx=e=>bl(e),es=(e,t)=>{let n=ma(t),r=Qx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},xl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Yx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Yx.morph(e,t.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 og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="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:{...ti}}}function ag(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(P=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?P:0,(I=(C=(k=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(O=(N=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?O:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function cg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Co(e,t){return Br(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Ao=xn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zx=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ga.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ga.buffer}},fg=[{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"}],fa=new Map;for(let e of fg)fa.set(e.name,e);var ev=e=>{fa.set(e.name,e)},tv=e=>{fg.some(t=>t.name===e)||fa.delete(e)},nv=()=>Array.from(fa.keys()),ks=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
18
|
+
_Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),Km=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gm=e=>Ko(e)||e===Hr,da=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ts(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ko(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.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 As(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.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||ml().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Zo.isSupported()?new Zo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.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,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return ml().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(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 p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.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(t){console.error("Failed to start voice:",t)}}}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,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Hy(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 As(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?aa():n==="assistant"?Xo():`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},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?aa():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,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(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=aa(),s=Xo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Va,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(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let S=gl(b,this.config.errorMessage);if(S){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Xo();this.activeAssistantMessageId=null,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:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=gl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(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(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,S,T,L,P,E,k;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,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=t.toolCall)==null?void 0:v.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let j=typeof((S=I[0])==null?void 0:S.question)=="string"?I[0].question:"";j&&(a={[j]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.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(([I,j])=>`${I}: ${Array.isArray(j)?j.join(", "):j}`).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((I,j)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let R=C[$],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${j}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${j}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(k=(E=this.callbacks).onError)==null||k.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var k,C,I,j,$,R,N;let g=(k=f.toolCall)==null?void 0:k.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),T=(j=(I=f.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?j:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:nl(),toolMessage:f,startedAt:S,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let P=this.client.executeWebMcpToolCall(g,($=f.toolCall)==null?void 0:$.args,L.signal),E;if(!P)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await P}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(N=(R=this.callbacks).onError)==null||N.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(f,ca(Z?"Aborted by cancel()":Km(O)),S),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ca("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:E,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,ca("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,S,T,L,P,E,k,C,I,j,$;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,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(N){(E=(P=this.callbacks).onError)==null||E.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Hr,p=(k=t.toolCall)==null?void 0:k.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let R;if(c?R=nl():u?R=await u:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),a);return}let N=(I=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;f="resume",await this.resumeWithToolOutput(n,N,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,R,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let N=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||N||d.aborted)&&this.markWebMcpToolComplete(t,ca(N||d.aborted?"Aborted by cancel()":Km(R)),a),N||($=(j=this.callbacks).onError)==null||$.call(j,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(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.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 t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.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(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Vm(),zm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>gl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=ul(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=ul(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let $=o.approval,R=n.approval;a.approval={...$,...R,executionId:R.executionId||$.executionId,toolName:R.toolName||$.toolName,description:R.description||$.description,toolType:(g=R.toolType)!=null?g:$.toolType,reason:(b=R.reason)!=null?b:$.reason,parameters:(v=R.parameters)!=null?v:$.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&Gm(i)&&d&&c&&((P=n.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let $=`${d}:${c}`,R=this.webMcpInflightKeys.has($),N=this.webMcpResolvedKeys.has($),O=(E=o.toolCall)==null?void 0:E.name,Z=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&O!==void 0&&Gm(O)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(R||N||Z)&&(a.agentMetadata={...(j=a.agentMetadata)!=null?j:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,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 By,ArrowDown as Dy,ArrowUp as Ny,ArrowUpRight as Oy,Bot as Fy,ChevronDown as _y,ChevronUp as $y,ChevronRight as jy,ChevronLeft as Uy,Check as qy,Clipboard as zy,ClipboardCopy as Vy,Copy as Ky,File as Gy,FileCode as Jy,FileSpreadsheet as Xy,FileText as Qy,ImagePlus as Yy,Loader as Zy,LoaderCircle as eb,Mic as tb,Paperclip as nb,RefreshCw as rb,Search as ob,Send as sb,ShieldAlert as ab,ShieldCheck as ib,ShieldX as lb,Square as cb,ThumbsDown as db,ThumbsUp as pb,Upload as ub,Volume2 as mb,X as gb,User as fb,Mail as hb,Phone as yb,Calendar as bb,Clock as xb,Building as vb,MapPin as wb,Lock as Cb,Key as Ab,CreditCard as Sb,AtSign as Tb,Hash as Eb,Globe as Mb,Link as kb,CircleCheck as Lb,CircleX as Pb,TriangleAlert as Ib,Info as Rb,Ban as Wb,Shield as Hb,ArrowLeft as Bb,ArrowRight as Db,ExternalLink as Nb,Ellipsis as Ob,EllipsisVertical as Fb,Menu as _b,House as $b,Plus as jb,Minus as Ub,Pencil as qb,Trash as zb,Trash2 as Vb,Save as Kb,Download as Gb,Share as Jb,Funnel as Xb,Settings as Qb,RotateCw as Yb,Maximize as Zb,Minimize as ex,ShoppingCart as tx,ShoppingBag as nx,Package as rx,Truck as ox,Tag as sx,Gift as ax,Receipt as ix,Wallet as lx,Store as cx,DollarSign as dx,Percent as px,Play as ux,Pause as mx,VolumeX as gx,Camera as fx,Image as hx,Film as yx,Headphones as bx,MessageCircle as xx,MessageSquare as vx,Bell as wx,Heart as Cx,Star as Ax,Eye as Sx,EyeOff as Tx,Bookmark as Ex,CalendarDays as Mx,History as kx,Timer as Lx,Folder as Px,FolderOpen as Ix,Files as Rx,Sparkles as Wx,Zap as Hx,Sun as Bx,Moon as Dx,Flag as Nx,Monitor as Ox,Smartphone as Fx}from"lucide";var _x={activity:By,"arrow-down":Dy,"arrow-up":Ny,"arrow-up-right":Oy,bot:Fy,"chevron-down":_y,"chevron-up":$y,"chevron-right":jy,"chevron-left":Uy,check:qy,clipboard:zy,"clipboard-copy":Vy,copy:Ky,file:Gy,"file-code":Jy,"file-spreadsheet":Xy,"file-text":Qy,"image-plus":Yy,loader:Zy,"loader-circle":eb,mic:tb,paperclip:nb,"refresh-cw":rb,search:ob,send:sb,"shield-alert":ab,"shield-check":ib,"shield-x":lb,square:cb,"thumbs-down":db,"thumbs-up":pb,upload:ub,"volume-2":mb,x:gb,user:fb,mail:hb,phone:yb,calendar:bb,clock:xb,building:vb,"map-pin":wb,lock:Cb,key:Ab,"credit-card":Sb,"at-sign":Tb,hash:Eb,globe:Mb,link:kb,"circle-check":Lb,"circle-x":Pb,"triangle-alert":Ib,info:Rb,ban:Wb,shield:Hb,"arrow-left":Bb,"arrow-right":Db,"external-link":Nb,ellipsis:Ob,"ellipsis-vertical":Fb,menu:_b,house:$b,plus:jb,minus:Ub,pencil:qb,trash:zb,"trash-2":Vb,save:Kb,download:Gb,share:Jb,funnel:Xb,settings:Qb,"rotate-cw":Yb,maximize:Zb,minimize:ex,"shopping-cart":tx,"shopping-bag":nx,package:rx,truck:ox,tag:sx,gift:ax,receipt:ix,wallet:lx,store:cx,"dollar-sign":dx,percent:px,play:ux,pause:mx,"volume-x":gx,camera:fx,image:hx,film:yx,headphones:bx,"message-circle":xx,"message-square":vx,bell:wx,heart:Cx,star:Ax,eye:Sx,"eye-off":Tx,bookmark:Ex,"calendar-days":Mx,history:kx,timer:Lx,folder:Px,"folder-open":Ix,files:Rx,sparkles:Wx,zap:Hx,sun:Bx,moon:Dx,flag:Nx,monitor:Ox,smartphone:Fx},ye=(e,t=24,n="currentColor",r=2)=>{let o=_x[e];return o?$x(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function $x(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),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"),e.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,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ux(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Es=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ya.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Dm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Bm(c),f=Ga(c)?URL.createObjectURL(c):null,g={id:jx(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);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="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",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=Ux(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Nm(t.file.type,t.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=ye("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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Jm(s)&&Jm(o)?n[r]=pa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",fl="440px",qx={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:tr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:qx,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xm(e,t){if(!(!e&&!t))return e?t?pa(e,t):e:t}function hl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k;return e?{...Dt,...e,theme:Xm(Dt.theme,e.theme),darkTheme:Xm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let C=(re=Dt.features)==null?void 0:re.artifacts,I=(se=e.features)==null?void 0:se.artifacts,j=(ae=Dt.features)==null?void 0:ae.scrollToBottom,$=(fe=e.features)==null?void 0:fe.scrollToBottom,R=($e=Dt.features)==null?void 0:$e.scrollBehavior,N=(V=e.features)==null?void 0:V.scrollBehavior,O=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Le=j===void 0&&$===void 0?void 0:{...j,...$},Pe=R===void 0&&N===void 0?void 0:{...R,...N},ne=O===void 0&&Z===void 0?void 0:{...O,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Dt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(T=(S=e.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(E=Dt.markdown)==null?void 0:E.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var Qm={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ym={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Zm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},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:tr,maxWidth:fl,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 Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;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."))?Ms(e,r):r}function yl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[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(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function tg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=tg(s,o):n[r]=o}return n}function zx(e,t){return t?tg(e,t):e}function ua(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,S;let n={palette:Qm,semantic:Ym,components:Zm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:zx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=eg(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function bl(e){var v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,vn,Ct,fn,yr,br,Ue,M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro;let t=yl(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P: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"]=(k=n["--persona-semantic-colors-text"])!=null?k: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"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(j=n["--persona-semantic-colors-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$: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=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O: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"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de: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"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re: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"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(vn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?vn:"0.5rem",n["--persona-message-user-radius"]=(fn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te: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"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(xr=n["--persona-components-message-assistant-shadow"])!=null?xr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Xr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Xr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Qr=n["--persona-components-scrollToBottom-gap"])!=null?Qr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Yr=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(wr=n["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Cr=n["--persona-components-reasoningBubble-shadow"])!=null?Cr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Ar=(Lo=n["--persona-components-markdown-link-foreground"])!=null?Lo:n["--persona-accent"])!=null?Ar:"#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"]=(Po=n["--persona-components-markdown-codeBlock-background"])!=null?Po:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ss=n["--persona-components-markdown-codeBlock-textColor"])!=null?ss:"inherit",n["--persona-md-table-header-bg"]=(Zr=n["--persona-components-markdown-table-headerBackground"])!=null?Zr:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(eo=n["--persona-components-markdown-hr-color"])!=null?eo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(to=n["--persona-components-markdown-blockquote-borderColor"])!=null?to:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Io=n["--persona-components-markdown-blockquote-background"])!=null?Io:"transparent",n["--persona-md-blockquote-text-color"]=(Ro=n["--persona-components-markdown-blockquote-textColor"])!=null?Ro:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(no=n["--persona-components-collapsibleWidget-container"])!=null?no:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ce=b.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(wn=n["--persona-dropdown-bg"])!=null?wn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(b!=null&&b.tab){let Ce=b.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(b!=null&&b.pane){let Ce=b.pane;if(Ce.toolbarBackground){let $r=(ro=Ms(e,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var Vx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Kx={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"}}},ng=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Gx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},rg=e=>Gx(e),Jx=e=>ua(e),Xx=e=>{var n;let t=ua(void 0,{validate:!1});return ua({...e,palette:{...t.palette,colors:{...Kx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ma=e=>{let t=rg(e),n=ng(e==null?void 0:e.theme),r=ng(e==null?void 0:e.darkTheme);return t==="dark"?Xx(pa(n!=null?n:{},r!=null?r:{})):Jx(n)},Qx=e=>bl(e),es=(e,t)=>{let n=ma(t),r=Qx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},xl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Yx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Yx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="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:{...ti}}}function ag(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(P=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?P:0,(I=(C=(k=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(O=(N=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?O:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function cg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Co(e,t){return Br(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Ao=xn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zx=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ga.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ga.buffer}},fg=[{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"}],fa=new Map;for(let e of fg)fa.set(e.name,e);var ev=e=>{fa.set(e.name,e)},tv=e=>{fg.some(t=>t.name===e)||fa.delete(e)},nv=()=>Array.from(fa.keys()),ks=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
19
19
|
`);return s<0?"":e.slice(0,s)}return e},rv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},ov=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,sv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},av=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let c=i;for(;c<s.length&&vl.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 p=i;for(;p<s.length&&!vl.test(s[p]);)c.appendChild(rv(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},iv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.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(ov(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Zx).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)sv(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?av:iv;for(let g of i)p(g,n,c);return o.innerHTML},ii=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ya=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},gg=new WeakMap,lv=(e,t)=>{var s;if(!e.styles)return;let n=gg.get(t);if(n||(n=new Set,gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,cv=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},hg=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},li=(e,t)=>{lv(e,t),cv(e,t)};function Cl(e,t=xn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var ba=0,So=null;function Al(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;So={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 t=!1;return()=>{var r;if(!t&&(t=!0,ba=Math.max(0,ba-1),ba===0&&So)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,s.scrollTo(0,So.scrollY),So=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},To=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var hr={"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 dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ci=(e,t={})=>{var S,T,L,P,E,k;let{showClose:n=!0,wrapperClassName:r=dv,buttonSize:o,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(P=a.closeButtonShowTooltip)!=null?P:!0,u=(E=a.closeButtonIconName)!=null?E:"x",f=(k=a.closeButtonIconText)!=null?k:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=ye(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,I=()=>{if(C)return;let $=b.ownerDocument,R=$.body;if(!R)return;C=Wr($,"div","persona-clear-chat-tooltip"),C.textContent=c;let N=Wr($,"div");N.className="persona-clear-chat-tooltip-arrow",C.appendChild(N);let O=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ao),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},j=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",j),b.addEventListener("focus",I),b.addEventListener("blur",j),d._cleanupTooltip=()=>{j(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",j),b.removeEventListener("focus",I),b.removeEventListener("blur",j)}}return{button:b,wrapper:d}},pv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",di=(e,t={})=>{var C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe;let{wrapperClassName:n=pv,buttonSize:r,iconSize:o="20px"}=t,a=(I=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(j=r!=null?r:a.size)!=null?j:"32px",d=($=a.iconName)!=null?$:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(N=a.backgroundColor)!=null?N:"",u=(O=a.borderWidth)!=null?O:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ee=a.borderRadius)!=null?Ee:"",b=(de=a.paddingX)!=null?de:"",v=(ee=a.paddingY)!=null?ee:"",S=(Le=a.tooltipText)!=null?Le:"Clear chat",T=(Pe=a.showTooltip)!=null?Pe:!0,L=y("div",n),P=!!(u||f),E=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:c||Mn.actionIconColor,backgroundColor:p||void 0,border:P?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),k=ye(d,o,"currentColor",1);if(k&&(k.style.display="block",E.appendChild(k)),L.appendChild(E),T&&S){let ne=null,Ae=()=>{if(ne)return;let se=E.ownerDocument,ae=se.body;if(!ae)return;ne=Wr(se,"div","persona-clear-chat-tooltip"),ne.textContent=S;let fe=Wr(se,"div");fe.className="persona-clear-chat-tooltip-arrow",ne.appendChild(fe);let $e=E.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(Ao),ne.style.left=`${$e.left+$e.width/2}px`,ne.style.top=`${$e.top-8}px`,ne.style.transform="translate(-50%, -100%)",ae.appendChild(ne)},re=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",re),E.addEventListener("focus",Ae),E.addEventListener("blur",re),L._cleanupTooltip=()=>{re(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",re),E.removeEventListener("focus",Ae),E.removeEventListener("blur",re)}}return{button:E,wrapper:L}};var Mn={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))"},Eo=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae;let{config:t,showClose:n=!0}=e,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=(k=t==null?void 0:t.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(I=o.closeButtonPlacement)!=null?I:"inline",i=(j=o.headerIconHidden)!=null?j:!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 re=parseFloat(s)||24,se=ye(d,re*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?R:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let re=y("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(Z=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Mn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Pe=o.clearChat)!=null?Pe:{},b=(ne=g.enabled)!=null?ne:!0,v=(Ae=g.placement)!=null?Ae:"inline",S=null,T=null;if(b){let se=di(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=se.button,T=se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&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:P,wrapper:E}=ci(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:P,closeButtonWrapper:E,clearChatButton:S,clearChatButtonWrapper:T}},Ls=(e,t,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";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ts(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ao)):(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 g of t){if(g.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let S=ye(g.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",S=>{S.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ye(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function pi(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=ye(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function ui(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Sl(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,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",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=ye(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,S;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ts({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var yg=e=>{var r;let t=Eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function uv(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){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=ye(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=ts({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var bg=e=>{var L,P,E,k,C,I,j,$,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},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,p;if(d)c=Sl({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Mn.titleColor,p=(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"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(p),uv(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 O=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||O()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),O())})}let N=o==null?void 0:o.titleRowHover;N&&(c.style.borderRadius=(I=N.borderRadius)!=null?I:"10px",c.style.padding=(j=N.padding)!=null?j:"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 O,Z;c.style.backgroundColor=(O=N.background)!=null?O:"",c.style.borderColor=(Z=N.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=($=a.closeButtonSize)!=null?$:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Mn.actionIconColor;let b=(R=a.closeButtonIconName)!=null?R:"x",v=ye(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let S=y("div");S.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:T,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:yg,minimal:bg},xg=e=>{var t;return(t=Tl[e])!=null?t:Tl.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=xg(r)({config:e,showClose:(d=(i=t==null?void 0:t.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:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},gi=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee;let t=(k=e==null?void 0:e.sendButton)!=null?k:{},n=(C=t.useIcon)!=null?C:!1,r=(I=t.iconText)!=null?I:"\u2191",o=t.iconName,s=(j=t.stopIconName)!=null?j:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(O=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?O:"Send",c=(Ee=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("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&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),S=null,T=null;if(n){let Le=parseFloat(u)||24,Pe=(g==null?void 0:g.trim())||"currentColor";o?(S=ye(o,Le,Pe,2),S?v.appendChild(S):v.textContent=r):v.textContent=r,T=ye(s,Le,Pe,2)}else v.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,b.appendChild(L)),v.setAttribute("aria-label",a),b.appendChild(v);let P="send";return{button:v,wrapper:b,setMode:Le=>{if(Le===P)return;P=Le;let Pe=Le==="stop"?i:a;if(v.setAttribute("aria-label",Pe),L&&(L.textContent=Pe),n){if(S&&T){let ne=Le==="stop"?T:S;v.replaceChildren(ne)}}else v.textContent=Le==="stop"?c:d}}},fi=e=>{var L,P,E,k,C,I,j,$,R,N,O,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||o))return null;let a=(k=(E=e==null?void 0:e.sendButton)==null?void 0:E.size)!=null?k:"40px",i=(C=t.iconName)!=null?C:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=($=t.backgroundColor)!=null?$:(j=e==null?void 0:e.sendButton)==null?void 0:j.backgroundColor,u=(N=t.iconColor)!=null?N:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,f=y("div","persona-send-button-wrapper"),g=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:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ye(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let S=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&S){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=S,f.appendChild(Ee)}return{button:g,wrapper:f}},hi=e=>{var b,v,S,T,L,P,E,k;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(S=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?S:"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=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(P=t.buttonIconName)!=null?P:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=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=t.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"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ye(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(k=t.buttonTooltipText)!=null?k:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.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=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.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},bi=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var b,v,S,T,L,P;let{config:t}=e,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=bi(),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}=mi(t);a();let i=gi(t),d=fi(t),c=hi(t),p=yi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),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,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var vg=()=>{let e=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ye("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},wg=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=bi();r.style.display="none";let o=yi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),c=hi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.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&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Cg=e=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(To(e)){let N=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(b=N.expandedSize)!=null?b:"anchored",O.style.zIndex=String((S=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?S:xn);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%",O.appendChild(Z);let Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=N.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((P=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?P:xn),{wrapper:O,panel:Z,pillRoot:Ee}}if(n){let N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(O),{wrapper:N,panel:O}}if(!t){let N=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.width)!=null?k:"100%";return N.style.width=Z,O.style.width="100%",N.appendChild(O),{wrapper:N,panel:O}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&hr[o.position]?hr[o.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((j=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?j:xn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?R:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},mv=(e,t)=>{var E,k,C,I,j,$,R,N,O;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}=ci(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=di(e,{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 p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(j=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?j:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),f=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))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let S=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"}}),T=wg({config:e}),{root:L,textNode:P}=vg();return n.append(d,o,c,S),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:P}},Ag=(e,t=!0)=>{var S,T,L,P,E,k,C,I,j;if(To(e))return mv(e,t);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=(S=e==null?void 0:e.layout)==null?void 0:S.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):Eo({config:e,showClose:t}),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:(P=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeSubtitle)!=null?k:"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:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=wa({config:e}),b=((j=e==null?void 0:e.layout)==null?void 0:j.showFooter)!==!1;o?Ls(n,s,e):(s.header.style.display="none",Ls(n,s,e)),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 b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var El=(e,t)=>{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" />
|