@runtypelabs/persona 4.4.1 → 4.4.2

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/index.js CHANGED
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},Xf=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)}},Qf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Yf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zf="agent_",eh="flow_";function Nu(e){return e.startsWith(Zf)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Ou(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 l=Nu(i);if(l)return l;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=Nu(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 th,ARR as nh,OBJ as rh,STR as oh}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 St=(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},qs=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",zs=8,ms="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",_u="Type your own answer here",$u="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,$i="data-ask-current-index",ji="data-ask-question-count",ju="data-ask-answers",Ui="data-ask-grouped",Uu="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",mh=e=>e.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,qu=e=>e.replace(/["\\]/g,"\\$&"),po=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,Ia=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},uo=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=th(o,oh|rh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!Fu&&(Fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},gh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},fh=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},zu=(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))},Vu=(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},hh=(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 l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Vu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=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},bh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<ph;f++)s.appendChild(yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(hh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?sh:ah;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:_u,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=Vu(r,a,d.length);T&&v.appendChild(T),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Ku=(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:_u,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:$u,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xh=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:$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:lh,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:dh,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:ch:(g=n.nextLabel)!=null?g:ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let t=e.getAttribute(ju);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gu=(e,t)=>{e.setAttribute(ju,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute($i,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ui)==="true",Ch=(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},Ah=(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)))},Ra=(e,t)=>{let{payload:n}=uo(t),r=Vs(n),o=Fo(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ju=e=>{let t=Fo(e),n=or(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 l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);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 l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),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=""},Xu=e=>{if(!mo(e))return;let t=Fo(e),n=or(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}},qi=(e,t,n)=>{let r=Ia(n),o=mh(e),{payload:s,complete:a}=uo(t),i=mo(e),d=or(e),l=gs(e),p=i?fh(s,d):gh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=bh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ku(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(xh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=vh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Ju(e),Xu(e)},Sh=(e,t,n)=>{let r=Ia(t),o=uh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=Ch(e,a),p=d?Ah(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ms,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(ji,String(i)),u.setAttribute($i,String(p)),u.setAttribute(Ui,d?"true":"false"),u.setAttribute(Uu,o),Gu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),zu(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(Ku(r,o)),qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:r}=uo(t),o=Math.max(1,Vs(r).length);o>gs(e)&&(e.setAttribute(ji,String(o)),o>1&&!mo(e)&&e.setAttribute(Ui,"true")),qi(e,t,n)},Eh=(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=Ia(t);zu(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=uo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!po(e)||Ia(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==o&&l.remove()});let a=n.querySelector(`[${ms}="${qu(o)}"]`);if(a){Th(a,e,t);return}let{payload:i}=uo(e),d=Sh(e,t,i);n.appendChild(d)},_o=(e,t)=>{if(!e)return;let n=t?`[${ms}="${qu(t)}"]`:`[${ms}]`;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)})},zi=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),go=(e,t)=>{let n=Fo(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Gu(e,n),Ju(e),Xu(e)},Wa=(e,t,n,r)=>{let o=gs(e),s=Math.max(0,Math.min(o-1,r));wh(e,s),qi(e,t,n)};var Hr="suggest_replies";var Qu={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},Vi={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:Qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ha=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Yu=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},Gi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ha(r))continue;let o=Yu((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Zu=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 em={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},tm={name:Pa,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:em,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=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(tm),Zu(e)&&t.push(Vi),t};import{parse as nm,STR as rm,OBJ as om}from"partial-json";var Da=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=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)}},Mh=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`},sm=e=>e.status==="complete"?Mh(e):e.status==="pending"?"Waiting":"",kh=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 am=e=>e.status==="complete"?kh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=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 Na(t)},Oa=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 Na(t)},Ji=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Gs(r,n.slice(s,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Gs(r,n.slice(s),[]),r},Gs=(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})},Lh=()=>{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()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();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)}},Yi=()=>{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=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(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=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{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 im="4.4.1";var fr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(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 el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(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=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=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:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(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 js(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=Ou(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$/,""))||_a}/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,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l: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$/,""))||_a}/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 M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}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){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}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$/,""))||_a}/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 l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/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(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(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 l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l: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,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(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 l=>{try{let p=await l({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 l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}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},l=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=l(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){var xt,hn,yr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,De=A.tools?A.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:De}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Te,De,Pe,Ne;return W((Ne=(Pe=(De=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?De:A.parentId)!=null?Pe:A.flowStepId)!=null?Ne:A.flow_step_id)},N=A=>{var te,Te,De,Pe,Ne,Ge,it;return W((it=(Ge=(Ne=(Pe=(De=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?De:A.request_id)!=null?Pe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Y=r,Ee=!1,de=()=>{if(f)return f;let A,te=T;return!Ee&&Y?(A=Y,Ee=!0):Y&&te?A=`${Y}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},Z=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},Ce=(A,te)=>{var Ne;let Te=(Ne=A.reasoningId)!=null?Ne:A.id,De=O(A);if(Te){let Ge=String(Te);return Z(De,Ge),Ge}if(De){let Ge=F.byStep.get(De);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Pe=`reason-${l()}`;return Z(De,Pe),Pe},ke=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},re=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},we=new Set,le=new Map,se=new Set,oe=new Map,be=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},He=(A,te)=>{var Ne;let Te=(Ne=A.toolId)!=null?Ne:A.id,De=N(A);if(Te){let Ge=String(Te);return re(De,Ge),Ge}if(De){let Ge=j.byCall.get(De);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Pe=`tool-${l()}`;return re(De,Pe),Pe},V=A=>{let te=R.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Te),g(Te),Te},X=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},We=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,pe=new Map,$e=new Map,ge=(A,te,Te)=>{var it;let De=$e.get(A);De||(De=[],$e.set(A,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<te?Pe=It+1:Ne=It}((it=De[Pe])==null?void 0:it.seq)===te?De[Pe]={seq:te,text:Te}:De.splice(Pe,0,{seq:te,text:Te});let Ge="";for(let It=0;It<De.length;It++)Ge+=De[It].text;return Ge},Ve=(A,te)=>{let Te=We(te),De=pe.get(A.id),Pe=Bh(De,Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=he=>{var vt;let Fe=(vt=A.content)!=null?vt:"";he.trim()!==""&&(Fe.trim().length===0||he.startsWith(Fe)||he.trimStart().startsWith(Fe.trim()))&&(A.content=he)},it=()=>{var he;if(Ne){let Fe=(he=Ne.close)==null?void 0:he.call(Ne);Fe instanceof Promise&&Fe.catch(()=>{})}K.delete(A.id),pe.delete(A.id),A.streaming=!1,g(A)};if(!Ne){Ge(Te),it();return}let It=Xs(Pe);if(It!==null&&It.trim()!==""){Ge(It),it();return}let ce=he=>{var Ye;let Fe=typeof he=="string"?he:(Ye=he==null?void 0:he.text)!=null?Ye:null;if(Fe!==null&&Fe.trim()!=="")return Fe;let vt=Ne.getExtractedText();return vt!==null&&vt.trim()!==""?vt:Te},H;try{H=Ne.processChunk(Pe)}catch{Ge(Te),it();return}if(H instanceof Promise){H.then(he=>{Ge(ce(he)),it()}).catch(()=>{Ge(Te),it()});return}Ge(ce(H)),it()},et=null,$t=(A,te,Te,De)=>{var It;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Pe=K.get(A.id),Ne=te.trim().startsWith("{")||te.trim().startsWith("[");if(Ne&&pe.set(A.id,te),Pe.__isPlainTextParser===!0){A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let it=Pe.processChunk(te);if(it instanceof Promise)it.then(ce=>{var he;let H=typeof ce=="string"?ce:(he=ce==null?void 0:ce.text)!=null?he:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof it=="string"?it:(It=it==null?void 0:it.text)!=null?It:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var It,ce;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let De=pe.get(A.id),Pe=De!=null?De:We(Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=null,it=!1;if(Ne&&(Ge=Ne.getExtractedText(),Ge===null&&(Ge=Xs(Pe)),Ge===null)){let H=Ne.processChunk(Pe);H instanceof Promise?(it=!0,H.then(he=>{var vt;let Fe=typeof he=="string"?he:(vt=he==null?void 0:he.text)!=null?vt:null;Fe!==null&&(A.content=Fe,A.streaming=!1,K.delete(A.id),pe.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(It=H==null?void 0:H.text)!=null?It:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:pe.has(A.id)||(A.content=We(Te));let H=K.get(A.id);if(H){let he=(ce=H.close)==null?void 0:ce.call(H);he instanceof Promise&&he.catch(()=>{}),K.delete(A.id)}pe.delete(A.id),A.streaming=!1,g(A)}},fe=(A,te,Te)=>{let De=M.get(A);if(De)return De;let Pe={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Pe),g(Pe),Pe},J=[],dt,qe=new Map,Ae=0,Me="agent",nt=!1,Pt=null,ee=null,je=new Map,Cn=(xt=this.config.iterationDisplay)!=null?xt:"separate";for(dt=()=>{var A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo,xe,Pn,Cr,mt,rn,on,Ar,ks,_r,Eo,Sr,$,Qo,Tr,Er,$r,Mr,cr,Yo,xa,_n,$n,dr,pr,Mo,jr,bn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,In,Ca;for(let rs=0;rs<J.length;rs++){let tt=J[rs].payloadType,w=J[rs].payload;if(!nt&&Me!=="flow"&&typeof w.stepType=="string"&&(Me="flow"),tt==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),fe(z,U,"reasoning");continue}let G=(A=Ce(w,!0))!=null?A:`reason-${l()}`,ye=ke(G);ye.reasoning=(te=ye.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},ye.reasoning.startedAt=(De=ye.reasoning.startedAt)!=null?De:X((Te=w.startedAt)!=null?Te:w.timestamp),ye.reasoning.completedAt=void 0,ye.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),ye.streaming=!0,ye.reasoning.status="streaming",g(ye)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let _e=M.get(z),gt=(Ge=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(gt)),g(_e));continue}let U=(It=(it=Ce(w,!1))!=null?it:Ce(w,!0))!=null?It:`reason-${l()}`,G=ke(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(he=G.reasoning.startedAt)!=null?he:X((H=w.startedAt)!=null?H:w.timestamp);let ye=(Ye=(vt=(Fe=w.reasoningText)!=null?Fe:w.text)!=null?vt:w.delta)!=null?Ye:"";if(ye&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let gt=ge(U,_e,String(ye));G.reasoning.chunks=[gt]}else G.reasoning.chunks.push(String(ye))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Ht=w.completedAt)!=null?Ht:w.timestamp);let _e=(Tt=G.reasoning.startedAt)!=null?Tt:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-_e)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(tt==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(Qt=(Lt=Ce(w,!1))!=null?Lt:Ce(w,!0))!=null?Qt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&ke(U);let ye=C.get(U);if(ye!=null&&ye.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),G&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(G),ye.reasoning.status="complete",ye.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let gt=(Hn=ye.reasoning.startedAt)!=null?Hn:Date.now();ye.reasoning.durationMs=Math.max(0,((jt=ye.reasoning.completedAt)!=null?jt:Date.now())-gt),ye.streaming=!1,g(ye)}let _e=O(w);_e&&F.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ae=w.iteration);let z=(Gn=(Bn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Bn:He(w,!0))!=null?Gn:`tool-${l()}`,U=(yn=w.toolName)!=null?yn:w.name;if(be(U)){we.add(z);continue}re(N(w),z);let G=V(z),ye=(kn=G.toolCall)!=null?kn:{id:z,status:"pending"};ye.name=U!=null?U:ye.name,ye.status="running",w.parameters!==void 0?ye.args=w.parameters:w.args!==void 0&&(ye.args=w.args),ye.startedAt=(Xr=ye.startedAt)!=null?Xr:X((Jn=w.startedAt)!=null?Jn:w.timestamp),ye.completedAt=void 0,ye.durationMs=void 0,G.toolCall=ye,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(xr=(wt=He(w,!1))!=null?wt:He(w,!0))!=null?xr:`tool-${l()}`;if(we.has(z))continue;let U=V(z),G=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Dr=w.startedAt)!=null?Dr:w.timestamp);let ye=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";ye&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ye))),G.status="running",U.toolCall=G,U.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Ln=_e==null?void 0:_e.executionId)!=null?Ln:w.executionId,iteration:(Xo=_e==null?void 0:_e.iteration)!=null?Xo:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(Yr=(Nr=He(w,!1))!=null?Nr:He(w,!0))!=null?Yr:`tool-${l()}`;if(we.has(z)){we.delete(z);continue}let U=V(z),G=(Zr=U.toolCall)!=null?Zr:{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=X((So=w.completedAt)!=null?So:w.timestamp);let ye=(To=w.duration)!=null?To:w.executionTime;if(typeof ye=="number")G.durationMs=ye;else{let st=(eo=G.startedAt)!=null?eo:Date.now();G.durationMs=Math.max(0,((bt=G.completedAt)!=null?bt:Date.now())-st)}U.toolCall=G,U.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(An=U.agentMetadata)!=null?An:{executionId:(Dn=_e==null?void 0:_e.executionId)!=null?Dn:w.executionId,iteration:(Nn=_e==null?void 0:_e.iteration)!=null?Nn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(Ct=z!=null?z:w.toolId)!=null?Ct:`local-${l()}`,G=V(U),ye=w.toolName,_e=w.origin==="webmcp"&&!Oo(ye)?`webmcp:${ye}`:ye,gt=Oo(_e),st=(Xn=G.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=_e,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Or=st.startedAt)!=null?Or:X((to=(On=w.startedAt)!=null?On:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,G.toolCall=st,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:(Fn=G.agentMetadata)==null?void 0:Fn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(tt==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let G=f;G&&(Me==="flow"?(Xe(G),et=G):(G.streaming=!1,g(G)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(tt==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let ye=typeof w.delta=="string"?w.delta:"",_e=((Sn=P.get(z))!=null?Sn:"")+ye;if(P.set(z,_e),_e.trim()==="")continue;let gt=fe(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},$t(gt,_e,ye,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Me==="flow"){let ye=typeof w.delta=="string"?w.delta:"";if(L+=ye,L.trim()==="")continue;let _e=de();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},$t(_e,L,ye,void 0),v=_e;continue}let G=de();G.content+=(Yn=w.delta)!=null?Yn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Pt!=null?Pt:void 0,agentName:ee==null?void 0:ee.agentName},v=G,g(G)}else if(tt==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let G=M.get(z);G&&Xe(G),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Me==="flow"?(Xe(U),et=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(tt==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let G=w.error,ye=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Fr=G.message)!=null?Fr:"Step failed"):"Step failed";n({type:"error",error:new Error(ye)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let ye=w.stopReason,_e=(oo=w.result)==null?void 0:oo.response;if(G)ye&&(G.stopReason=ye),_e!=null?Ve(G,_e):G.streaming!==!1&&(K.delete(G.id),pe.delete(G.id),G.streaming=!1,g(G));else{let gt=_e!=null&&_e!=="";if(gt||ye){let st=de();ye&&(st.stopReason=ye),gt?Xe(st,_e):(st.streaming=!1,g(st))}}continue}}else if(tt==="execution_start")Me=w.kind==="flow"?"flow":"agent",nt=!0,Me==="agent"&&(ee={executionId:w.executionId,agentId:(xe=w.agentId)!=null?xe:"virtual",agentName:(Pn=w.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Ae;if(z!==Ae){if(ee&&(ee.currentIteration=z),Cn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Ae=z}Pt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let G=w.id;(!G||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===G)&&(U.stopReason=z,g(U))}Pt===w.id&&(Pt=null)}else if(tt==="media_start"){let z=String(w.id);qe.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(tt==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(tt==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let G=(_r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?_r:"application/octet-stream",ye=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(ye)gt={type:"media",data:ye,mediaType:G};else if(_e){let dn=G.toLowerCase();gt={type:dn==="image"||dn.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:G}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Rn=[];for(let dn of Ps){if(!dn||typeof dn!="object")continue;let pn=dn,Lo=typeof pn.type=="string"?pn.type:void 0,Ur=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",Tn=null,fn="";if(Lo==="media"){let jn=typeof pn.data=="string"?pn.data:void 0;if(!jn)continue;fn=Ur.length>0?Ur:"application/octet-stream",Tn=`data:${fn};base64,${jn}`}else if(Lo==="image-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else if(Lo==="file-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else continue;if(Tn)if(Lo==="image-url"||fn.startsWith("image/"))Rn.push({type:"image",image:Tn,...fn.includes("/")?{mimeType:fn}:{}});else if(fn.startsWith("audio/"))Rn.push({type:"audio",audio:Tn,mimeType:fn});else if(fn.startsWith("video/"))Rn.push({type:"video",video:Tn,mimeType:fn});else{let jn=fn||"application/octet-stream";Rn.push({type:"file",data:Tn,mimeType:jn,filename:Wh(jn)})}}if(Rn.length>0){let dn=l(),pn=st,Ur={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${dn}`:String(dn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:dn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ae}};g(Ur);let Tn=f;Tn&&(Tn.streaming=!1,g(Tn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Me;z==="agent"&&ee&&(ee.status=w.success?"complete":"error",ee.completedAt=X(w.completedAt),ee.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Xe(U):(U.streaming=!1,g(U)),f=null),T=null,L="",et=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ee==null?void 0:ee.agentId)!=null?Er:"virtual",executionId:(Mr=($r=w.executionId)!=null?$r:ee==null?void 0:ee.executionId)!=null?Mr:"",toolName:(cr=w.toolName)!=null?cr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let z=(_n=w.approvalId)!=null?_n:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:($n=ee==null?void 0:ee.agentId)!=null?$n:"virtual",executionId:(pr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?pr:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(bn=w.description)!=null?bn:`Execute ${(jr=w.toolName)!=null?jr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="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:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ee==null?void 0:ee.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ee==null?void 0:ee.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=w.artifactType,U=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),oe.set(U,{markdown:"",title:G}),!se.has(U)){se.add(U);let ye={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:G,artifactType:z,status:"streaming"}})};le.set(U,ye),g(ye)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let G=oe.get(z);G&&(G.markdown+=U)}else if(tt==="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(tt==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=le.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(G.props){G.props.status="complete";let ye=oe.get(z);ye!=null&&ye.markdown&&(G.props.markdown=ye.markdown)}U.rawContent=JSON.stringify(G)}catch{}oe.delete(z),g(U),le.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),G=z.role,_e={id:U,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:l()};if(g(_e),_e.rawContent)try{let gt=JSON.parse(_e.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&se.add(st)}catch{}f=null,x.current=null,K.delete(U),pe.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(tt==="dispatch_error"){let U=(In=w.message)!=null?In:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>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()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();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)}},Yi=()=>{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=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(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=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{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 im="4.4.2";var fr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(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 el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(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=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=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:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(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 js(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=Ou(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$/,""))||_a}/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,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l: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$/,""))||_a}/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 M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}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){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}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$/,""))||_a}/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 l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/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(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(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 l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l: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,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(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 l=>{try{let p=await l({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 l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}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},l=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=l(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){var xt,hn,yr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,De=A.tools?A.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:De}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Te,De,Pe,Ne;return W((Ne=(Pe=(De=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?De:A.parentId)!=null?Pe:A.flowStepId)!=null?Ne:A.flow_step_id)},N=A=>{var te,Te,De,Pe,Ne,Ge,it;return W((it=(Ge=(Ne=(Pe=(De=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?De:A.request_id)!=null?Pe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Y=r,Ee=!1,de=()=>{if(f)return f;let A,te=T;return!Ee&&Y?(A=Y,Ee=!0):Y&&te?A=`${Y}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},Z=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},Ce=(A,te)=>{var Ne;let Te=(Ne=A.reasoningId)!=null?Ne:A.id,De=O(A);if(Te){let Ge=String(Te);return Z(De,Ge),Ge}if(De){let Ge=F.byStep.get(De);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Pe=`reason-${l()}`;return Z(De,Pe),Pe},ke=A=>{let te=C.get(A);if(te)return te;let Te={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Te),g(Te),Te},re=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},we=new Set,le=new Map,se=new Set,oe=new Map,be=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},He=(A,te)=>{var Ne;let Te=(Ne=A.toolId)!=null?Ne:A.id,De=N(A);if(Te){let Ge=String(Te);return re(De,Ge),Ge}if(De){let Ge=j.byCall.get(De);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Pe=`tool-${l()}`;return re(De,Pe),Pe},V=A=>{let te=R.get(A);if(te)return te;let Te={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Te),g(Te),Te},X=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},We=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,pe=new Map,$e=new Map,ge=(A,te,Te)=>{var it;let De=$e.get(A);De||(De=[],$e.set(A,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<te?Pe=It+1:Ne=It}((it=De[Pe])==null?void 0:it.seq)===te?De[Pe]={seq:te,text:Te}:De.splice(Pe,0,{seq:te,text:Te});let Ge="";for(let It=0;It<De.length;It++)Ge+=De[It].text;return Ge},Ve=(A,te)=>{let Te=We(te),De=pe.get(A.id),Pe=Bh(De,Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=he=>{var vt;let Fe=(vt=A.content)!=null?vt:"";he.trim()!==""&&(Fe.trim().length===0||he.startsWith(Fe)||he.trimStart().startsWith(Fe.trim()))&&(A.content=he)},it=()=>{var he;if(Ne){let Fe=(he=Ne.close)==null?void 0:he.call(Ne);Fe instanceof Promise&&Fe.catch(()=>{})}K.delete(A.id),pe.delete(A.id),A.streaming=!1,g(A)};if(!Ne){Ge(Te),it();return}let It=Xs(Pe);if(It!==null&&It.trim()!==""){Ge(It),it();return}let ce=he=>{var Ye;let Fe=typeof he=="string"?he:(Ye=he==null?void 0:he.text)!=null?Ye:null;if(Fe!==null&&Fe.trim()!=="")return Fe;let vt=Ne.getExtractedText();return vt!==null&&vt.trim()!==""?vt:Te},H;try{H=Ne.processChunk(Pe)}catch{Ge(Te),it();return}if(H instanceof Promise){H.then(he=>{Ge(ce(he)),it()}).catch(()=>{Ge(Te),it()});return}Ge(ce(H)),it()},et=null,$t=(A,te,Te,De)=>{var It;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Pe=K.get(A.id),Ne=te.trim().startsWith("{")||te.trim().startsWith("[");if(Ne&&pe.set(A.id,te),Pe.__isPlainTextParser===!0){A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let it=Pe.processChunk(te);if(it instanceof Promise)it.then(ce=>{var he;let H=typeof ce=="string"?ce:(he=ce==null?void 0:ce.text)!=null?he:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof it=="string"?it:(It=it==null?void 0:it.text)!=null?It:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var It,ce;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let De=pe.get(A.id),Pe=De!=null?De:We(Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=null,it=!1;if(Ne&&(Ge=Ne.getExtractedText(),Ge===null&&(Ge=Xs(Pe)),Ge===null)){let H=Ne.processChunk(Pe);H instanceof Promise?(it=!0,H.then(he=>{var vt;let Fe=typeof he=="string"?he:(vt=he==null?void 0:he.text)!=null?vt:null;Fe!==null&&(A.content=Fe,A.streaming=!1,K.delete(A.id),pe.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(It=H==null?void 0:H.text)!=null?It:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:pe.has(A.id)||(A.content=We(Te));let H=K.get(A.id);if(H){let he=(ce=H.close)==null?void 0:ce.call(H);he instanceof Promise&&he.catch(()=>{}),K.delete(A.id)}pe.delete(A.id),A.streaming=!1,g(A)}},fe=(A,te,Te)=>{let De=M.get(A);if(De)return De;let Pe={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Pe),g(Pe),Pe},J=[],dt,qe=new Map,Ae=0,Me="agent",nt=!1,Pt=null,ee=null,je=new Map,Cn=(xt=this.config.iterationDisplay)!=null?xt:"separate";for(dt=()=>{var A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo,xe,Pn,Cr,mt,rn,on,Ar,ks,_r,Eo,Sr,$,Qo,Tr,Er,$r,Mr,cr,Yo,xa,_n,$n,dr,pr,Mo,jr,bn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,In,Ca;for(let rs=0;rs<J.length;rs++){let tt=J[rs].payloadType,w=J[rs].payload;if(!nt&&Me!=="flow"&&typeof w.stepType=="string"&&(Me="flow"),tt==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),fe(z,U,"reasoning");continue}let G=(A=Ce(w,!0))!=null?A:`reason-${l()}`,ye=ke(G);ye.reasoning=(te=ye.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},ye.reasoning.startedAt=(De=ye.reasoning.startedAt)!=null?De:X((Te=w.startedAt)!=null?Te:w.timestamp),ye.reasoning.completedAt=void 0,ye.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),ye.streaming=!0,ye.reasoning.status="streaming",g(ye)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let _e=M.get(z),gt=(Ge=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(gt)),g(_e));continue}let U=(It=(it=Ce(w,!1))!=null?it:Ce(w,!0))!=null?It:`reason-${l()}`,G=ke(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(he=G.reasoning.startedAt)!=null?he:X((H=w.startedAt)!=null?H:w.timestamp);let ye=(Ye=(vt=(Fe=w.reasoningText)!=null?Fe:w.text)!=null?vt:w.delta)!=null?Ye:"";if(ye&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let gt=ge(U,_e,String(ye));G.reasoning.chunks=[gt]}else G.reasoning.chunks.push(String(ye))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Ht=w.completedAt)!=null?Ht:w.timestamp);let _e=(Tt=G.reasoning.startedAt)!=null?Tt:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-_e)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(tt==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(Qt=(Lt=Ce(w,!1))!=null?Lt:Ce(w,!0))!=null?Qt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&ke(U);let ye=C.get(U);if(ye!=null&&ye.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),G&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(G),ye.reasoning.status="complete",ye.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let gt=(Hn=ye.reasoning.startedAt)!=null?Hn:Date.now();ye.reasoning.durationMs=Math.max(0,((jt=ye.reasoning.completedAt)!=null?jt:Date.now())-gt),ye.streaming=!1,g(ye)}let _e=O(w);_e&&F.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ae=w.iteration);let z=(Gn=(Bn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Bn:He(w,!0))!=null?Gn:`tool-${l()}`,U=(yn=w.toolName)!=null?yn:w.name;if(be(U)){we.add(z);continue}re(N(w),z);let G=V(z),ye=(kn=G.toolCall)!=null?kn:{id:z,status:"pending"};ye.name=U!=null?U:ye.name,ye.status="running",w.parameters!==void 0?ye.args=w.parameters:w.args!==void 0&&(ye.args=w.args),ye.startedAt=(Xr=ye.startedAt)!=null?Xr:X((Jn=w.startedAt)!=null?Jn:w.timestamp),ye.completedAt=void 0,ye.durationMs=void 0,G.toolCall=ye,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(xr=(wt=He(w,!1))!=null?wt:He(w,!0))!=null?xr:`tool-${l()}`;if(we.has(z))continue;let U=V(z),G=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Dr=w.startedAt)!=null?Dr:w.timestamp);let ye=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";ye&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ye))),G.status="running",U.toolCall=G,U.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Ln=_e==null?void 0:_e.executionId)!=null?Ln:w.executionId,iteration:(Xo=_e==null?void 0:_e.iteration)!=null?Xo:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(Yr=(Nr=He(w,!1))!=null?Nr:He(w,!0))!=null?Yr:`tool-${l()}`;if(we.has(z)){we.delete(z);continue}let U=V(z),G=(Zr=U.toolCall)!=null?Zr:{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=X((So=w.completedAt)!=null?So:w.timestamp);let ye=(To=w.duration)!=null?To:w.executionTime;if(typeof ye=="number")G.durationMs=ye;else{let st=(eo=G.startedAt)!=null?eo:Date.now();G.durationMs=Math.max(0,((bt=G.completedAt)!=null?bt:Date.now())-st)}U.toolCall=G,U.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(An=U.agentMetadata)!=null?An:{executionId:(Dn=_e==null?void 0:_e.executionId)!=null?Dn:w.executionId,iteration:(Nn=_e==null?void 0:_e.iteration)!=null?Nn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(Ct=z!=null?z:w.toolId)!=null?Ct:`local-${l()}`,G=V(U),ye=w.toolName,_e=w.origin==="webmcp"&&!Oo(ye)?`webmcp:${ye}`:ye,gt=Oo(_e),st=(Xn=G.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=_e,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Or=st.startedAt)!=null?Or:X((to=(On=w.startedAt)!=null?On:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,G.toolCall=st,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:(Fn=G.agentMetadata)==null?void 0:Fn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(tt==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let G=f;G&&(Me==="flow"?(Xe(G),et=G):(G.streaming=!1,g(G)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(tt==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let ye=typeof w.delta=="string"?w.delta:"",_e=((Sn=P.get(z))!=null?Sn:"")+ye;if(P.set(z,_e),_e.trim()==="")continue;let gt=fe(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},$t(gt,_e,ye,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Me==="flow"){let ye=typeof w.delta=="string"?w.delta:"";if(L+=ye,L.trim()==="")continue;let _e=de();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},$t(_e,L,ye,void 0),v=_e;continue}let G=de();G.content+=(Yn=w.delta)!=null?Yn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Pt!=null?Pt:void 0,agentName:ee==null?void 0:ee.agentName},v=G,g(G)}else if(tt==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let G=M.get(z);G&&Xe(G),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Me==="flow"?(Xe(U),et=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(tt==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let G=w.error,ye=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Fr=G.message)!=null?Fr:"Step failed"):"Step failed";n({type:"error",error:new Error(ye)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let ye=w.stopReason,_e=(oo=w.result)==null?void 0:oo.response;if(G)ye&&(G.stopReason=ye),_e!=null?Ve(G,_e):G.streaming!==!1&&(K.delete(G.id),pe.delete(G.id),G.streaming=!1,g(G));else{let gt=_e!=null&&_e!=="";if(gt||ye){let st=de();ye&&(st.stopReason=ye),gt?Xe(st,_e):(st.streaming=!1,g(st))}}continue}}else if(tt==="execution_start")Me=w.kind==="flow"?"flow":"agent",nt=!0,Me==="agent"&&(ee={executionId:w.executionId,agentId:(xe=w.agentId)!=null?xe:"virtual",agentName:(Pn=w.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Ae;if(z!==Ae){if(ee&&(ee.currentIteration=z),Cn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Ae=z}Pt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let G=w.id;(!G||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===G)&&(U.stopReason=z,g(U))}Pt===w.id&&(Pt=null)}else if(tt==="media_start"){let z=String(w.id);qe.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(tt==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(tt==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let G=(_r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?_r:"application/octet-stream",ye=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(ye)gt={type:"media",data:ye,mediaType:G};else if(_e){let dn=G.toLowerCase();gt={type:dn==="image"||dn.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:G}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Rn=[];for(let dn of Ps){if(!dn||typeof dn!="object")continue;let pn=dn,Lo=typeof pn.type=="string"?pn.type:void 0,Ur=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",Tn=null,fn="";if(Lo==="media"){let jn=typeof pn.data=="string"?pn.data:void 0;if(!jn)continue;fn=Ur.length>0?Ur:"application/octet-stream",Tn=`data:${fn};base64,${jn}`}else if(Lo==="image-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else if(Lo==="file-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else continue;if(Tn)if(Lo==="image-url"||fn.startsWith("image/"))Rn.push({type:"image",image:Tn,...fn.includes("/")?{mimeType:fn}:{}});else if(fn.startsWith("audio/"))Rn.push({type:"audio",audio:Tn,mimeType:fn});else if(fn.startsWith("video/"))Rn.push({type:"video",video:Tn,mimeType:fn});else{let jn=fn||"application/octet-stream";Rn.push({type:"file",data:Tn,mimeType:jn,filename:Wh(jn)})}}if(Rn.length>0){let dn=l(),pn=st,Ur={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${dn}`:String(dn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:dn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ae}};g(Ur);let Tn=f;Tn&&(Tn.streaming=!1,g(Tn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Me;z==="agent"&&ee&&(ee.status=w.success?"complete":"error",ee.completedAt=X(w.completedAt),ee.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Xe(U):(U.streaming=!1,g(U)),f=null),T=null,L="",et=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ee==null?void 0:ee.agentId)!=null?Er:"virtual",executionId:(Mr=($r=w.executionId)!=null?$r:ee==null?void 0:ee.executionId)!=null?Mr:"",toolName:(cr=w.toolName)!=null?cr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let z=(_n=w.approvalId)!=null?_n:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:($n=ee==null?void 0:ee.agentId)!=null?$n:"virtual",executionId:(pr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?pr:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(bn=w.description)!=null?bn:`Execute ${(jr=w.toolName)!=null?jr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="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:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ee==null?void 0:ee.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ee==null?void 0:ee.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=w.artifactType,U=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),oe.set(U,{markdown:"",title:G}),!se.has(U)){se.add(U);let ye={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:G,artifactType:z,status:"streaming"}})};le.set(U,ye),g(ye)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let G=oe.get(z);G&&(G.markdown+=U)}else if(tt==="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(tt==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=le.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(G.props){G.props.status="complete";let ye=oe.get(z);ye!=null&&ye.markdown&&(G.props.markdown=ye.markdown)}U.rawContent=JSON.stringify(G)}catch{}oe.delete(z),g(U),le.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),G=z.role,_e={id:U,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:l()};if(g(_e),_e.rawContent)try{let gt=JSON.parse(_e.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&se.add(st)}catch{}f=null,x.current=null,K.delete(U),pe.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(tt==="dispatch_error"){let U=(In=w.message)!=null?In:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Te=a.split(`
12
12
 
13
13
  `);a=(hn=Te.pop())!=null?hn:"";for(let De of Te){let Pe=De.split(`
14
14
  `),Ne="message",Ge="";for(let ce of Pe)ce.startsWith("event:")?Ne=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ge+=ce.replace("data:","").trim());if(!Ge)continue;let it;try{it=JSON.parse(Ge)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let It=Ne!=="message"?Ne:(yr=it.type)!=null?yr:"message";if((br=this.onSSEEvent)==null||br.call(this,It,it),this.parseSSEEvent){x.current=f;let ce=await this.handleCustomSSEEvent(it,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),ce)continue}J.push({payloadType:It,payload:it}),dt()}}dt()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var $a="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _h(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ja(e){return{type:"text",text:e}}function $h(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 jh(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 Uh(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 cm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Kr=[...cm,...qh];function zh(e){return cm.includes(e)||e.startsWith("image/")}function Ua(e){return zh(e.type)}async function dm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(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 pm(e,t=Kr,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 Vh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Vh(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"}tl();var mm=16e3,Kh=24e3,Gh=4096,Jh=1380533830;function Xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jh?new Uint8Array(e,44):new Uint8Array(e)}function Qh(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 Ys=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 l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:mm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:mm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ys(Kh);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Qh(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}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(Gh,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.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=Xh(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 $o=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 jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(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 nl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return jo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if($o.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return nl(e),!0}catch{return!1}}function Zs(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 Uo=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):Zs(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 l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.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 bs=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 rl(e){if(!e)return"";let t=Yh(e);return gm(t!==null?t:e)}function Yh(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 gm(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`