@runtypelabs/persona 3.34.0 → 3.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ ${t}`:"")+(e.description?`
6
6
  ${e.description}`:"");return window.confirm(n)},Vg=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)}},Kg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Gg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Jg,ARR as Qg,OBJ as Xg,STR as Yg}from"partial-json";var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Hr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Da="ask_user_question",zs=8,ls="data-persona-ask-sheet-for",Zg="Other",ef="Other\u2026",mu="Type your own answer here",gu="Send",tf="Next",nf="Back",rf="Submit all",of="Skip",sf=3,zi="data-ask-current-index",Vi="data-ask-question-count",fu="data-ask-answers",Ki="data-ask-grouped",hu="data-ask-layout",af=e=>e.layout==="pills"?"pills":"rows",lf=e=>e.getAttribute(hu)==="pills"?"pills":"rows",uu=!1,bu=e=>e.replace(/["\\]/g,"\\$&"),mo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Da,Oa=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},go=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 s=r.join(""),o=Jg(s,Yg|Xg|Qg);if(o&&typeof o=="object")return{payload:o,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&&!uu&&(uu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},cf=e=>{var t;return(t=Vs(e)[0])!=null?t:null},df=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},yu=(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))},xu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},pf=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=xu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},uf=e=>{let n=h("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},mf=(e,t,n,r)=>{var p,u,f;let o=h("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");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<sf;g++)o.appendChild(uf(r));return o}if(d.forEach((g,v)=>{o.appendChild(pf(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Zg:ef;if(r==="rows"){let v=h("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 y=h("span","persona-ask-row-content"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:mu,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),y.appendChild(w),v.appendChild(y);let A=xu(r,a,d.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("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=(f=t.freeTextLabel)!=null?f:g,o.appendChild(v)}}return o},vu=(e,t)=>{var o,a;let r=h("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 s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:mu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:gu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},gf=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:gu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ff=(e,t,n)=>{var l,p,u,f;let r=h("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 s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:nf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:of,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("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:rf:(f=n.nextLabel)!=null?f:tf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Oo=e=>{let t=e.getAttribute(fu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},wu=(e,t)=>{e.setAttribute(fu,JSON.stringify(t))},dr=e=>{var n;let t=Number((n=e.getAttribute(zi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},hf=(e,t)=>{e.setAttribute(zi,String(Math.max(0,Math.floor(t))))},cs=e=>{var n;let t=Number((n=e.getAttribute(Vi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},fo=e=>e.getAttribute(Ki)==="true",bf=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},yf=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=go(t),r=Vs(n),s=Oo(e),o={},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(s,d)&&(o[l]=s[d]))}),o},Cu=e=>{let t=Oo(e),n=dr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).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=""},Au=e=>{if(!fo(e))return;let t=Oo(e),n=dr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);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}},Gi=(e,t,n)=>{let r=Oa(n),s=lf(e),{payload:o,complete:a}=go(t),i=fo(e),d=dr(e),l=cs(e),p=i?df(o,d):cf(o),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let D=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=D,v.classList.toggle("persona-ask-question-skeleton",!D&&!a)}let y=e.querySelector('[data-ask-pill-list="true"]');if(y){let D=mf(p,r,a,s);y.replaceWith(D)}if(s!=="rows"){let D=e.querySelector('[data-ask-free-text-row="true"]');D&&D.replaceWith(vu(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(gf(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let D=ff(d,l,r);A?A.replaceWith(D):e.appendChild(D)}else A&&A.remove();Cu(e),Au(e)},xf=(e,t,n)=>{let r=Oa(t),s=af(r),o=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=bf(e,a),p=d?yf(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ls,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(Vi,String(i)),u.setAttribute(zi,String(p)),u.setAttribute(Ki,d?"true":"false"),u.setAttribute(hu,s),wu(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`),yu(u,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let w=h("div",s==="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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),s!=="rows"&&u.appendChild(vu(r,s)),Gi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},vf=(e,t,n)=>{let{payload:r}=go(t),s=Math.max(1,Vs(r).length);s>cs(e)&&(e.setAttribute(Vi,String(s)),s>1&&!fo(e)&&e.setAttribute(Ki,"true")),Gi(e,t,n)},wf=(e,t)=>{let n=h("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=Oa(t);yu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=go(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Ks=(e,t,n)=>{if(!n||!mo(e)||Oa(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ls}]`).forEach(l=>{l.getAttribute(ls)!==s&&l.remove()});let a=n.querySelector(`[${ls}="${bu(s)}"]`);if(a){vf(a,e,t);return}let{payload:i}=go(e),d=xf(e,t,i);n.appendChild(d)},No=(e,t)=>{if(!e)return;let n=t?`[${ls}="${bu(t)}"]`:`[${ls}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Ji=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),ho=(e,t)=>{let n=Oo(e),r=dr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,wu(e,n),Cu(e),Au(e)},Fa=(e,t,n,r)=>{let s=cs(e),o=Math.max(0,Math.min(s-1,r));hf(e,o),Gi(e,t,n)};var Br="suggest_replies";var Su={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},Qi={name:Br,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 \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Su,origin:"sdk",annotations:{readOnlyHint:!0}},Xi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_a=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Br},Tu=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(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.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},Yi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!_a(r))continue;let s=Tu((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Eu=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 Mu={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 \u2014 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},ku={name:Da,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 \u2014 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:Mu,origin:"sdk",annotations:{readOnlyHint:!0}},$a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(ku),Eu(e)&&t.push(Qi),t};import{parse as Lu,STR as Pu,OBJ as Iu}from"partial-json";var Ua=e=>e.replace(/\\n/g,`
7
7
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ds=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)}},Cf=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Ru=e=>e.status==="complete"?Cf(e):e.status==="pending"?"Waiting":"",Af=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o: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 Wu=e=>e.status==="complete"?Af(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ja(t)},qa=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ja(t)},Zi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},za=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Gs(r,n.slice(o,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"]),o=a.index+a[0].length;return o<n.length&&Gs(r,n.slice(o),[]),r},Gs=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Sf=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).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 s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Fo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},el=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tl=()=>{var t;let e=Sf();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)}},nl=()=>{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 s=Lu(n,Pu|Iu);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ua(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ua(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Tf=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ua(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ua(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Lu(o,Pu|Iu),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},rl=()=>{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 Va=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Ef="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Mf(e){var o,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 s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ol=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 kf(e){switch(e){case"json":return nl;case"regex-json":return tl;case"xml":return rl;default:return el}}var Hu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lf(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 s=Hu(n);if(!Hu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Fo(e);return Fo(t)!==null&&a===null?t:e}var ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Ef,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:kf(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/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 o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,""))||Ka}/v1/client/feedback`}async sendFeedback(t){var o,a;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 s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.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.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,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(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ol).map(P=>{var I,S,R;return{id:P.id,role:P.role,content:(R=(S=(I=P.contentParts)!=null?I:P.llmContent)!=null?S:P.rawContent)!=null?R:P.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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?pu(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,A=!1,D=null,M;for(let P=0;;P++){let S={...u,...g&&(A||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&P===0&&g){let R=await M.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}D=R!=null?R:{error:"Chat request failed"}}break}if(!M.ok){let P=D!=null?D:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(M.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let I=new Error(P.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!M.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.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 s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;s&&(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(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,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:o(),...p!==void 0&&{partId:p}};return r.current=u,s(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,s(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,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(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 Wt,ln,nr,Sr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=W=>{let de=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,De=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Je=W.tools?W.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...W,reasoning:de,toolCall:De,tools:Je}},u=W=>{if(W.role!=="assistant"||W.variant)return!0;let de=Array.isArray(W.contentParts)&&W.contentParts.length>0,De=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||de||De||!!W.stopReason},f=W=>{u(W)&&n({type:"message",message:p(W)})},g=null,v=null,y={current:null},w={current:null},A=!1,D=new Map,M=new Map,P=new Map,I=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},F=(W,de,De="")=>`${W}::${de}::${De}`,N=(W,de)=>`${W}::${de}::`,E=(W,de,De,Je)=>{let Fe=F(W,de,De),$e=P.get(Fe);if($e)return $e;let st=De?`-${De}`:"",Lt={id:`nested-${W}-${de}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Je,parentToolId:W,parentStepId:de}};return P.set(Fe,Lt),f(Lt),Lt},U=W=>{if(W==null)return null;try{return String(W)}catch{return null}},q=W=>{var de,De,Je,Fe,$e;return U(($e=(Fe=(Je=(De=(de=W.stepId)!=null?de:W.step_id)!=null?De:W.step)!=null?Je:W.parentId)!=null?Fe:W.flowStepId)!=null?$e:W.flow_step_id)},re=W=>{var de,De,Je,Fe,$e,st,Lt;return U((Lt=(st=($e=(Fe=(Je=(De=(de=W.callId)!=null?de:W.call_id)!=null?De:W.requestId)!=null?Je:W.request_id)!=null?Fe:W.toolCallId)!=null?$e:W.tool_call_id)!=null?st:W.stepId)!=null?Lt:W.step_id)},Me=r,qe=!1,we=()=>{if(g)return g;let W;return!qe&&Me?(W=Me,qe=!0):Me&&w.current?W=`${Me}_${w.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Ie=(W,de)=>{S.lastId=de,W&&S.byStep.set(W,de)},he=(W,de)=>{var $e;let De=($e=W.reasoningId)!=null?$e:W.id,Je=q(W);if(De){let st=String(De);return Ie(Je,st),st}if(Je){let st=S.byStep.get(Je);if(st)return S.lastId=st,st}if(S.lastId&&!de)return S.lastId;if(!de)return null;let Fe=`reason-${l()}`;return Ie(Je,Fe),Fe},ke=W=>{let de=D.get(W);if(de)return de;let De={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:W,status:"streaming",chunks:[]}};return D.set(W,De),f(De),De},Re=(W,de)=>{R.lastId=de,W&&R.byCall.set(W,de)},ce=new Set,Q=new Map,ne=new Set,le=new Map,me=W=>{if(!W)return!1;let de=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},V=(W,de)=>{var $e;let De=($e=W.toolId)!=null?$e:W.id,Je=re(W);if(De){let st=String(De);return Re(Je,st),st}if(Je){let st=R.byCall.get(Je);if(st)return R.lastId=st,st}if(R.lastId&&!de)return R.lastId;if(!de)return null;let Fe=`tool-${l()}`;return Re(Je,Fe),Fe},se=W=>{let de=M.get(W);if(de)return de;let De={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:W,status:"pending"}};return M.set(W,De),f(De),De},We=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let de=Number(W);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let De=Date.parse(W);if(!Number.isNaN(De))return De}return Date.now()},X=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Z=new Map,ae=new Map,Ce=new Map,Ye=new Map,xe=null,ge=(W,de,De)=>{var Lt;let Je=Ce.get(W);Je||(Je=[],Ce.set(W,Je));let Fe=0,$e=Je.length;for(;Fe<$e;){let zt=Fe+$e>>>1;Je[zt].seq<de?Fe=zt+1:$e=zt}((Lt=Je[Fe])==null?void 0:Lt.seq)===de?Je[Fe]={seq:de,text:De}:Je.splice(Fe,0,{seq:de,text:De});let st="";for(let zt=0;zt<Je.length;zt++)st+=Je[zt].text;return st},Ge=(W,de)=>{let De=X(de),Je=ae.get(W.id),Fe=Lf(Je,De);W.rawContent=Fe;let $e=Z.get(W.id),st=yt=>{var ve;let it=(ve=W.content)!=null?ve:"";yt.trim()!==""&&(it.trim().length===0||yt.startsWith(it)||yt.trimStart().startsWith(it.trim()))&&(W.content=yt)},Lt=()=>{var yt;if($e){let it=(yt=$e.close)==null?void 0:yt.call($e);it instanceof Promise&&it.catch(()=>{})}Z.delete(W.id),ae.delete(W.id),W.streaming=!1,f(W)};if(!$e){st(De),Lt();return}let zt=Fo(Fe);if(zt!==null&&zt.trim()!==""){st(zt),Lt();return}let Yt=yt=>{var ie;let it=typeof yt=="string"?yt:(ie=yt==null?void 0:yt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let ve=$e.getExtractedText();return ve!==null&&ve.trim()!==""?ve:De},K;try{K=$e.processChunk(Fe)}catch{st(De),Lt();return}if(K instanceof Promise){K.then(yt=>{st(Yt(yt)),Lt()}).catch(()=>{st(De),Lt()});return}st(Yt(K)),Lt()},Be=[],z=!1,pe,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,pe()}))},Tt=new Va((W,de)=>{Be.push({payloadType:W,payload:de}),rt()}),te=null,ze=new Map,On=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(pe=()=>{var W,de,De,Je,Fe,$e,st,Lt,zt,Yt,K,yt,it,ve,ie,tt,en,Vt,Ln,vn,ut,Et,Ze,jt,cn,Cn,An,bn,Tr,Ct,Un,jn,Or,gr,xt,Ao,Er,So,Nn,zo,Qr,Nr,At,qn,zn,Pn,kt,rr,or,Vn,Xr,Fr,Yr,Kn,Ht,In,sr,Zr,_r,eo,Mr,Gn,fr,gt,tn,nn,Jn,to,be,hr,ar,_,Vo,kr,$r,Ur,Lr,br,Ss,Qn,Xn,yr,xr,To,jr,Sn,Pr,Ko,Eo,Go,ya,Jo,xa,Qo,bt,Ts,ir,Fn,va,wa,Xo,qr,Es,no,Ms,ks,Ls,Ps,_n,Yo,Ir,Rr,Is,Ca,Rs,Ws,Mo,Aa,Sa,Ta,Ea,Oi,ko,ro,Ma,Hs,oo,ka,Bs,so,Ds,La,zr,Pa,ao,Bt,Zo,es;for(let Lo=0;Lo<Be.length;Lo++){let Ue=Be[Lo].payloadType,C=Be[Lo].payload;if(Ue==="reason_start"){let $=(W=he(C,!0))!=null?W:`reason-${l()}`,k=ke($);k.reasoning=(de=k.reasoning)!=null?de:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(Je=k.reasoning.startedAt)!=null?Je:We((De=C.startedAt)!=null?De:C.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",f(k)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=($e=(Fe=he(C,!1))!=null?Fe:he(C,!0))!=null?$e:`reason-${l()}`,k=ke($);k.reasoning=(st=k.reasoning)!=null?st:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(zt=k.reasoning.startedAt)!=null?zt:We((Lt=C.startedAt)!=null?Lt:C.timestamp);let Y=(yt=(K=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?K:C.delta)!=null?yt:"";if(Y&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let G=ge($,oe,String(Y));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=We((it=C.completedAt)!=null?it:C.timestamp);let oe=(ve=k.reasoning.startedAt)!=null?ve:Date.now();k.reasoning.durationMs=Math.max(0,((ie=k.reasoning.completedAt)!=null?ie:Date.now())-oe)}k.streaming=k.reasoning.status!=="complete",f(k)}else if(Ue==="reason_complete"){let $=(en=(tt=he(C,!1))!=null?tt:he(C,!0))!=null?en:`reason-${l()}`,k=D.get($);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=We((Vt=C.completedAt)!=null?Vt:C.timestamp);let oe=(Ln=k.reasoning.startedAt)!=null?Ln:Date.now();k.reasoning.durationMs=Math.max(0,((vn=k.reasoning.completedAt)!=null?vn:Date.now())-oe),k.streaming=!1,f(k)}let Y=q(C);Y&&S.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(ut=V(C,!0))!=null?ut:`tool-${l()}`,k=(Et=C.toolName)!=null?Et:C.name;if(me(k)){ce.add($);continue}let Y=se($),oe=(Ze=Y.toolCall)!=null?Ze:{id:$,status:"pending"};oe.name=k!=null?k:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:We((jt=C.startedAt)!=null?jt:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(Y.agentMetadata={executionId:(Cn=G==null?void 0:G.executionId)!=null?Cn:C.executionId,iteration:(An=G==null?void 0:G.iteration)!=null?An:C.iteration}),f(Y)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(Tr=(bn=V(C,!1))!=null?bn:V(C,!0))!=null?Tr:`tool-${l()}`;if(ce.has($))continue;let k=se($),Y=(Ct=k.toolCall)!=null?Ct:{id:$,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:We((Un=C.startedAt)!=null?Un:C.timestamp);let oe=(xt=(gr=(Or=C.text)!=null?Or:C.delta)!=null?gr:C.message)!=null?xt:"";oe&&(Y.chunks=(Ao=Y.chunks)!=null?Ao:[],Y.chunks.push(String(oe))),Y.status="running",k.toolCall=Y,k.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(Nn=k.agentMetadata)!=null?Nn:{executionId:(Er=G==null?void 0:G.executionId)!=null?Er:C.executionId,iteration:(So=G==null?void 0:G.iteration)!=null?So:C.iteration}),f(k)}else if(Ue==="tool_complete"){let $=(Qr=(zo=V(C,!1))!=null?zo:V(C,!0))!=null?Qr:`tool-${l()}`;if(ce.has($)){ce.delete($);continue}let k=se($),Y=(Nr=k.toolCall)!=null?Nr:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=We((At=C.completedAt)!=null?At:C.timestamp);let oe=(qn=C.duration)!=null?qn:C.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Ne=(zn=Y.startedAt)!=null?zn:Date.now();Y.durationMs=Math.max(0,((Pn=Y.completedAt)!=null?Pn:Date.now())-Ne)}k.toolCall=Y,k.streaming=!1;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(or=k.agentMetadata)!=null?or:{executionId:(kt=G==null?void 0:G.executionId)!=null?kt:C.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:C.iteration}),f(k);let Ee=re(C);Ee&&R.byCall.delete(Ee)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(Vn=$!=null?$:C.toolId)!=null?Vn:`local-${l()}`,Y=se(k),oe=C.toolName,G=is(oe),Ee=(Xr=Y.toolCall)!=null?Xr:{id:k,status:"pending"};Ee.name=oe,Ee.args=C.parameters,Ee.status=G?"running":"complete",Ee.chunks=(Fr=Ee.chunks)!=null?Fr:[],Ee.startedAt=(Kn=Ee.startedAt)!=null?Kn:We((Yr=C.startedAt)!=null?Yr:C.timestamp),G?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(Ht=Ee.completedAt)!=null?Ht:Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=C.executionId)!=null?sr:(In=Y.agentMetadata)==null?void 0:In.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(Y)}else if(Ue==="text_start"){if((Zr=C.toolContext)!=null&&Zr.toolId)continue;let $=C.partId;if($!==void 0&&w.current!==null&&$!==w.current){let k=g;k&&(k.streaming=!1,f(k),xe=k,g=null,A=!0)}$!==void 0&&(w.current=$)}else if(Ue==="text_end"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=g;$&&($.streaming=!1,f($),xe=$,g=null,A=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((Mr=(eo=C.id)!=null?eo:Y.stepId)!=null?Mr:`step-${l()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",et=`${Y.toolId}::${Ne}`,Rt=I.get(et);if(lt!==""&&Rt!==void 0&&Rt!==""&&Rt!==lt){let at=P.get(F(Y.toolId,Ne,Rt));at&&at.streaming!==!1&&(at.streaming=!1,f(at))}lt!==""&&I.set(et,lt);let _t=E(Y.toolId,Ne,lt,Y.executionId),un=(tn=(gt=(fr=(Gn=C.text)!=null?Gn:C.delta)!=null?fr:C.content)!=null?gt:C.chunk)!=null?tn:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),C.isComplete&&(_t.streaming=!1,f(_t));continue}let oe=C.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Ne=g;Ne&&(Ne.streaming=!1,f(Ne),xe=Ne,g=null,A=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(nn=Ye.get(oe))!=null?nn:we();oe!==void 0&&(G.partId||(G.partId=oe),Ye.set(oe,G));let Ee=(hr=(be=(to=(Jn=C.text)!=null?Jn:C.delta)!=null?to:C.content)!=null?be:C.chunk)!=null?hr:"";if(Ee){let Ne=typeof C.seq=="number"?C.seq:void 0,lt=oe!=null?oe:G.id,et=Ne!==void 0?ge(lt,Ne,String(Ee)):((ar=ae.get(G.id))!=null?ar:"")+Ee;G.rawContent=et,Z.has(G.id)||Z.set(G.id,this.createStreamParser());let Rt=Z.get(G.id),_t=et.trim().startsWith("{")||et.trim().startsWith("[");if(_t&&ae.set(G.id,et),Rt.__isPlainTextParser===!0){G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G);continue}let at=Rt.processChunk(et);if(at instanceof Promise)at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")G.content=Zt,f(G);else if(!_t&&!et.trim().startsWith("<")){let wn=g,Jt=wn&&wn.id===G.id?wn:G;Jt.id===G.id&&(Jt.content=Ne!==void 0?et:Jt.content+Ee,ae.delete(Jt.id),Z.delete(Jt.id),Jt.rawContent=void 0,f(Jt))}}).catch(()=>{G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G)});else{let ft=typeof at=="string"?at:(_=at==null?void 0:at.text)!=null?_:null;ft!==null&&ft.trim()!==""?(G.content=ft,f(G)):!_t&&!et.trim().startsWith("<")&&(G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G))}}if(C.isComplete){let Ne=(kr=(Vo=C.result)==null?void 0:Vo.response)!=null?kr:G.content;if(Ne){let lt=ae.get(G.id),et=lt!=null?lt:X(Ne);G.rawContent=et;let Rt=Z.get(G.id),_t=null,un=!1;if(Rt&&(_t=Rt.getExtractedText(),_t===null&&(_t=Fo(et)),_t===null)){let at=Rt.processChunk(et);at instanceof Promise?(un=!0,at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null){let wn=g;wn&&wn.id===G.id&&(wn.content=Zt,wn.streaming=!1,Z.delete(wn.id),ae.delete(wn.id),f(wn))}})):_t=typeof at=="string"?at:($r=at==null?void 0:at.text)!=null?$r:null}if(!un){_t!==null&&_t.trim()!==""?G.content=_t:ae.has(G.id)||(G.content=X(Ne));let at=Z.get(G.id);if(at){let ft=(Ur=at.close)==null?void 0:Ur.call(at);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Ue==="step_complete"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((br=(Lr=C.id)!=null?Lr:Y.stepId)!=null?br:"");if(Ne){let lt=N(Y.toolId,Ne);for(let[et,Rt]of P)et.startsWith(lt)&&Rt.streaming!==!1&&(Rt.streaming=!1,f(Rt));I.delete(`${Y.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(A){if(g!==null){let et=g;oe&&(et.stopReason=oe),Z.delete(et.id),ae.delete(et.id),et.streaming!==!1&&(et.streaming=!1,f(et))}let Ne=(Ss=C.result)==null?void 0:Ss.response,lt=xe;lt&&(oe&&(lt.stopReason=oe),Ne!=null?Ge(lt,Ne):(Z.delete(lt.id),ae.delete(lt.id))),xe=null;continue}let G=(Qn=C.result)==null?void 0:Qn.response,Ee=we();if(oe&&(Ee.stopReason=oe),G!=null){let Ne=Z.get(Ee.id),lt=!1,et=!1;if(Ne){let Rt=Ne.getExtractedText(),_t=ae.get(Ee.id),un=_t!=null?_t:X(G);if(Ee.rawContent=un,Rt!==null&&Rt.trim()!=="")Ee.content=Rt,lt=!0;else{let at=Fo(un);if(at!==null)Ee.content=at,lt=!0;else{let ft=Ne.processChunk(un);if(ft instanceof Promise)et=!0,ft.then(Zt=>{var wn;let Ke=typeof Zt=="string"?Zt:(wn=Zt==null?void 0:Zt.text)!=null?wn:null;if(Ke!==null&&Ke.trim()!==""){let Jt=g;Jt&&Jt.id===Ee.id&&(Jt.content=Ke,Jt.streaming=!1,Z.delete(Jt.id),ae.delete(Jt.id),f(Jt))}else{let Jt=Ne.getExtractedText(),yn=g;yn&&yn.id===Ee.id&&(Jt!==null&&Jt.trim()!==""?yn.content=Jt:ae.has(yn.id)||(yn.content=X(G)),yn.streaming=!1,Z.delete(yn.id),ae.delete(yn.id),f(yn))}});else{let Zt=typeof ft=="string"?ft:(Xn=ft==null?void 0:ft.text)!=null?Xn:null;if(Zt!==null&&Zt.trim()!=="")Ee.content=Zt,lt=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Ee.content=Ke,lt=!0)}}}}}if(!et){if(!Ee.rawContent){let Rt=ae.get(Ee.id);Ee.rawContent=Rt!=null?Rt:X(G)}if(!lt&&!ae.has(Ee.id)&&(Ee.content=X(G)),Ne){let Rt=(yr=Ne.close)==null?void 0:yr.call(Ne);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}}else Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}else if(Ue==="flow_complete"){let $=(xr=C.result)==null?void 0:xr.response;if(A){if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}}else if($!=null){let k=we(),Y=ae.get(k.id),oe=Y!=null?Y:X($);k.rawContent=oe;let G=X($),Ee=Z.get(k.id);if(Ee){let et=Fo(oe);if(et!==null)G=et;else{let Rt=Ee.processChunk(oe);Rt instanceof Promise&&Rt.then(un=>{var ft;let at=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;at!==null&&(k.content=at,k.streaming=!1,f(k))});let _t=Ee.getExtractedText();_t!==null&&(G=_t)}}Z.delete(k.id),ae.delete(k.id);let Ne=G!==k.content,lt=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||lt)&&f(k)}else if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")te={executionId:C.executionId,agentId:(To=C.agentId)!=null?To:"virtual",agentName:(jr=C.agentName)!=null?jr:"",status:"running",currentIteration:0,maxTurns:(Sn=C.maxTurns)!=null?Sn:1,startedAt:We(C.startedAt)};else if(Ue==="agent_iteration_start"){if(te&&(te.currentIteration=C.iteration),On==="separate"&&C.iteration>1){let $=g;$&&($.streaming=!1,f($),ze.set(C.iteration-1,$),g=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=we();$.content+=(Pr=C.delta)!=null?Pr:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:te==null?void 0:te.agentName},v=$,f($)}else if(C.contentType==="thinking"){let $=(Ko=C.turnId)!=null?Ko:`agent-think-${C.iteration}`,k=ke($);k.reasoning=(Eo=k.reasoning)!=null?Eo:{id:$,status:"streaming",chunks:[]},k.reasoning.chunks.push((Go=C.delta)!=null?Go:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(k)}else if(C.contentType==="tool_input"){let $=(ya=C.toolCallId)!=null?ya:R.lastId;if($){let k=M.get($);k!=null&&k.toolCall&&(k.toolCall.chunks=(Jo=k.toolCall.chunks)!=null?Jo:[],k.toolCall.chunks.push((xa=C.delta)!=null?xa:""),f(k))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let oe=D.get($);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=We(C.completedAt);let G=(Qo=oe.reasoning.startedAt)!=null?Qo:Date.now();oe.reasoning.durationMs=Math.max(0,((bt=oe.reasoning.completedAt)!=null?bt:Date.now())-G),oe.streaming=!1,f(oe)}}let k=C.stopReason,Y=g!=null?g:v;if(k&&Y!==null){let oe=C.turnId;(!oe||((Ts=Y.agentMetadata)==null?void 0:Ts.turnId)===oe)&&(Y.stopReason=k,f(Y))}}else if(Ue==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let $=(ir=C.toolCallId)!=null?ir:`agent-tool-${l()}`;Re(re(C),$);let k=se($),Y=(Fn=k.toolCall)!=null?Fn:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(wa=(va=C.toolName)!=null?va:C.name)!=null?wa:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=We((Xo=C.startedAt)!=null?Xo:C.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(k)}else if(Ue==="agent_tool_delta"){let $=(qr=C.toolCallId)!=null?qr:R.lastId;if($){let k=(Es=M.get($))!=null?Es:se($);k.toolCall&&(k.toolCall.chunks=(no=k.toolCall.chunks)!=null?no:[],k.toolCall.chunks.push((Ms=C.delta)!=null?Ms:""),k.toolCall.status="running",k.streaming=!0,f(k))}}else if(Ue==="agent_tool_complete"){let $=(ks=C.toolCallId)!=null?ks:R.lastId;if($){let k=(Ls=M.get($))!=null?Ls:se($);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=We((Ps=C.completedAt)!=null?Ps:C.timestamp),k.streaming=!1,f(k);let Y=re(C);Y&&R.byCall.delete(Y)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],k=[];for(let Y of $){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Ee=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,lt="";if(G==="media"){let et=typeof oe.data=="string"?oe.data:void 0;if(!et)continue;lt=Ee.length>0?Ee:"application/octet-stream",Ne=`data:${lt};base64,${et}`}else if(G==="image-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else if(G==="file-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else continue;if(Ne)if(G==="image-url"||lt.startsWith("image/"))k.push({type:"image",image:Ne,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:lt});else if(lt.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:lt});else{let et=lt||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:et,filename:Mf(et)})}}if(k.length>0){let Y=l(),oe=C.toolCallId,Ee={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Ee);let Ne=g;Ne&&(Ne.streaming=!1,f(Ne)),g=null,y.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:$,role:"assistant",content:(_n=C.reflection)!=null?_n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Yo=C.reflection)!=null?Yo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(k)}else if(Ue==="agent_complete"){te&&(te.status=C.success?"complete":"error",te.completedAt=We(C.completedAt),te.stopReason=C.stopReason);let $=g;$&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(Rr=(Ir=C.error)==null?void 0:Ir.message)!=null?Rr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ca=te==null?void 0:te.agentId)!=null?Ca:"virtual",executionId:(Ws=(Rs=C.executionId)!=null?Rs:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Mo=C.toolName)!=null?Mo:"",toolType:C.toolType,description:(Sa=C.description)!=null?Sa:`Execute ${(Aa=C.toolName)!=null?Aa:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(Ta=C.approvalId)!=null?Ta:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ea=te==null?void 0:te.agentId)!=null?Ea:"virtual",executionId:(ko=(Oi=C.executionId)!=null?Oi:te==null?void 0:te.executionId)!=null?ko:"",toolName:(ro=C.toolName)!=null?ro:"",toolType:C.toolType,description:(Hs=C.description)!=null?Hs:`Execute ${(Ma=C.toolName)!=null?Ma:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(oo=C.decision)!=null?oo:"approved",agentId:(ka=te==null?void 0:te.agentId)!=null?ka:"virtual",executionId:(so=(Bs=C.executionId)!=null?Bs:te==null?void 0:te.executionId)!=null?so:"",toolName:(Ds=C.toolName)!=null?Ds:"",description:(La=C.description)!=null?La:"",resolvedAt:Date.now()}};f(Y)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,k=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:k,artifactType:$,title:Y,component:typeof C.component=="string"?C.component:void 0}),le.set(k,{markdown:"",title:Y}),!ne.has(k)){ne.add(k);let oe={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:$,status:"streaming"}})};Q.set(k,oe),f(oe)}}else if(Ue==="artifact_delta"){let $=String(C.id),k=typeof C.delta=="string"?C.delta:String((zr=C.delta)!=null?zr:"");n({type:"artifact_delta",id:$,artDelta:k});let Y=le.get($);Y&&(Y.markdown+=k)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let k=Q.get($);if(k){k.streaming=!1;try{let Y=JSON.parse((Pa=k.rawContent)!=null?Pa:"{}");if(Y.props){Y.props.status="complete";let oe=le.get($);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete($),f(k),Q.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let k=String((ao=$.id)!=null?ao:`msg-${l()}`),Y=$.role,G={id:k,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(f(G),G.rawContent)try{let Ee=JSON.parse(G.rawContent),Ne=(Bt=Ee==null?void 0:Ee.props)==null?void 0:Bt.artifactId;typeof Ne=="string"&&ne.add(Ne)}catch{}g=null,y.current=null,Z.delete(k),ae.delete(k)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let k=(Zo=C.message)!=null?Zo:C.error;k!=null&&k!==""&&($=new Error(String(k)))}else if(Ue==="step_error"||Ue==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?$=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&($=new Error(String((es=k.message)!=null?es:k)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let k=g;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:W,value:de}=await s.read();if(W)break;a+=o.decode(de,{stream:!0});let De=a.split(`
9
+ `).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 s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Fo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},el=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tl=()=>{var t;let e=Sf();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)}},nl=()=>{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 s=Lu(n,Pu|Iu);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ua(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ua(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Tf=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ua(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ua(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Lu(o,Pu|Iu),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},rl=()=>{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 Va=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Ef="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Mf(e){var o,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 s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ol=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 kf(e){switch(e){case"json":return nl;case"regex-json":return tl;case"xml":return rl;default:return el}}var Hu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lf(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 s=Hu(n);if(!Hu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Fo(e);return Fo(t)!==null&&a===null?t:e}var ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Ef,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:kf(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/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 o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,""))||Ka}/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 s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.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.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,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(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ol).map(P=>{var I,S,R;return{id:P.id,role:P.role,content:(R=(S=(I=P.contentParts)!=null?I:P.llmContent)!=null?S:P.rawContent)!=null?R:P.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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?pu(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,A=!1,D=null,M;for(let P=0;;P++){let S={...u,...g&&(A||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&P===0&&g){let R=await M.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}D=R!=null?R:{error:"Chat request failed"}}break}if(!M.ok){let P=D!=null?D:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(M.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let I=new Error(P.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!M.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.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 s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:r.signal},s)}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:o,body:JSON.stringify(s),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 s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;s&&(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(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,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:o(),...p!==void 0&&{partId:p}};return r.current=u,s(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,s(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,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(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 Wt,ln,nr,Sr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=W=>{let de=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,De=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Je=W.tools?W.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...W,reasoning:de,toolCall:De,tools:Je}},u=W=>{if(W.role!=="assistant"||W.variant)return!0;let de=Array.isArray(W.contentParts)&&W.contentParts.length>0,De=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||de||De||!!W.stopReason},f=W=>{u(W)&&n({type:"message",message:p(W)})},g=null,v=null,y={current:null},w={current:null},A=!1,D=new Map,M=new Map,P=new Map,I=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},F=(W,de,De="")=>`${W}::${de}::${De}`,N=(W,de)=>`${W}::${de}::`,E=(W,de,De,Je)=>{let Fe=F(W,de,De),$e=P.get(Fe);if($e)return $e;let st=De?`-${De}`:"",Lt={id:`nested-${W}-${de}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Je,parentToolId:W,parentStepId:de}};return P.set(Fe,Lt),f(Lt),Lt},U=W=>{if(W==null)return null;try{return String(W)}catch{return null}},q=W=>{var de,De,Je,Fe,$e;return U(($e=(Fe=(Je=(De=(de=W.stepId)!=null?de:W.step_id)!=null?De:W.step)!=null?Je:W.parentId)!=null?Fe:W.flowStepId)!=null?$e:W.flow_step_id)},re=W=>{var de,De,Je,Fe,$e,st,Lt;return U((Lt=(st=($e=(Fe=(Je=(De=(de=W.callId)!=null?de:W.call_id)!=null?De:W.requestId)!=null?Je:W.request_id)!=null?Fe:W.toolCallId)!=null?$e:W.tool_call_id)!=null?st:W.stepId)!=null?Lt:W.step_id)},Me=r,qe=!1,we=()=>{if(g)return g;let W;return!qe&&Me?(W=Me,qe=!0):Me&&w.current?W=`${Me}_${w.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Ie=(W,de)=>{S.lastId=de,W&&S.byStep.set(W,de)},he=(W,de)=>{var $e;let De=($e=W.reasoningId)!=null?$e:W.id,Je=q(W);if(De){let st=String(De);return Ie(Je,st),st}if(Je){let st=S.byStep.get(Je);if(st)return S.lastId=st,st}if(S.lastId&&!de)return S.lastId;if(!de)return null;let Fe=`reason-${l()}`;return Ie(Je,Fe),Fe},ke=W=>{let de=D.get(W);if(de)return de;let De={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:W,status:"streaming",chunks:[]}};return D.set(W,De),f(De),De},Re=(W,de)=>{R.lastId=de,W&&R.byCall.set(W,de)},ce=new Set,Q=new Map,ne=new Set,le=new Map,me=W=>{if(!W)return!1;let de=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},V=(W,de)=>{var $e;let De=($e=W.toolId)!=null?$e:W.id,Je=re(W);if(De){let st=String(De);return Re(Je,st),st}if(Je){let st=R.byCall.get(Je);if(st)return R.lastId=st,st}if(R.lastId&&!de)return R.lastId;if(!de)return null;let Fe=`tool-${l()}`;return Re(Je,Fe),Fe},se=W=>{let de=M.get(W);if(de)return de;let De={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:W,status:"pending"}};return M.set(W,De),f(De),De},We=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let de=Number(W);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let De=Date.parse(W);if(!Number.isNaN(De))return De}return Date.now()},X=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Z=new Map,ae=new Map,Ce=new Map,Ye=new Map,xe=null,ge=(W,de,De)=>{var Lt;let Je=Ce.get(W);Je||(Je=[],Ce.set(W,Je));let Fe=0,$e=Je.length;for(;Fe<$e;){let zt=Fe+$e>>>1;Je[zt].seq<de?Fe=zt+1:$e=zt}((Lt=Je[Fe])==null?void 0:Lt.seq)===de?Je[Fe]={seq:de,text:De}:Je.splice(Fe,0,{seq:de,text:De});let st="";for(let zt=0;zt<Je.length;zt++)st+=Je[zt].text;return st},Ge=(W,de)=>{let De=X(de),Je=ae.get(W.id),Fe=Lf(Je,De);W.rawContent=Fe;let $e=Z.get(W.id),st=yt=>{var ve;let it=(ve=W.content)!=null?ve:"";yt.trim()!==""&&(it.trim().length===0||yt.startsWith(it)||yt.trimStart().startsWith(it.trim()))&&(W.content=yt)},Lt=()=>{var yt;if($e){let it=(yt=$e.close)==null?void 0:yt.call($e);it instanceof Promise&&it.catch(()=>{})}Z.delete(W.id),ae.delete(W.id),W.streaming=!1,f(W)};if(!$e){st(De),Lt();return}let zt=Fo(Fe);if(zt!==null&&zt.trim()!==""){st(zt),Lt();return}let Yt=yt=>{var ie;let it=typeof yt=="string"?yt:(ie=yt==null?void 0:yt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let ve=$e.getExtractedText();return ve!==null&&ve.trim()!==""?ve:De},K;try{K=$e.processChunk(Fe)}catch{st(De),Lt();return}if(K instanceof Promise){K.then(yt=>{st(Yt(yt)),Lt()}).catch(()=>{st(De),Lt()});return}st(Yt(K)),Lt()},Be=[],z=!1,pe,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,pe()}))},Tt=new Va((W,de)=>{Be.push({payloadType:W,payload:de}),rt()}),te=null,ze=new Map,On=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(pe=()=>{var W,de,De,Je,Fe,$e,st,Lt,zt,Yt,K,yt,it,ve,ie,tt,en,Vt,Ln,vn,ut,Et,Ze,jt,cn,Cn,An,bn,Tr,Ct,Un,jn,Or,gr,xt,Ao,Er,So,Nn,zo,Qr,Nr,At,qn,zn,Pn,kt,rr,or,Vn,Xr,Fr,Yr,Kn,Ht,In,sr,Zr,_r,eo,Mr,Gn,fr,gt,tn,nn,Jn,to,be,hr,ar,_,Vo,kr,$r,Ur,Lr,br,Ss,Qn,Xn,yr,xr,To,jr,Sn,Pr,Ko,Eo,Go,ya,Jo,xa,Qo,bt,Ts,ir,Fn,va,wa,Xo,qr,Es,no,Ms,ks,Ls,Ps,_n,Yo,Ir,Rr,Is,Ca,Rs,Ws,Mo,Aa,Sa,Ta,Ea,Oi,ko,ro,Ma,Hs,oo,ka,Bs,so,Ds,La,zr,Pa,ao,Bt,Zo,es;for(let Lo=0;Lo<Be.length;Lo++){let Ue=Be[Lo].payloadType,C=Be[Lo].payload;if(Ue==="reason_start"){let $=(W=he(C,!0))!=null?W:`reason-${l()}`,k=ke($);k.reasoning=(de=k.reasoning)!=null?de:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(Je=k.reasoning.startedAt)!=null?Je:We((De=C.startedAt)!=null?De:C.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",f(k)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=($e=(Fe=he(C,!1))!=null?Fe:he(C,!0))!=null?$e:`reason-${l()}`,k=ke($);k.reasoning=(st=k.reasoning)!=null?st:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(zt=k.reasoning.startedAt)!=null?zt:We((Lt=C.startedAt)!=null?Lt:C.timestamp);let Y=(yt=(K=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?K:C.delta)!=null?yt:"";if(Y&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let G=ge($,oe,String(Y));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=We((it=C.completedAt)!=null?it:C.timestamp);let oe=(ve=k.reasoning.startedAt)!=null?ve:Date.now();k.reasoning.durationMs=Math.max(0,((ie=k.reasoning.completedAt)!=null?ie:Date.now())-oe)}k.streaming=k.reasoning.status!=="complete",f(k)}else if(Ue==="reason_complete"){let $=(en=(tt=he(C,!1))!=null?tt:he(C,!0))!=null?en:`reason-${l()}`,k=D.get($);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=We((Vt=C.completedAt)!=null?Vt:C.timestamp);let oe=(Ln=k.reasoning.startedAt)!=null?Ln:Date.now();k.reasoning.durationMs=Math.max(0,((vn=k.reasoning.completedAt)!=null?vn:Date.now())-oe),k.streaming=!1,f(k)}let Y=q(C);Y&&S.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(ut=V(C,!0))!=null?ut:`tool-${l()}`,k=(Et=C.toolName)!=null?Et:C.name;if(me(k)){ce.add($);continue}let Y=se($),oe=(Ze=Y.toolCall)!=null?Ze:{id:$,status:"pending"};oe.name=k!=null?k:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:We((jt=C.startedAt)!=null?jt:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(Y.agentMetadata={executionId:(Cn=G==null?void 0:G.executionId)!=null?Cn:C.executionId,iteration:(An=G==null?void 0:G.iteration)!=null?An:C.iteration}),f(Y)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(Tr=(bn=V(C,!1))!=null?bn:V(C,!0))!=null?Tr:`tool-${l()}`;if(ce.has($))continue;let k=se($),Y=(Ct=k.toolCall)!=null?Ct:{id:$,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:We((Un=C.startedAt)!=null?Un:C.timestamp);let oe=(xt=(gr=(Or=C.text)!=null?Or:C.delta)!=null?gr:C.message)!=null?xt:"";oe&&(Y.chunks=(Ao=Y.chunks)!=null?Ao:[],Y.chunks.push(String(oe))),Y.status="running",k.toolCall=Y,k.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(Nn=k.agentMetadata)!=null?Nn:{executionId:(Er=G==null?void 0:G.executionId)!=null?Er:C.executionId,iteration:(So=G==null?void 0:G.iteration)!=null?So:C.iteration}),f(k)}else if(Ue==="tool_complete"){let $=(Qr=(zo=V(C,!1))!=null?zo:V(C,!0))!=null?Qr:`tool-${l()}`;if(ce.has($)){ce.delete($);continue}let k=se($),Y=(Nr=k.toolCall)!=null?Nr:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=We((At=C.completedAt)!=null?At:C.timestamp);let oe=(qn=C.duration)!=null?qn:C.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Ne=(zn=Y.startedAt)!=null?zn:Date.now();Y.durationMs=Math.max(0,((Pn=Y.completedAt)!=null?Pn:Date.now())-Ne)}k.toolCall=Y,k.streaming=!1;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(or=k.agentMetadata)!=null?or:{executionId:(kt=G==null?void 0:G.executionId)!=null?kt:C.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:C.iteration}),f(k);let Ee=re(C);Ee&&R.byCall.delete(Ee)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(Vn=$!=null?$:C.toolId)!=null?Vn:`local-${l()}`,Y=se(k),oe=C.toolName,G=is(oe),Ee=(Xr=Y.toolCall)!=null?Xr:{id:k,status:"pending"};Ee.name=oe,Ee.args=C.parameters,Ee.status=G?"running":"complete",Ee.chunks=(Fr=Ee.chunks)!=null?Fr:[],Ee.startedAt=(Kn=Ee.startedAt)!=null?Kn:We((Yr=C.startedAt)!=null?Yr:C.timestamp),G?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(Ht=Ee.completedAt)!=null?Ht:Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=C.executionId)!=null?sr:(In=Y.agentMetadata)==null?void 0:In.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(Y)}else if(Ue==="text_start"){if((Zr=C.toolContext)!=null&&Zr.toolId)continue;let $=C.partId;if($!==void 0&&w.current!==null&&$!==w.current){let k=g;k&&(k.streaming=!1,f(k),xe=k,g=null,A=!0)}$!==void 0&&(w.current=$)}else if(Ue==="text_end"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=g;$&&($.streaming=!1,f($),xe=$,g=null,A=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((Mr=(eo=C.id)!=null?eo:Y.stepId)!=null?Mr:`step-${l()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",et=`${Y.toolId}::${Ne}`,Rt=I.get(et);if(lt!==""&&Rt!==void 0&&Rt!==""&&Rt!==lt){let at=P.get(F(Y.toolId,Ne,Rt));at&&at.streaming!==!1&&(at.streaming=!1,f(at))}lt!==""&&I.set(et,lt);let _t=E(Y.toolId,Ne,lt,Y.executionId),un=(tn=(gt=(fr=(Gn=C.text)!=null?Gn:C.delta)!=null?fr:C.content)!=null?gt:C.chunk)!=null?tn:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),C.isComplete&&(_t.streaming=!1,f(_t));continue}let oe=C.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Ne=g;Ne&&(Ne.streaming=!1,f(Ne),xe=Ne,g=null,A=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(nn=Ye.get(oe))!=null?nn:we();oe!==void 0&&(G.partId||(G.partId=oe),Ye.set(oe,G));let Ee=(hr=(be=(to=(Jn=C.text)!=null?Jn:C.delta)!=null?to:C.content)!=null?be:C.chunk)!=null?hr:"";if(Ee){let Ne=typeof C.seq=="number"?C.seq:void 0,lt=oe!=null?oe:G.id,et=Ne!==void 0?ge(lt,Ne,String(Ee)):((ar=ae.get(G.id))!=null?ar:"")+Ee;G.rawContent=et,Z.has(G.id)||Z.set(G.id,this.createStreamParser());let Rt=Z.get(G.id),_t=et.trim().startsWith("{")||et.trim().startsWith("[");if(_t&&ae.set(G.id,et),Rt.__isPlainTextParser===!0){G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G);continue}let at=Rt.processChunk(et);if(at instanceof Promise)at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")G.content=Zt,f(G);else if(!_t&&!et.trim().startsWith("<")){let wn=g,Jt=wn&&wn.id===G.id?wn:G;Jt.id===G.id&&(Jt.content=Ne!==void 0?et:Jt.content+Ee,ae.delete(Jt.id),Z.delete(Jt.id),Jt.rawContent=void 0,f(Jt))}}).catch(()=>{G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G)});else{let ft=typeof at=="string"?at:(_=at==null?void 0:at.text)!=null?_:null;ft!==null&&ft.trim()!==""?(G.content=ft,f(G)):!_t&&!et.trim().startsWith("<")&&(G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G))}}if(C.isComplete){let Ne=(kr=(Vo=C.result)==null?void 0:Vo.response)!=null?kr:G.content;if(Ne){let lt=ae.get(G.id),et=lt!=null?lt:X(Ne);G.rawContent=et;let Rt=Z.get(G.id),_t=null,un=!1;if(Rt&&(_t=Rt.getExtractedText(),_t===null&&(_t=Fo(et)),_t===null)){let at=Rt.processChunk(et);at instanceof Promise?(un=!0,at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null){let wn=g;wn&&wn.id===G.id&&(wn.content=Zt,wn.streaming=!1,Z.delete(wn.id),ae.delete(wn.id),f(wn))}})):_t=typeof at=="string"?at:($r=at==null?void 0:at.text)!=null?$r:null}if(!un){_t!==null&&_t.trim()!==""?G.content=_t:ae.has(G.id)||(G.content=X(Ne));let at=Z.get(G.id);if(at){let ft=(Ur=at.close)==null?void 0:Ur.call(at);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Ue==="step_complete"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((br=(Lr=C.id)!=null?Lr:Y.stepId)!=null?br:"");if(Ne){let lt=N(Y.toolId,Ne);for(let[et,Rt]of P)et.startsWith(lt)&&Rt.streaming!==!1&&(Rt.streaming=!1,f(Rt));I.delete(`${Y.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(A){if(g!==null){let et=g;oe&&(et.stopReason=oe),Z.delete(et.id),ae.delete(et.id),et.streaming!==!1&&(et.streaming=!1,f(et))}let Ne=(Ss=C.result)==null?void 0:Ss.response,lt=xe;lt&&(oe&&(lt.stopReason=oe),Ne!=null?Ge(lt,Ne):(Z.delete(lt.id),ae.delete(lt.id))),xe=null;continue}let G=(Qn=C.result)==null?void 0:Qn.response,Ee=we();if(oe&&(Ee.stopReason=oe),G!=null){let Ne=Z.get(Ee.id),lt=!1,et=!1;if(Ne){let Rt=Ne.getExtractedText(),_t=ae.get(Ee.id),un=_t!=null?_t:X(G);if(Ee.rawContent=un,Rt!==null&&Rt.trim()!=="")Ee.content=Rt,lt=!0;else{let at=Fo(un);if(at!==null)Ee.content=at,lt=!0;else{let ft=Ne.processChunk(un);if(ft instanceof Promise)et=!0,ft.then(Zt=>{var wn;let Ke=typeof Zt=="string"?Zt:(wn=Zt==null?void 0:Zt.text)!=null?wn:null;if(Ke!==null&&Ke.trim()!==""){let Jt=g;Jt&&Jt.id===Ee.id&&(Jt.content=Ke,Jt.streaming=!1,Z.delete(Jt.id),ae.delete(Jt.id),f(Jt))}else{let Jt=Ne.getExtractedText(),yn=g;yn&&yn.id===Ee.id&&(Jt!==null&&Jt.trim()!==""?yn.content=Jt:ae.has(yn.id)||(yn.content=X(G)),yn.streaming=!1,Z.delete(yn.id),ae.delete(yn.id),f(yn))}});else{let Zt=typeof ft=="string"?ft:(Xn=ft==null?void 0:ft.text)!=null?Xn:null;if(Zt!==null&&Zt.trim()!=="")Ee.content=Zt,lt=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Ee.content=Ke,lt=!0)}}}}}if(!et){if(!Ee.rawContent){let Rt=ae.get(Ee.id);Ee.rawContent=Rt!=null?Rt:X(G)}if(!lt&&!ae.has(Ee.id)&&(Ee.content=X(G)),Ne){let Rt=(yr=Ne.close)==null?void 0:yr.call(Ne);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}}else Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}else if(Ue==="flow_complete"){let $=(xr=C.result)==null?void 0:xr.response;if(A){if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}}else if($!=null){let k=we(),Y=ae.get(k.id),oe=Y!=null?Y:X($);k.rawContent=oe;let G=X($),Ee=Z.get(k.id);if(Ee){let et=Fo(oe);if(et!==null)G=et;else{let Rt=Ee.processChunk(oe);Rt instanceof Promise&&Rt.then(un=>{var ft;let at=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;at!==null&&(k.content=at,k.streaming=!1,f(k))});let _t=Ee.getExtractedText();_t!==null&&(G=_t)}}Z.delete(k.id),ae.delete(k.id);let Ne=G!==k.content,lt=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||lt)&&f(k)}else if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")te={executionId:C.executionId,agentId:(To=C.agentId)!=null?To:"virtual",agentName:(jr=C.agentName)!=null?jr:"",status:"running",currentIteration:0,maxTurns:(Sn=C.maxTurns)!=null?Sn:1,startedAt:We(C.startedAt)};else if(Ue==="agent_iteration_start"){if(te&&(te.currentIteration=C.iteration),On==="separate"&&C.iteration>1){let $=g;$&&($.streaming=!1,f($),ze.set(C.iteration-1,$),g=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=we();$.content+=(Pr=C.delta)!=null?Pr:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:te==null?void 0:te.agentName},v=$,f($)}else if(C.contentType==="thinking"){let $=(Ko=C.turnId)!=null?Ko:`agent-think-${C.iteration}`,k=ke($);k.reasoning=(Eo=k.reasoning)!=null?Eo:{id:$,status:"streaming",chunks:[]},k.reasoning.chunks.push((Go=C.delta)!=null?Go:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(k)}else if(C.contentType==="tool_input"){let $=(ya=C.toolCallId)!=null?ya:R.lastId;if($){let k=M.get($);k!=null&&k.toolCall&&(k.toolCall.chunks=(Jo=k.toolCall.chunks)!=null?Jo:[],k.toolCall.chunks.push((xa=C.delta)!=null?xa:""),f(k))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let oe=D.get($);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=We(C.completedAt);let G=(Qo=oe.reasoning.startedAt)!=null?Qo:Date.now();oe.reasoning.durationMs=Math.max(0,((bt=oe.reasoning.completedAt)!=null?bt:Date.now())-G),oe.streaming=!1,f(oe)}}let k=C.stopReason,Y=g!=null?g:v;if(k&&Y!==null){let oe=C.turnId;(!oe||((Ts=Y.agentMetadata)==null?void 0:Ts.turnId)===oe)&&(Y.stopReason=k,f(Y))}}else if(Ue==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let $=(ir=C.toolCallId)!=null?ir:`agent-tool-${l()}`;Re(re(C),$);let k=se($),Y=(Fn=k.toolCall)!=null?Fn:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(wa=(va=C.toolName)!=null?va:C.name)!=null?wa:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=We((Xo=C.startedAt)!=null?Xo:C.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(k)}else if(Ue==="agent_tool_delta"){let $=(qr=C.toolCallId)!=null?qr:R.lastId;if($){let k=(Es=M.get($))!=null?Es:se($);k.toolCall&&(k.toolCall.chunks=(no=k.toolCall.chunks)!=null?no:[],k.toolCall.chunks.push((Ms=C.delta)!=null?Ms:""),k.toolCall.status="running",k.streaming=!0,f(k))}}else if(Ue==="agent_tool_complete"){let $=(ks=C.toolCallId)!=null?ks:R.lastId;if($){let k=(Ls=M.get($))!=null?Ls:se($);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=We((Ps=C.completedAt)!=null?Ps:C.timestamp),k.streaming=!1,f(k);let Y=re(C);Y&&R.byCall.delete(Y)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],k=[];for(let Y of $){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Ee=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,lt="";if(G==="media"){let et=typeof oe.data=="string"?oe.data:void 0;if(!et)continue;lt=Ee.length>0?Ee:"application/octet-stream",Ne=`data:${lt};base64,${et}`}else if(G==="image-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else if(G==="file-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else continue;if(Ne)if(G==="image-url"||lt.startsWith("image/"))k.push({type:"image",image:Ne,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:lt});else if(lt.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:lt});else{let et=lt||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:et,filename:Mf(et)})}}if(k.length>0){let Y=l(),oe=C.toolCallId,Ee={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Ee);let Ne=g;Ne&&(Ne.streaming=!1,f(Ne)),g=null,y.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:$,role:"assistant",content:(_n=C.reflection)!=null?_n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Yo=C.reflection)!=null?Yo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(k)}else if(Ue==="agent_complete"){te&&(te.status=C.success?"complete":"error",te.completedAt=We(C.completedAt),te.stopReason=C.stopReason);let $=g;$&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(Rr=(Ir=C.error)==null?void 0:Ir.message)!=null?Rr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ca=te==null?void 0:te.agentId)!=null?Ca:"virtual",executionId:(Ws=(Rs=C.executionId)!=null?Rs:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Mo=C.toolName)!=null?Mo:"",toolType:C.toolType,description:(Sa=C.description)!=null?Sa:`Execute ${(Aa=C.toolName)!=null?Aa:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(Ta=C.approvalId)!=null?Ta:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ea=te==null?void 0:te.agentId)!=null?Ea:"virtual",executionId:(ko=(Oi=C.executionId)!=null?Oi:te==null?void 0:te.executionId)!=null?ko:"",toolName:(ro=C.toolName)!=null?ro:"",toolType:C.toolType,description:(Hs=C.description)!=null?Hs:`Execute ${(Ma=C.toolName)!=null?Ma:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(oo=C.decision)!=null?oo:"approved",agentId:(ka=te==null?void 0:te.agentId)!=null?ka:"virtual",executionId:(so=(Bs=C.executionId)!=null?Bs:te==null?void 0:te.executionId)!=null?so:"",toolName:(Ds=C.toolName)!=null?Ds:"",description:(La=C.description)!=null?La:"",resolvedAt:Date.now()}};f(Y)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,k=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:k,artifactType:$,title:Y,component:typeof C.component=="string"?C.component:void 0}),le.set(k,{markdown:"",title:Y}),!ne.has(k)){ne.add(k);let oe={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:$,status:"streaming"}})};Q.set(k,oe),f(oe)}}else if(Ue==="artifact_delta"){let $=String(C.id),k=typeof C.delta=="string"?C.delta:String((zr=C.delta)!=null?zr:"");n({type:"artifact_delta",id:$,artDelta:k});let Y=le.get($);Y&&(Y.markdown+=k)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let k=Q.get($);if(k){k.streaming=!1;try{let Y=JSON.parse((Pa=k.rawContent)!=null?Pa:"{}");if(Y.props){Y.props.status="complete";let oe=le.get($);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete($),f(k),Q.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let k=String((ao=$.id)!=null?ao:`msg-${l()}`),Y=$.role,G={id:k,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(f(G),G.rawContent)try{let Ee=JSON.parse(G.rawContent),Ne=(Bt=Ee==null?void 0:Ee.props)==null?void 0:Bt.artifactId;typeof Ne=="string"&&ne.add(Ne)}catch{}g=null,y.current=null,Z.delete(k),ae.delete(k)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let k=(Zo=C.message)!=null?Zo:C.error;k!=null&&k!==""&&($=new Error(String(k)))}else if(Ue==="step_error"||Ue==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?$=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&($=new Error(String((es=k.message)!=null?es:k)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let k=g;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:W,value:de}=await s.read();if(W)break;a+=o.decode(de,{stream:!0});let De=a.split(`
10
10
 
11
11
  `);a=(ln=De.pop())!=null?ln:"";for(let Je of De){let Fe=Je.split(`
12
12
  `),$e="message",st="";for(let Yt of Fe)Yt.startsWith("event:")?$e=Yt.replace("event:","").trim():Yt.startsWith("data:")&&(st+=Yt.replace("data:","").trim());if(!st)continue;let Lt;try{Lt=JSON.parse(st)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let zt=$e!=="message"?$e:(nr=Lt.type)!=null?nr:"message";if((Sr=this.onSSEEvent)==null||Sr.call(this,zt,Lt),this.parseSSEEvent){y.current=g;let Yt=await this.handleCustomSSEEvent(Lt,n,y,f,l,w);if(y.current&&y.current!==g&&(g=y.current),Yt)continue}Tt.push(zt,Lt),pe()}}Tt.flushPending(),pe(),Tt.destroy()}};function Pf(){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 us(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function If(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Rf(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wf(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Hf(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ja(e){return{type:"text",text:e}}function Bf(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 Df(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Of(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 Bu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Nf=["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=[...Bu,...Nf];function Ff(e){return Bu.includes(e)||e.startsWith("image/")}function Qa(e){return Ff(e.type)}async function Du(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Qa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ou(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 _f(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nu(e,t){let n=_f(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Xa=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ya=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Xs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ya;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,y=A=>{v||(v=!0,clearTimeout(w),g(new Error(A)))},w=setTimeout(()=>y("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let D=A.code!==1006?` (code ${A.code})`:"";y("WebSocket connection failed"+D+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};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=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("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 ms(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xs(e.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function sl(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ms({type:"runtype",runtype:e.runtype});if(_o.isSupported())return ms({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Za(e){try{return sl(e),!0}catch{return!1}}var $f=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Uf(e,t){return $f.some(n=>e[n]!==t[n])}function Fu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
@@ -120,7 +120,7 @@ ${a.join(`
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var dg="3.34.0";var As=dg;function uv(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function mv(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function gv(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function fv(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function hv(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function bv(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var yv={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},pg={components:{panel:{borderRadius:"0",shadow:"none"}}},ug={id:"shop",label:"Shopping Assistant",config:{theme:yv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},mg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pg}},gg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pg}},fg={shop:ug,minimal:mg,fullscreen:gg};function xv(e){return fg[e]}var vv=Xm;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function wv(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var hg=`({ text, message }: any) => {
123
+ `)}var dg="3.34.1";var As=dg;function uv(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function mv(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function gv(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function fv(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function hv(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function bv(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var yv={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},pg={components:{panel:{borderRadius:"0",shadow:"none"}}},ug={id:"shop",label:"Shopping Assistant",config:{theme:yv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},mg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pg}},gg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pg}},fg={shop:ug,minimal:mg,fullscreen:gg};function xv(e){return fg[e]}var vv=Xm;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function wv(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var hg=`({ text, message }: any) => {
124
124
  const jsonSource = (message as any).rawContent || text || message.content;
125
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
126
126
  let cleanJson = jsonSource