@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.
@@ -6,7 +6,7 @@ ${t}`:"")+(e.description?`
6
6
  ${e.description}`:"");return window.confirm(n)},Vh=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)}},$h=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Uh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as zh,ARR as qh,OBJ as jh,STR as Kh}from"partial-json";var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Fo=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var kl="ask_user_question",Ys=8,ds="data-persona-ask-sheet-for",Gh="Other",Yh="Other\u2026",cm="Type your own answer here",dm="Send",Qh="Next",Xh="Back",Jh="Submit all",Zh="Skip",eb=3,El="data-ask-current-index",Ml="data-ask-question-count",pm="data-ask-answers",Ll="data-ask-grouped",um="data-ask-layout",tb=e=>e.layout==="pills"?"pills":"rows",nb=e=>e.getAttribute(um)==="pills"?"pills":"rows",lm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Hr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===kl,Il=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ps=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=zh(r,Kh|jh|qh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Qs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Ys&&!lm&&(lm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ys}.`)),t.slice(0,Ys)},ob=e=>{var t;return(t=Qs(e)[0])!=null?t:null},rb=(e,t)=>{var n;return(n=Qs(e)[t])!=null?n:null},sb=(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))},gm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},ab=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=b("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=gm(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ib=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},lb=(e,t,n,o)=>{var u,g,f;let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<eb;m++)s.appendChild(ib(o));return s}if(d.forEach((m,x)=>{s.appendChild(ab(m,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Gh:Yh;if(o==="rows"){let x=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(u=t.freeTextPlaceholder)!=null?u:cm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),v.appendChild(E),x.appendChild(v);let L=gm(o,a,d.length);L&&x.appendChild(L),s.appendChild(x)}else{let x=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(f=t.freeTextLabel)!=null?f:m,s.appendChild(x)}}return s},fm=(e,t)=>{var s,a;let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=(s=e.freeTextPlaceholder)!=null?s:cm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:dm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},cb=e=>{var o;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(o=e.submitLabel)!=null?o:dm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},db=(e,t,n)=>{var l,u,g,f;let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=(l=n.backLabel)!=null?l:Xh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:Zh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(g=n.submitAllLabel)!=null?g:Jh:(f=n.nextLabel)!=null?f:Qh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Dr=e=>{let t=e.getAttribute(pm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},hm=(e,t)=>{e.setAttribute(pm,JSON.stringify(t))},go=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pb=(e,t)=>{e.setAttribute(El,String(Math.max(0,Math.floor(t))))},us=e=>{var n;let t=Number((n=e.getAttribute(Ml))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},gr=e=>e.getAttribute(Ll)==="true",ub=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(o[a]=d)}}),o},mb=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},si=(e,t)=>{let{payload:n}=ps(t),o=Qs(n),r=Dr(e),s={},a=new Set;return o.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(r,d)&&(s[l]=r[d]))}),s},bm=e=>{let t=Dr(e),n=go(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let l=(g=d.getAttribute("data-option-label"))!=null?g:"",u=r.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!a.has(o)){i.value=o;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ym=e=>{if(!gr(e))return;let t=Dr(e),n=go(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Rl=(e,t,n)=>{let o=Il(n),r=nb(e),{payload:s,complete:a}=ps(t),i=gr(e),d=go(e),l=us(e),u=i?rb(s,d):ob(s),g=!!(u!=null&&u.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let I=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=I,x.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let I=lb(u,o,a,r);v.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(fm(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!E?e.appendChild(cb(o)):(!g||i)&&E&&E.remove(),e.setAttribute("data-multi-select",g?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=db(d,l,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();bm(e),ym(e)},gb=(e,t,n)=>{let o=Il(t),r=tb(o),s=e.toolCall.id,a=Qs(n),i=Math.max(1,a.length),d=i>1,l=ub(e,a),u=d?mb(e,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Ml,String(i)),g.setAttribute(El,String(u)),g.setAttribute(Ll,d?"true":"false"),g.setAttribute(um,r),hm(g,l),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),sb(g,o);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",f.appendChild(m);let x=b("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",f.appendChild(x),g.appendChild(f);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),g.appendChild(E),r!=="rows"&&g.appendChild(fm(o,r)),Rl(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},fb=(e,t,n)=>{let{payload:o}=ps(t),r=Math.max(1,Qs(o).length);r>us(e)&&(e.setAttribute(Ml,String(r)),r>1&&!gr(e)&&e.setAttribute(Ll,"true")),Rl(e,t,n)};var ai=(e,t,n)=>{if(!n||!Hr(e)||Il(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ds}]`).forEach(l=>{l.getAttribute(ds)!==r&&l.remove()});let a=n.querySelector(`[${ds}="${mm(r)}"]`);if(a){fb(a,e,t);return}let{payload:i}=ps(e),d=gb(e,t,i);n.appendChild(d)},ms=(e,t)=>{if(!e)return;let n=t?`[${ds}="${mm(t)}"]`:`[${ds}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Pl=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),fr=(e,t)=>{let n=Dr(e),o=go(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,hm(e,n),bm(e),ym(e)},ii=(e,t,n,o)=>{let r=us(e),s=Math.max(0,Math.min(r-1,o));pb(e,s),Rl(e,t,n)};var Yo="suggest_replies";var hb={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},vm={name:Yo,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:hb,origin:"sdk",annotations:{readOnlyHint:!0}},Wl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Bl=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Yo},bb=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 o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},xm=e=>{var t;for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return null;if(!Bl(o))continue;let r=bb((t=o.toolCall)==null?void 0:t.args);return r.length>0?r:null}return null},wm=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 yb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ys,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},vb={name:kl,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:yb,origin:"sdk",annotations:{readOnlyHint:!0}},Hl=e=>{var o;let t=[],n=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(vb),wm(e)&&t.push(vm),t};import{parse as xb,STR as wb,OBJ as Cb}from"partial-json";var Cm=e=>e.replace(/\\n/g,`
7
7
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=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)}},Sb=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Sm=e=>e.status==="complete"?Sb(e):e.status==="pending"?"Waiting":"",Ab=e=>{var r,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Am=e=>e.status==="complete"?Ab(e):"Using tool...",li=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,o,r;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return li(t)},ci=e=>{var n,o,r;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((r=(o=e.startedAt)!=null?o:e.completedAt)!=null?r:Date.now()));return li(t)},Dl=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=Js(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},di=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Xs(o,n.slice(s,a.index),[]),a[1]!==void 0?Xs(o,a[1],["bold"]):a[2]!==void 0?Xs(o,a[2],["italic"]):a[3]!==void 0&&Xs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Xs(o,n.slice(s),[]),o},Xs=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Tb=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.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 o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Or=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},km=()=>{var t;let e=Tb();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Em=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=xb(n,wb|Cb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mm=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var pi=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 s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),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,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var kb="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function Eb(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var 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 Mb(e){switch(e){case"json":return Em;case"regex-json":return km;case"xml":return Mm;default:return Tm}}var Lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lb(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lm(n);if(!Lm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Or(e);return Or(t)!==null&&a===null?t:e}var Zs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:kb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Mb(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new ri(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,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.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$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,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 r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(Ol).map(H=>{var R,w,C;return{id:H.id,role:H.role,content:(C=(w=(R=H.contentParts)!=null?R:H.llmContent)!=null?w:H.rawContent)!=null?C:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),x=m?am(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===x,L=!1,I=null,W;for(let H=0;;H++){let w={...g,...m&&(L||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),W.status===409&&H===0&&m){let C=await W.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=C!=null?C:{error:"Chat request failed"}}break}if(!W.ok){let H=I!=null?I:await W.json().catch(()=>({error:"Chat request failed"}));if(W.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(W.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let R=new Error(H.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!W.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.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 o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.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 o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.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,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,a;r&&(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:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,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(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),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&&(o.context=i)}return o}async buildPayload(t){var s,a;let o={messages:t.slice().filter(Ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),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&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let d=i;return o.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=o.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=g,r(g),g},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.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,o){var Bt,an,ro,Eo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Ke=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:Ke}},g=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},f=D=>{g(D)&&n({type:"message",message:u(D)})},m=null,x=null,v={current:null},E={current:null},L=!1,I=new Map,W=new Map,H=new Map,R=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,A=(D,pe)=>`${D}::${pe}::`,S=(D,pe,De,Ke)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let ot=De?`-${De}`:"",It={id:`nested-${D}-${pe}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ke,parentToolId:D,parentStepId:pe}};return H.set(Ne,It),f(It),It},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var pe,De,Ke,Ne,Ve;return _((Ve=(Ne=(Ke=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?Ke:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},K=D=>{var pe,De,Ke,Ne,Ve,ot,It;return _((It=(ot=(Ve=(Ne=(Ke=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?Ke:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?ot:D.stepId)!=null?It:D.step_id)},fe=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&fe?(D=fe,ue=!0):fe&&E.current?D=`${fe}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,Ke=V(D);if(De){let ot=String(De);return ke(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(Ke,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),f(De),De},Se=(D,pe)=>{C.lastId=pe,D&&C.byCall.set(D,pe)},ie=new Set,Q=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,Ke=K(D);if(De){let ot=String(De);return Se(Ke,ot),ot}if(Ke){let ot=C.byCall.get(Ke);if(ot)return C.lastId=ot,ot}if(C.lastId&&!pe)return C.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(Ke,Ne),Ne},se=D=>{let pe=W.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return W.set(D,De),f(De),De},Re=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Le=null,de=(D,pe,De)=>{var It;let Ke=at.get(D);Ke||(Ke=[],at.set(D,Ke));let Ne=0,Ve=Ke.length;for(;Ne<Ve;){let qt=Ne+Ve>>>1;Ke[qt].seq<pe?Ne=qt+1:Ve=qt}((It=Ke[Ne])==null?void 0:It.seq)===pe?Ke[Ne]={seq:pe,text:De}:Ke.splice(Ne,0,{seq:pe,text:De});let ot="";for(let qt=0;qt<Ke.length;qt++)ot+=Ke[qt].text;return ot},Qe=(D,pe)=>{let De=ne(pe),Ke=oe.get(D.id),Ne=Lb(Ke,De);D.rawContent=Ne;let Ve=Z.get(D.id),ot=yt=>{var Ce;let st=(Ce=D.content)!=null?Ce:"";yt.trim()!==""&&(st.trim().length===0||yt.startsWith(st)||yt.trimStart().startsWith(st.trim()))&&(D.content=yt)},It=()=>{var yt;if(Ve){let st=(yt=Ve.close)==null?void 0:yt.call(Ve);st instanceof Promise&&st.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,f(D)};if(!Ve){ot(De),It();return}let qt=Or(Ne);if(qt!==null&&qt.trim()!==""){ot(qt),It();return}let Xt=yt=>{var le;let st=typeof yt=="string"?yt:(le=yt==null?void 0:yt.text)!=null?le:null;if(st!==null&&st.trim()!=="")return st;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},G;try{G=Ve.processChunk(Ne)}catch{ot(De),It();return}if(G instanceof Promise){G.then(yt=>{ot(Xt(yt)),It()}).catch(()=>{ot(De),It()});return}ot(Xt(G)),It()},We=[],q=!1,me,tt=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Tt=new pi((D,pe)=>{We.push({payloadType:D,payload:pe}),tt()}),te=null,ze=new Map,Nn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(me=()=>{var D,pe,De,Ke,Ne,Ve,ot,It,qt,Xt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Xe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Qn,bo,gt,en,tn,Xn,rr,xe,yo,lo,$,jr,Ro,Uo,zo,Po,vo,As,Jn,Zn,xo,wo,xr,qo,Tn,Wo,Kr,wr,Gr,Aa,Yr,Ta,Qr,bt,Ts,co,Vn,ka,Ea,Xr,jo,ks,sr,Es,Ms,Ls,Is,$n,Jr,Bo,Ho,Rs,Ma,Ps,Ws,Cr,La,Ia,Ra,Pa,rl,Sr,ar,Wa,Bs,ir,Ba,Hs,lr,Ds,Ha,Ko,Da,cr,Dt,Zr,es;for(let Ar=0;Ar<We.length;Ar++){let $e=We[Ar].payloadType,T=We[Ar].payload;if($e==="reason_start"){let U=(D=ve(T,!0))!=null?D:`reason-${l()}`,P=He(U);P.reasoning=(pe=P.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ke=P.reasoning.startedAt)!=null?Ke:Re((De=T.startedAt)!=null?De:T.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if($e==="reason_delta"||$e==="reason_chunk"){let U=(Ve=(Ne=ve(T,!1))!=null?Ne:ve(T,!0))!=null?Ve:`reason-${l()}`,P=He(U);P.reasoning=(ot=P.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(qt=P.reasoning.startedAt)!=null?qt:Re((It=T.startedAt)!=null?It:T.timestamp);let J=(yt=(G=(Xt=T.reasoningText)!=null?Xt:T.text)!=null?G:T.delta)!=null?yt:"";if(J&&T.hidden!==!0){let ae=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ae!==void 0){let Y=de(U,ae,String(J));P.reasoning.chunks=[Y]}else P.reasoning.chunks.push(String(J))}if(P.reasoning.status=T.done?"complete":"streaming",T.done){P.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ae=(Ce=P.reasoning.startedAt)!=null?Ce:Date.now();P.reasoning.durationMs=Math.max(0,((le=P.reasoning.completedAt)!=null?le:Date.now())-ae)}P.streaming=P.reasoning.status!=="complete",f(P)}else if($e==="reason_complete"){let U=(Zt=(Ze=ve(T,!1))!=null?Ze:ve(T,!0))!=null?Zt:`reason-${l()}`,P=I.get(U);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Re((jt=T.completedAt)!=null?jt:T.timestamp);let ae=(Rn=P.reasoning.startedAt)!=null?Rn:Date.now();P.reasoning.durationMs=Math.max(0,((xn=P.reasoning.completedAt)!=null?xn:Date.now())-ae),P.streaming=!1,f(P)}let J=V(T);J&&w.byStep.delete(J)}else if($e==="tool_start"){let U=(ut=j(T,!0))!=null?ut:`tool-${l()}`,P=(kt=T.toolName)!=null?kt:T.name;if(he(P)){ie.add(U);continue}let J=se(U),ae=(Xe=J.toolCall)!=null?Xe:{id:U,status:"pending"};ae.name=P!=null?P:ae.name,ae.status="running",T.args!==void 0?ae.args=T.args:T.parameters!==void 0&&(ae.args=T.parameters),ae.startedAt=(ln=ae.startedAt)!=null?ln:Re((Ut=T.startedAt)!=null?Ut:T.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,J.toolCall=ae,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Sn=Y==null?void 0:Y.executionId)!=null?Sn:T.executionId,iteration:(An=Y==null?void 0:Y.iteration)!=null?An:T.iteration}),f(J)}else if($e==="tool_chunk"||$e==="tool_delta"){let U=(Mo=(bn=j(T,!1))!=null?bn:j(T,!0))!=null?Mo:`tool-${l()}`;if(ie.has(U))continue;let P=se(U),J=(Ct=P.toolCall)!=null?Ct:{id:U,status:"running"};J.startedAt=(qn=J.startedAt)!=null?qn:Re((zn=T.startedAt)!=null?zn:T.timestamp);let ae=(vt=(ho=(No=T.text)!=null?No:T.delta)!=null?ho:T.message)!=null?vt:"";ae&&(J.chunks=(yr=J.chunks)!=null?yr:[],J.chunks.push(String(ae))),J.status="running",P.toolCall=J,P.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(_n=P.agentMetadata)!=null?_n:{executionId:(Lo=Y==null?void 0:Y.executionId)!=null?Lo:T.executionId,iteration:(vr=Y==null?void 0:Y.iteration)!=null?vr:T.iteration}),f(P)}else if($e==="tool_complete"){let U=(Zo=(qr=j(T,!1))!=null?qr:j(T,!0))!=null?Zo:`tool-${l()}`;if(ie.has(U)){ie.delete(U);continue}let P=se(U),J=(_o=P.toolCall)!=null?_o:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Re((St=T.completedAt)!=null?St:T.timestamp);let ae=(jn=T.duration)!=null?jn:T.executionTime;if(typeof ae=="number")J.durationMs=ae;else{let Fe=(Kn=J.startedAt)!=null?Kn:Date.now();J.durationMs=Math.max(0,((Pn=J.completedAt)!=null?Pn:Date.now())-Fe)}P.toolCall=J,P.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(ao=P.agentMetadata)!=null?ao:{executionId:(Lt=Y==null?void 0:Y.executionId)!=null?Lt:T.executionId,iteration:(so=Y==null?void 0:Y.iteration)!=null?so:T.iteration}),f(P);let Me=K(T);Me&&C.byCall.delete(Me)}else if($e==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,P=(Gn=U!=null?U:T.toolId)!=null?Gn:`local-${l()}`,J=se(P),ae=T.toolName,Y=Gs(ae),Me=(er=J.toolCall)!=null?er:{id:P,status:"pending"};Me.name=ae,Me.args=T.parameters,Me.status=Y?"running":"complete",Me.chunks=(Vo=Me.chunks)!=null?Vo:[],Me.startedAt=(Yn=Me.startedAt)!=null?Yn:Re((tr=T.startedAt)!=null?tr:T.timestamp),Y?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Ht=Me.completedAt)!=null?Ht:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(io=T.executionId)!=null?io:(Wn=J.agentMetadata)==null?void 0:Wn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if($e==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let P=m;P&&(P.streaming=!1,f(P),Le=P,m=null,L=!0)}U!==void 0&&(E.current=U)}else if($e==="text_end"){if(($o=T.toolContext)!=null&&$o.toolId)continue;let U=m;U&&(U.streaming=!1,f(U),Le=U,m=null,L=!0)}else if($e==="step_chunk"||$e==="step_delta"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((Io=(or=T.id)!=null?or:J.stepId)!=null?Io:`step-${l()}`),lt=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Je=`${J.toolId}::${Fe}`,Wt=R.get(Je);if(lt!==""&&Wt!==void 0&&Wt!==""&&Wt!==lt){let rt=H.get(k(J.toolId,Fe,Wt));rt&&rt.streaming!==!1&&(rt.streaming=!1,f(rt))}lt!==""&&R.set(Je,lt);let _t=S(J.toolId,Fe,lt,J.executionId),un=(en=(gt=(bo=(Qn=T.text)!=null?Qn:T.delta)!=null?bo:T.content)!=null?gt:T.chunk)!=null?en:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),T.isComplete&&(_t.streaming=!1,f(_t));continue}let ae=T.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),Le=Fe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(tn=it.get(ae))!=null?tn:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Me=(yo=(xe=(rr=(Xn=T.text)!=null?Xn:T.delta)!=null?rr:T.content)!=null?xe:T.chunk)!=null?yo:"";if(Me){let Fe=typeof T.seq=="number"?T.seq:void 0,lt=ae!=null?ae:Y.id,Je=Fe!==void 0?de(lt,Fe,String(Me)):((lo=oe.get(Y.id))!=null?lo:"")+Me;Y.rawContent=Je,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Wt=Z.get(Y.id),_t=Je.trim().startsWith("{")||Je.trim().startsWith("[");if(_t&&oe.set(Y.id,Je),Wt.__isPlainTextParser===!0){Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let rt=Wt.processChunk(Je);if(rt instanceof Promise)rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null&&Jt.trim()!=="")Y.content=Jt,f(Y);else if(!_t&&!Je.trim().startsWith("<")){let wn=m,Gt=wn&&wn.id===Y.id?wn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Je:Gt.content+Me,oe.delete(Gt.id),Z.delete(Gt.id),Gt.rawContent=void 0,f(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let ft=typeof rt=="string"?rt:($=rt==null?void 0:rt.text)!=null?$:null;ft!==null&&ft.trim()!==""?(Y.content=ft,f(Y)):!_t&&!Je.trim().startsWith("<")&&(Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Fe=(Ro=(jr=T.result)==null?void 0:jr.response)!=null?Ro:Y.content;if(Fe){let lt=oe.get(Y.id),Je=lt!=null?lt:ne(Fe);Y.rawContent=Je;let Wt=Z.get(Y.id),_t=null,un=!1;if(Wt&&(_t=Wt.getExtractedText(),_t===null&&(_t=Or(Je)),_t===null)){let rt=Wt.processChunk(Je);rt instanceof Promise?(un=!0,rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null){let wn=m;wn&&wn.id===Y.id&&(wn.content=Jt,wn.streaming=!1,Z.delete(wn.id),oe.delete(wn.id),f(wn))}})):_t=typeof rt=="string"?rt:(Uo=rt==null?void 0:rt.text)!=null?Uo:null}if(!un){_t!==null&&_t.trim()!==""?Y.content=_t:oe.has(Y.id)||(Y.content=ne(Fe));let rt=Z.get(Y.id);if(rt){let ft=(zo=rt.close)==null?void 0:zo.call(rt);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if($e==="step_complete"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((vo=(Po=T.id)!=null?Po:J.stepId)!=null?vo:"");if(Fe){let lt=A(J.toolId,Fe);for(let[Je,Wt]of H)Je.startsWith(lt)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${J.toolId}::${Fe}`)}continue}let ae=T.stopReason;if(L){if(m!==null){let Je=m;ae&&(Je.stopReason=ae),Z.delete(Je.id),oe.delete(Je.id),Je.streaming!==!1&&(Je.streaming=!1,f(Je))}let Fe=(As=T.result)==null?void 0:As.response,lt=Le;lt&&(ae&&(lt.stopReason=ae),Fe!=null?Qe(lt,Fe):(Z.delete(lt.id),oe.delete(lt.id))),Le=null;continue}let Y=(Jn=T.result)==null?void 0:Jn.response,Me=ce();if(ae&&(Me.stopReason=ae),Y!=null){let Fe=Z.get(Me.id),lt=!1,Je=!1;if(Fe){let Wt=Fe.getExtractedText(),_t=oe.get(Me.id),un=_t!=null?_t:ne(Y);if(Me.rawContent=un,Wt!==null&&Wt.trim()!=="")Me.content=Wt,lt=!0;else{let rt=Or(un);if(rt!==null)Me.content=rt,lt=!0;else{let ft=Fe.processChunk(un);if(ft instanceof Promise)Je=!0,ft.then(Jt=>{var wn;let je=typeof Jt=="string"?Jt:(wn=Jt==null?void 0:Jt.text)!=null?wn:null;if(je!==null&&je.trim()!==""){let Gt=m;Gt&&Gt.id===Me.id&&(Gt.content=je,Gt.streaming=!1,Z.delete(Gt.id),oe.delete(Gt.id),f(Gt))}else{let Gt=Fe.getExtractedText(),yn=m;yn&&yn.id===Me.id&&(Gt!==null&&Gt.trim()!==""?yn.content=Gt:oe.has(yn.id)||(yn.content=ne(Y)),yn.streaming=!1,Z.delete(yn.id),oe.delete(yn.id),f(yn))}});else{let Jt=typeof ft=="string"?ft:(Zn=ft==null?void 0:ft.text)!=null?Zn:null;if(Jt!==null&&Jt.trim()!=="")Me.content=Jt,lt=!0;else{let je=Fe.getExtractedText();je!==null&&je.trim()!==""&&(Me.content=je,lt=!0)}}}}}if(!Je){if(!Me.rawContent){let Wt=oe.get(Me.id);Me.rawContent=Wt!=null?Wt:ne(Y)}if(!lt&&!oe.has(Me.id)&&(Me.content=ne(Y)),Fe){let Wt=(xo=Fe.close)==null?void 0:xo.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}}else Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}else if($e==="flow_complete"){let U=(wo=T.result)==null?void 0:wo.response;if(L){if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(U!=null){let P=ce(),J=oe.get(P.id),ae=J!=null?J:ne(U);P.rawContent=ae;let Y=ne(U),Me=Z.get(P.id);if(Me){let Je=Or(ae);if(Je!==null)Y=Je;else{let Wt=Me.processChunk(ae);Wt instanceof Promise&&Wt.then(un=>{var ft;let rt=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;rt!==null&&(P.content=rt,P.streaming=!1,f(P))});let _t=Me.getExtractedText();_t!==null&&(Y=_t)}}Z.delete(P.id),oe.delete(P.id);let Fe=Y!==P.content,lt=P.streaming!==!1;Fe&&(P.content=Y),P.streaming=!1,(Fe||lt)&&f(P)}else if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if($e==="agent_start")te={executionId:T.executionId,agentId:(xr=T.agentId)!=null?xr:"virtual",agentName:(qo=T.agentName)!=null?qo:"",status:"running",currentIteration:0,maxTurns:(Tn=T.maxTurns)!=null?Tn:1,startedAt:Re(T.startedAt)};else if($e==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Nn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,f(U),ze.set(T.iteration-1,U),m=null)}}else if($e==="agent_turn_start")x=null;else if($e==="agent_turn_delta"){if(T.contentType==="text"){let U=ce();U.content+=(Wo=T.delta)!=null?Wo:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},x=U,f(U)}else if(T.contentType==="thinking"){let U=(Kr=T.turnId)!=null?Kr:`agent-think-${T.iteration}`,P=He(U);P.reasoning=(wr=P.reasoning)!=null?wr:{id:U,status:"streaming",chunks:[]},P.reasoning.chunks.push((Gr=T.delta)!=null?Gr:""),P.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(P)}else if(T.contentType==="tool_input"){let U=(Aa=T.toolCallId)!=null?Aa:C.lastId;if(U){let P=W.get(U);P!=null&&P.toolCall&&(P.toolCall.chunks=(Yr=P.toolCall.chunks)!=null?Yr:[],P.toolCall.chunks.push((Ta=T.delta)!=null?Ta:""),f(P))}}}else if($e==="agent_turn_complete"){let U=T.turnId;if(U){let ae=I.get(U);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Re(T.completedAt);let Y=(Qr=ae.reasoning.startedAt)!=null?Qr:Date.now();ae.reasoning.durationMs=Math.max(0,((bt=ae.reasoning.completedAt)!=null?bt:Date.now())-Y),ae.streaming=!1,f(ae)}}let P=T.stopReason,J=m!=null?m:x;if(P&&J!==null){let ae=T.turnId;(!ae||((Ts=J.agentMetadata)==null?void 0:Ts.turnId)===ae)&&(J.stopReason=P,f(J))}}else if($e==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let U=(co=T.toolCallId)!=null?co:`agent-tool-${l()}`;Se(K(T),U);let P=se(U),J=(Vn=P.toolCall)!=null?Vn:{id:U,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};J.name=(Ea=(ka=T.toolName)!=null?ka:T.name)!=null?Ea:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Re((Xr=T.startedAt)!=null?Xr:T.timestamp),P.toolCall=J,P.streaming=!0,P.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(P)}else if($e==="agent_tool_delta"){let U=(jo=T.toolCallId)!=null?jo:C.lastId;if(U){let P=(ks=W.get(U))!=null?ks:se(U);P.toolCall&&(P.toolCall.chunks=(sr=P.toolCall.chunks)!=null?sr:[],P.toolCall.chunks.push((Es=T.delta)!=null?Es:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if($e==="agent_tool_complete"){let U=(Ms=T.toolCallId)!=null?Ms:C.lastId;if(U){let P=(Ls=W.get(U))!=null?Ls:se(U);if(P.toolCall){P.toolCall.status="complete",T.result!==void 0&&(P.toolCall.result=T.result),typeof T.executionTime=="number"&&(P.toolCall.durationMs=T.executionTime),P.toolCall.completedAt=Re((Is=T.completedAt)!=null?Is:T.timestamp),P.streaming=!1,f(P);let J=K(T);J&&C.byCall.delete(J)}}}else if($e==="agent_media"){let U=Array.isArray(T.media)?T.media:[],P=[];for(let J of U){if(!J||typeof J!="object")continue;let ae=J,Y=typeof ae.type=="string"?ae.type:void 0,Me=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Fe=null,lt="";if(Y==="media"){let Je=typeof ae.data=="string"?ae.data:void 0;if(!Je)continue;lt=Me.length>0?Me:"application/octet-stream",Fe=`data:${lt};base64,${Je}`}else if(Y==="image-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else if(Y==="file-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else continue;if(Fe)if(Y==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:Fe,mimeType:lt});else{let Je=lt||"application/octet-stream";P.push({type:"file",data:Fe,mimeType:Je,filename:Eb(Je)})}}if(P.length>0){let J=l(),ae=T.toolCallId,Me={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Me);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,v.current=null}}else if($e!=="agent_iteration_complete"){if($e==="agent_reflection"||$e==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,P={id:U,role:"assistant",content:($n=T.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Jr=T.reflection)!=null?Jr:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(P)}else if($e==="agent_complete"){te&&(te.status=T.success?"complete":"error",te.completedAt=Re(T.completedAt),te.stopReason=T.stopReason);let U=m;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if($e==="agent_error"){let U=typeof T.error=="string"?T.error:(Ho=(Bo=T.error)==null?void 0:Bo.message)!=null?Ho:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if($e!=="agent_ping"){if($e==="agent_approval_start"){let U=(Rs=T.approvalId)!=null?Rs:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Ma=te==null?void 0:te.agentId)!=null?Ma:"virtual",executionId:(Ws=(Ps=T.executionId)!=null?Ps:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Cr=T.toolName)!=null?Cr:"",toolType:T.toolType,description:(Ia=T.description)!=null?Ia:`Execute ${(La=T.toolName)!=null?La:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="step_await"&&T.awaitReason==="approval_required"){let U=(Ra=T.approvalId)!=null?Ra:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Pa=te==null?void 0:te.agentId)!=null?Pa:"virtual",executionId:(Sr=(rl=T.executionId)!=null?rl:te==null?void 0:te.executionId)!=null?Sr:"",toolName:(ar=T.toolName)!=null?ar:"",toolType:T.toolType,description:(Bs=T.description)!=null?Bs:`Execute ${(Wa=T.toolName)!=null?Wa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ir=T.decision)!=null?ir:"approved",agentId:(Ba=te==null?void 0:te.agentId)!=null?Ba:"virtual",executionId:(lr=(Hs=T.executionId)!=null?Hs:te==null?void 0:te.executionId)!=null?lr:"",toolName:(Ds=T.toolName)!=null?Ds:"",description:(Ha=T.description)!=null?Ha:"",resolvedAt:Date.now()}};f(J)}}else if($e==="artifact_start"||$e==="artifact_delta"||$e==="artifact_update"||$e==="artifact_complete"){if($e==="artifact_start"){let U=T.artifactType,P=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:P,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),be.set(P,{markdown:"",title:J}),!re.has(P)){re.add(P);let ae={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:J,artifactType:U,status:"streaming"}})};Q.set(P,ae),f(ae)}}else if($e==="artifact_delta"){let U=String(T.id),P=typeof T.delta=="string"?T.delta:String((Ko=T.delta)!=null?Ko:"");n({type:"artifact_delta",id:U,artDelta:P});let J=be.get(U);J&&(J.markdown+=P)}else if($e==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if($e==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let P=Q.get(U);if(P){P.streaming=!1;try{let J=JSON.parse((Da=P.rawContent)!=null?Da:"{}");if(J.props){J.props.status="complete";let ae=be.get(U);ae!=null&&ae.markdown&&(J.props.markdown=ae.markdown)}P.rawContent=JSON.stringify(J)}catch{}be.delete(U),f(P),Q.delete(U)}}}else if($e==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let P=String((cr=U.id)!=null?cr:`msg-${l()}`),J=U.role,Y={id:P,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(Y),Y.rawContent)try{let Me=JSON.parse(Y.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,v.current=null,Z.delete(P),oe.delete(P)}else if($e==="error"||$e==="step_error"||$e==="dispatch_error"||$e==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if($e==="dispatch_error"){let P=(Zr=T.message)!=null?Zr:T.error;P!=null&&P!==""&&(U=new Error(String(P)))}else if($e==="step_error"||$e==="flow_error"){let P=T.error;typeof P=="string"&&P!==""?U=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(U=new Error(String((es=P.message)!=null?es:P)))}else $e==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{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 o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Or=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Tm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},km=()=>{var t;let e=Tb();return{processChunk:async n=>{let o=n.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Em=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=xb(n,wb|Cb);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Cm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Cm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var Mm=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var pi=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 s,a,i;let o=(i=(s=n==null?void 0:n.seq)!=null?s:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(t,n);return}let r=this.buffer.get(o);r!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${r.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(r.payloadType,r.payload)),this.buffer.set(o,{payloadType:t,payload:n,seq:o}),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,o)=>n[0]-o[0]);for(let[n,o]of t)this.buffer.delete(n),this.emitter(o.payloadType,o.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var kb="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function Eb(e){var s,a;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let i=(a=(s=t.slice(r+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var 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 Mb(e){switch(e){case"json":return Em;case"regex-json":return km;case"xml":return Mm;default:return Tm}}var Lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lb(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lm(n);if(!Lm(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Or(e);return Or(t)!==null&&a===null?t:e}var Zs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,o,r,s;this.apiUrl=(n=t.apiUrl)!=null?n:kb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Mb(t.parserType),this.contextProviders=(r=t.contextProviders)!=null?r:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new ri(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,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let i=await o.json().catch(()=>({error:"Session initialization failed"}));throw o.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):o.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let r=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.sessionId),{sessionId:r.sessionId,expiresAt:new Date(r.expiresAt),flow:r.flow,config:{welcomeMessage:r.config.welcomeMessage,placeholder:r.config.placeholder,theme:r.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$/,""))||ui}/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 r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,s,a,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(r=this.config).onSessionExpired)==null||s.call(r);let H=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:H}),H}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([H])=>H!=="sessionId"&&H!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(Ol).map(H=>{var R,w,C;return{id:H.id,role:H.role,content:(C=(w=(R=H.contentParts)!=null?R:H.llmContent)!=null?w:H.rawContent)!=null?C:H.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},f=l.clientTools,m=!!(f&&f.length>0),x=m?am(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&v&&this.lastSentClientToolsFingerprint===x,L=!1,I=null,W;for(let H=0;;H++){let w={...g,...m&&(L||!E)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),W=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),W.status===409&&H===0&&m){let C=await W.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){L=!0,this.lastSentClientToolsFingerprint=null;continue}I=C!=null?C:{error:"Chat request failed"}}break}if(!W.ok){let H=I!=null?I:await W.json().catch(()=>({error:"Chat request failed"}));if(W.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let w=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:w}),w}if(W.status===429){let w=new Error(H.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let R=new Error(H.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!W.body){let H=new Error("No response body received");throw n({type:"error",error:H}),H}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(W.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 o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.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 o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),n({type:"status",status:"connecting"});let r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.signal},r)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:o.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,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let r=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,o){var l,u;let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,a;r&&(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:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,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(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),o={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),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&&(o.context=i)}return o}async buildPayload(t){var s,a;let o={messages:t.slice().filter(Ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return l-u}).map(i=>{var d,l,u;return{role:i.role,content:(u=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},r=[...Hl(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(r.length>0&&(o.clientTools=r),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&&(o.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...o},config:this.config});if(i&&typeof i=="object"){let d=i;return o.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=o.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return o}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=g,r(g),g},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,r(u)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.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,o){var Bt,an,ro,Eo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=D=>{let pe=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,De=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,Ke=D.tools?D.tools.map(Ne=>({...Ne,chunks:Ne.chunks?[...Ne.chunks]:void 0})):void 0;return{...D,reasoning:pe,toolCall:De,tools:Ke}},g=D=>{if(D.role!=="assistant"||D.variant)return!0;let pe=Array.isArray(D.contentParts)&&D.contentParts.length>0,De=typeof D.rawContent=="string"&&D.rawContent.trim()!=="";return typeof D.content=="string"&&D.content.trim()!==""||pe||De||!!D.stopReason},f=D=>{g(D)&&n({type:"message",message:u(D)})},m=null,x=null,v={current:null},E={current:null},L=!1,I=new Map,W=new Map,H=new Map,R=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},k=(D,pe,De="")=>`${D}::${pe}::${De}`,A=(D,pe)=>`${D}::${pe}::`,S=(D,pe,De,Ke)=>{let Ne=k(D,pe,De),Ve=H.get(Ne);if(Ve)return Ve;let ot=De?`-${De}`:"",It={id:`nested-${D}-${pe}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Ke,parentToolId:D,parentStepId:pe}};return H.set(Ne,It),f(It),It},_=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var pe,De,Ke,Ne,Ve;return _((Ve=(Ne=(Ke=(De=(pe=D.stepId)!=null?pe:D.step_id)!=null?De:D.step)!=null?Ke:D.parentId)!=null?Ne:D.flowStepId)!=null?Ve:D.flow_step_id)},K=D=>{var pe,De,Ke,Ne,Ve,ot,It;return _((It=(ot=(Ve=(Ne=(Ke=(De=(pe=D.callId)!=null?pe:D.call_id)!=null?De:D.requestId)!=null?Ke:D.request_id)!=null?Ne:D.toolCallId)!=null?Ve:D.tool_call_id)!=null?ot:D.stepId)!=null?It:D.step_id)},fe=o,ue=!1,ce=()=>{if(m)return m;let D;return!ue&&fe?(D=fe,ue=!0):fe&&E.current?D=`${fe}_${E.current}`:D=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:D,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},ke=(D,pe)=>{w.lastId=pe,D&&w.byStep.set(D,pe)},ve=(D,pe)=>{var Ve;let De=(Ve=D.reasoningId)!=null?Ve:D.id,Ke=V(D);if(De){let ot=String(De);return ke(Ke,ot),ot}if(Ke){let ot=w.byStep.get(Ke);if(ot)return w.lastId=ot,ot}if(w.lastId&&!pe)return w.lastId;if(!pe)return null;let Ne=`reason-${l()}`;return ke(Ke,Ne),Ne},He=D=>{let pe=I.get(D);if(pe)return pe;let De={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:D,status:"streaming",chunks:[]}};return I.set(D,De),f(De),De},Se=(D,pe)=>{C.lastId=pe,D&&C.byCall.set(D,pe)},ie=new Set,Q=new Map,re=new Set,be=new Map,he=D=>{if(!D)return!1;let pe=D.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},j=(D,pe)=>{var Ve;let De=(Ve=D.toolId)!=null?Ve:D.id,Ke=K(D);if(De){let ot=String(De);return Se(Ke,ot),ot}if(Ke){let ot=C.byCall.get(Ke);if(ot)return C.lastId=ot,ot}if(C.lastId&&!pe)return C.lastId;if(!pe)return null;let Ne=`tool-${l()}`;return Se(Ke,Ne),Ne},se=D=>{let pe=W.get(D);if(pe)return pe;let De={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:D,status:"pending"}};return W.set(D,De),f(De),De},Re=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let pe=Number(D);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let De=Date.parse(D);if(!Number.isNaN(De))return De}return Date.now()},ne=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},Z=new Map,oe=new Map,at=new Map,it=new Map,Le=null,de=(D,pe,De)=>{var It;let Ke=at.get(D);Ke||(Ke=[],at.set(D,Ke));let Ne=0,Ve=Ke.length;for(;Ne<Ve;){let qt=Ne+Ve>>>1;Ke[qt].seq<pe?Ne=qt+1:Ve=qt}((It=Ke[Ne])==null?void 0:It.seq)===pe?Ke[Ne]={seq:pe,text:De}:Ke.splice(Ne,0,{seq:pe,text:De});let ot="";for(let qt=0;qt<Ke.length;qt++)ot+=Ke[qt].text;return ot},Qe=(D,pe)=>{let De=ne(pe),Ke=oe.get(D.id),Ne=Lb(Ke,De);D.rawContent=Ne;let Ve=Z.get(D.id),ot=yt=>{var Ce;let st=(Ce=D.content)!=null?Ce:"";yt.trim()!==""&&(st.trim().length===0||yt.startsWith(st)||yt.trimStart().startsWith(st.trim()))&&(D.content=yt)},It=()=>{var yt;if(Ve){let st=(yt=Ve.close)==null?void 0:yt.call(Ve);st instanceof Promise&&st.catch(()=>{})}Z.delete(D.id),oe.delete(D.id),D.streaming=!1,f(D)};if(!Ve){ot(De),It();return}let qt=Or(Ne);if(qt!==null&&qt.trim()!==""){ot(qt),It();return}let Xt=yt=>{var le;let st=typeof yt=="string"?yt:(le=yt==null?void 0:yt.text)!=null?le:null;if(st!==null&&st.trim()!=="")return st;let Ce=Ve.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:De},G;try{G=Ve.processChunk(Ne)}catch{ot(De),It();return}if(G instanceof Promise){G.then(yt=>{ot(Xt(yt)),It()}).catch(()=>{ot(De),It()});return}ot(Xt(G)),It()},We=[],q=!1,me,tt=()=>{q||(q=!0,queueMicrotask(()=>{q=!1,me()}))},Tt=new pi((D,pe)=>{We.push({payloadType:D,payload:pe}),tt()}),te=null,ze=new Map,Nn=(Bt=this.config.iterationDisplay)!=null?Bt:"separate";for(me=()=>{var D,pe,De,Ke,Ne,Ve,ot,It,qt,Xt,G,yt,st,Ce,le,Ze,Zt,jt,Rn,xn,ut,kt,Xe,Ut,ln,Sn,An,bn,Mo,Ct,zn,qn,No,ho,vt,yr,Lo,vr,_n,qr,Zo,_o,St,jn,Kn,Pn,Lt,so,ao,Gn,er,Vo,tr,Yn,Ht,Wn,io,nr,$o,or,Io,Qn,bo,gt,en,tn,Xn,rr,xe,yo,lo,$,jr,Ro,Uo,zo,Po,vo,As,Jn,Zn,xo,wo,xr,qo,Tn,Wo,Kr,wr,Gr,Aa,Yr,Ta,Qr,bt,Ts,co,Vn,ka,Ea,Xr,jo,ks,sr,Es,Ms,Ls,Is,$n,Jr,Bo,Ho,Rs,Ma,Ps,Ws,Cr,La,Ia,Ra,Pa,rl,Sr,ar,Wa,Bs,ir,Ba,Hs,lr,Ds,Ha,Ko,Da,cr,Dt,Zr,es;for(let Ar=0;Ar<We.length;Ar++){let $e=We[Ar].payloadType,T=We[Ar].payload;if($e==="reason_start"){let U=(D=ve(T,!0))!=null?D:`reason-${l()}`,P=He(U);P.reasoning=(pe=P.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(Ke=P.reasoning.startedAt)!=null?Ke:Re((De=T.startedAt)!=null?De:T.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",f(P)}else if($e==="reason_delta"||$e==="reason_chunk"){let U=(Ve=(Ne=ve(T,!1))!=null?Ne:ve(T,!0))!=null?Ve:`reason-${l()}`,P=He(U);P.reasoning=(ot=P.reasoning)!=null?ot:{id:U,status:"streaming",chunks:[]},P.reasoning.startedAt=(qt=P.reasoning.startedAt)!=null?qt:Re((It=T.startedAt)!=null?It:T.timestamp);let J=(yt=(G=(Xt=T.reasoningText)!=null?Xt:T.text)!=null?G:T.delta)!=null?yt:"";if(J&&T.hidden!==!0){let ae=typeof T.sequenceIndex=="number"?T.sequenceIndex:void 0;if(ae!==void 0){let Y=de(U,ae,String(J));P.reasoning.chunks=[Y]}else P.reasoning.chunks.push(String(J))}if(P.reasoning.status=T.done?"complete":"streaming",T.done){P.reasoning.completedAt=Re((st=T.completedAt)!=null?st:T.timestamp);let ae=(Ce=P.reasoning.startedAt)!=null?Ce:Date.now();P.reasoning.durationMs=Math.max(0,((le=P.reasoning.completedAt)!=null?le:Date.now())-ae)}P.streaming=P.reasoning.status!=="complete",f(P)}else if($e==="reason_complete"){let U=(Zt=(Ze=ve(T,!1))!=null?Ze:ve(T,!0))!=null?Zt:`reason-${l()}`,P=I.get(U);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Re((jt=T.completedAt)!=null?jt:T.timestamp);let ae=(Rn=P.reasoning.startedAt)!=null?Rn:Date.now();P.reasoning.durationMs=Math.max(0,((xn=P.reasoning.completedAt)!=null?xn:Date.now())-ae),P.streaming=!1,f(P)}let J=V(T);J&&w.byStep.delete(J)}else if($e==="tool_start"){let U=(ut=j(T,!0))!=null?ut:`tool-${l()}`,P=(kt=T.toolName)!=null?kt:T.name;if(he(P)){ie.add(U);continue}let J=se(U),ae=(Xe=J.toolCall)!=null?Xe:{id:U,status:"pending"};ae.name=P!=null?P:ae.name,ae.status="running",T.args!==void 0?ae.args=T.args:T.parameters!==void 0&&(ae.args=T.parameters),ae.startedAt=(ln=ae.startedAt)!=null?ln:Re((Ut=T.startedAt)!=null?Ut:T.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,J.toolCall=ae,J.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(J.agentMetadata={executionId:(Sn=Y==null?void 0:Y.executionId)!=null?Sn:T.executionId,iteration:(An=Y==null?void 0:Y.iteration)!=null?An:T.iteration}),f(J)}else if($e==="tool_chunk"||$e==="tool_delta"){let U=(Mo=(bn=j(T,!1))!=null?bn:j(T,!0))!=null?Mo:`tool-${l()}`;if(ie.has(U))continue;let P=se(U),J=(Ct=P.toolCall)!=null?Ct:{id:U,status:"running"};J.startedAt=(qn=J.startedAt)!=null?qn:Re((zn=T.startedAt)!=null?zn:T.timestamp);let ae=(vt=(ho=(No=T.text)!=null?No:T.delta)!=null?ho:T.message)!=null?vt:"";ae&&(J.chunks=(yr=J.chunks)!=null?yr:[],J.chunks.push(String(ae))),J.status="running",P.toolCall=J,P.streaming=!0;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(_n=P.agentMetadata)!=null?_n:{executionId:(Lo=Y==null?void 0:Y.executionId)!=null?Lo:T.executionId,iteration:(vr=Y==null?void 0:Y.iteration)!=null?vr:T.iteration}),f(P)}else if($e==="tool_complete"){let U=(Zo=(qr=j(T,!1))!=null?qr:j(T,!0))!=null?Zo:`tool-${l()}`;if(ie.has(U)){ie.delete(U);continue}let P=se(U),J=(_o=P.toolCall)!=null?_o:{id:U,status:"running"};J.status="complete",T.result!==void 0&&(J.result=T.result),typeof T.duration=="number"&&(J.duration=T.duration),J.completedAt=Re((St=T.completedAt)!=null?St:T.timestamp);let ae=(jn=T.duration)!=null?jn:T.executionTime;if(typeof ae=="number")J.durationMs=ae;else{let Fe=(Kn=J.startedAt)!=null?Kn:Date.now();J.durationMs=Math.max(0,((Pn=J.completedAt)!=null?Pn:Date.now())-Fe)}P.toolCall=J,P.streaming=!1;let Y=T.agentContext;(Y||T.executionId)&&(P.agentMetadata=(ao=P.agentMetadata)!=null?ao:{executionId:(Lt=Y==null?void 0:Y.executionId)!=null?Lt:T.executionId,iteration:(so=Y==null?void 0:Y.iteration)!=null?so:T.iteration}),f(P);let Me=K(T);Me&&C.byCall.delete(Me)}else if($e==="step_await"&&T.awaitReason==="local_tool_required"&&T.toolName){let U=typeof T.toolCallId=="string"&&T.toolCallId.length>0?T.toolCallId:void 0,P=(Gn=U!=null?U:T.toolId)!=null?Gn:`local-${l()}`,J=se(P),ae=T.toolName,Y=Gs(ae),Me=(er=J.toolCall)!=null?er:{id:P,status:"pending"};Me.name=ae,Me.args=T.parameters,Me.status=Y?"running":"complete",Me.chunks=(Vo=Me.chunks)!=null?Vo:[],Me.startedAt=(Yn=Me.startedAt)!=null?Yn:Re((tr=T.startedAt)!=null?tr:T.timestamp),Y?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Ht=Me.completedAt)!=null?Ht:Me.startedAt,J.toolCall=Me,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(io=T.executionId)!=null?io:(Wn=J.agentMetadata)==null?void 0:Wn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(J)}else if($e==="text_start"){if((nr=T.toolContext)!=null&&nr.toolId)continue;let U=T.partId;if(U!==void 0&&E.current!==null&&U!==E.current){let P=m;P&&(P.streaming=!1,f(P),Le=P,m=null,L=!0)}U!==void 0&&(E.current=U)}else if($e==="text_end"){if(($o=T.toolContext)!=null&&$o.toolId)continue;let U=m;U&&(U.streaming=!1,f(U),Le=U,m=null,L=!0)}else if($e==="step_chunk"||$e==="step_delta"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((Io=(or=T.id)!=null?or:J.stepId)!=null?Io:`step-${l()}`),lt=T.partId!==void 0&&T.partId!==null?String(T.partId):"",Je=`${J.toolId}::${Fe}`,Wt=R.get(Je);if(lt!==""&&Wt!==void 0&&Wt!==""&&Wt!==lt){let rt=H.get(k(J.toolId,Fe,Wt));rt&&rt.streaming!==!1&&(rt.streaming=!1,f(rt))}lt!==""&&R.set(Je,lt);let _t=S(J.toolId,Fe,lt,J.executionId),un=(en=(gt=(bo=(Qn=T.text)!=null?Qn:T.delta)!=null?bo:T.content)!=null?gt:T.chunk)!=null?en:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),T.isComplete&&(_t.streaming=!1,f(_t));continue}let ae=T.partId;if(ae!==void 0&&E.current!==null&&ae!==E.current){let Fe=m;Fe&&(Fe.streaming=!1,f(Fe),Le=Fe,m=null,L=!0)}ae!==void 0&&(E.current=ae);let Y=ae!==void 0&&(tn=it.get(ae))!=null?tn:ce();ae!==void 0&&(Y.partId||(Y.partId=ae),it.set(ae,Y));let Me=(yo=(xe=(rr=(Xn=T.text)!=null?Xn:T.delta)!=null?rr:T.content)!=null?xe:T.chunk)!=null?yo:"";if(Me){let Fe=typeof T.seq=="number"?T.seq:void 0,lt=ae!=null?ae:Y.id,Je=Fe!==void 0?de(lt,Fe,String(Me)):((lo=oe.get(Y.id))!=null?lo:"")+Me;Y.rawContent=Je,Z.has(Y.id)||Z.set(Y.id,this.createStreamParser());let Wt=Z.get(Y.id),_t=Je.trim().startsWith("{")||Je.trim().startsWith("[");if(_t&&oe.set(Y.id,Je),Wt.__isPlainTextParser===!0){Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y);continue}let rt=Wt.processChunk(Je);if(rt instanceof Promise)rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null&&Jt.trim()!=="")Y.content=Jt,f(Y);else if(!_t&&!Je.trim().startsWith("<")){let wn=m,Gt=wn&&wn.id===Y.id?wn:Y;Gt.id===Y.id&&(Gt.content=Fe!==void 0?Je:Gt.content+Me,oe.delete(Gt.id),Z.delete(Gt.id),Gt.rawContent=void 0,f(Gt))}}).catch(()=>{Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y)});else{let ft=typeof rt=="string"?rt:($=rt==null?void 0:rt.text)!=null?$:null;ft!==null&&ft.trim()!==""?(Y.content=ft,f(Y)):!_t&&!Je.trim().startsWith("<")&&(Y.content=Fe!==void 0?Je:Y.content+Me,oe.delete(Y.id),Z.delete(Y.id),Y.rawContent=void 0,f(Y))}}if(T.isComplete){let Fe=(Ro=(jr=T.result)==null?void 0:jr.response)!=null?Ro:Y.content;if(Fe){let lt=oe.get(Y.id),Je=lt!=null?lt:ne(Fe);Y.rawContent=Je;let Wt=Z.get(Y.id),_t=null,un=!1;if(Wt&&(_t=Wt.getExtractedText(),_t===null&&(_t=Or(Je)),_t===null)){let rt=Wt.processChunk(Je);rt instanceof Promise?(un=!0,rt.then(ft=>{var je;let Jt=typeof ft=="string"?ft:(je=ft==null?void 0:ft.text)!=null?je:null;if(Jt!==null){let wn=m;wn&&wn.id===Y.id&&(wn.content=Jt,wn.streaming=!1,Z.delete(wn.id),oe.delete(wn.id),f(wn))}})):_t=typeof rt=="string"?rt:(Uo=rt==null?void 0:rt.text)!=null?Uo:null}if(!un){_t!==null&&_t.trim()!==""?Y.content=_t:oe.has(Y.id)||(Y.content=ne(Fe));let rt=Z.get(Y.id);if(rt){let ft=(zo=rt.close)==null?void 0:zo.call(rt);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(Y.id)}oe.delete(Y.id),Y.streaming=!1,f(Y)}}}}else if($e==="step_complete"){let U=T.stepType,P=T.executionType;if(U==="tool"||P==="context")continue;let J=T.toolContext;if(J!=null&&J.toolId){let Fe=String((vo=(Po=T.id)!=null?Po:J.stepId)!=null?vo:"");if(Fe){let lt=A(J.toolId,Fe);for(let[Je,Wt]of H)Je.startsWith(lt)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${J.toolId}::${Fe}`)}continue}let ae=T.stopReason;if(L){if(m!==null){let Je=m;ae&&(Je.stopReason=ae),Z.delete(Je.id),oe.delete(Je.id),Je.streaming!==!1&&(Je.streaming=!1,f(Je))}let Fe=(As=T.result)==null?void 0:As.response,lt=Le;lt&&(ae&&(lt.stopReason=ae),Fe!=null?Qe(lt,Fe):(Z.delete(lt.id),oe.delete(lt.id))),Le=null;continue}let Y=(Jn=T.result)==null?void 0:Jn.response,Me=ce();if(ae&&(Me.stopReason=ae),Y!=null){let Fe=Z.get(Me.id),lt=!1,Je=!1;if(Fe){let Wt=Fe.getExtractedText(),_t=oe.get(Me.id),un=_t!=null?_t:ne(Y);if(Me.rawContent=un,Wt!==null&&Wt.trim()!=="")Me.content=Wt,lt=!0;else{let rt=Or(un);if(rt!==null)Me.content=rt,lt=!0;else{let ft=Fe.processChunk(un);if(ft instanceof Promise)Je=!0,ft.then(Jt=>{var wn;let je=typeof Jt=="string"?Jt:(wn=Jt==null?void 0:Jt.text)!=null?wn:null;if(je!==null&&je.trim()!==""){let Gt=m;Gt&&Gt.id===Me.id&&(Gt.content=je,Gt.streaming=!1,Z.delete(Gt.id),oe.delete(Gt.id),f(Gt))}else{let Gt=Fe.getExtractedText(),yn=m;yn&&yn.id===Me.id&&(Gt!==null&&Gt.trim()!==""?yn.content=Gt:oe.has(yn.id)||(yn.content=ne(Y)),yn.streaming=!1,Z.delete(yn.id),oe.delete(yn.id),f(yn))}});else{let Jt=typeof ft=="string"?ft:(Zn=ft==null?void 0:ft.text)!=null?Zn:null;if(Jt!==null&&Jt.trim()!=="")Me.content=Jt,lt=!0;else{let je=Fe.getExtractedText();je!==null&&je.trim()!==""&&(Me.content=je,lt=!0)}}}}}if(!Je){if(!Me.rawContent){let Wt=oe.get(Me.id);Me.rawContent=Wt!=null?Wt:ne(Y)}if(!lt&&!oe.has(Me.id)&&(Me.content=ne(Y)),Fe){let Wt=(xo=Fe.close)==null?void 0:xo.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}}else Z.delete(Me.id),oe.delete(Me.id),Me.streaming=!1,f(Me)}else if($e==="flow_complete"){let U=(wo=T.result)==null?void 0:wo.response;if(L){if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}}else if(U!=null){let P=ce(),J=oe.get(P.id),ae=J!=null?J:ne(U);P.rawContent=ae;let Y=ne(U),Me=Z.get(P.id);if(Me){let Je=Or(ae);if(Je!==null)Y=Je;else{let Wt=Me.processChunk(ae);Wt instanceof Promise&&Wt.then(un=>{var ft;let rt=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;rt!==null&&(P.content=rt,P.streaming=!1,f(P))});let _t=Me.getExtractedText();_t!==null&&(Y=_t)}}Z.delete(P.id),oe.delete(P.id);let Fe=Y!==P.content,lt=P.streaming!==!1;Fe&&(P.content=Y),P.streaming=!1,(Fe||lt)&&f(P)}else if(m!==null){let P=m;Z.delete(P.id),oe.delete(P.id),P.streaming!==!1&&(P.streaming=!1,f(P))}n({type:"status",status:"idle"})}else if($e==="agent_start")te={executionId:T.executionId,agentId:(xr=T.agentId)!=null?xr:"virtual",agentName:(qo=T.agentName)!=null?qo:"",status:"running",currentIteration:0,maxTurns:(Tn=T.maxTurns)!=null?Tn:1,startedAt:Re(T.startedAt)};else if($e==="agent_iteration_start"){if(te&&(te.currentIteration=T.iteration),Nn==="separate"&&T.iteration>1){let U=m;U&&(U.streaming=!1,f(U),ze.set(T.iteration-1,U),m=null)}}else if($e==="agent_turn_start")x=null;else if($e==="agent_turn_delta"){if(T.contentType==="text"){let U=ce();U.content+=(Wo=T.delta)!=null?Wo:"",U.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId,agentName:te==null?void 0:te.agentName},x=U,f(U)}else if(T.contentType==="thinking"){let U=(Kr=T.turnId)!=null?Kr:`agent-think-${T.iteration}`,P=He(U);P.reasoning=(wr=P.reasoning)!=null?wr:{id:U,status:"streaming",chunks:[]},P.reasoning.chunks.push((Gr=T.delta)!=null?Gr:""),P.agentMetadata={executionId:T.executionId,iteration:T.iteration,turnId:T.turnId},f(P)}else if(T.contentType==="tool_input"){let U=(Aa=T.toolCallId)!=null?Aa:C.lastId;if(U){let P=W.get(U);P!=null&&P.toolCall&&(P.toolCall.chunks=(Yr=P.toolCall.chunks)!=null?Yr:[],P.toolCall.chunks.push((Ta=T.delta)!=null?Ta:""),f(P))}}}else if($e==="agent_turn_complete"){let U=T.turnId;if(U){let ae=I.get(U);if(ae!=null&&ae.reasoning){ae.reasoning.status="complete",ae.reasoning.completedAt=Re(T.completedAt);let Y=(Qr=ae.reasoning.startedAt)!=null?Qr:Date.now();ae.reasoning.durationMs=Math.max(0,((bt=ae.reasoning.completedAt)!=null?bt:Date.now())-Y),ae.streaming=!1,f(ae)}}let P=T.stopReason,J=m!=null?m:x;if(P&&J!==null){let ae=T.turnId;(!ae||((Ts=J.agentMetadata)==null?void 0:Ts.turnId)===ae)&&(J.stopReason=P,f(J))}}else if($e==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let U=(co=T.toolCallId)!=null?co:`agent-tool-${l()}`;Se(K(T),U);let P=se(U),J=(Vn=P.toolCall)!=null?Vn:{id:U,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};J.name=(Ea=(ka=T.toolName)!=null?ka:T.name)!=null?Ea:J.name,J.status="running",T.parameters!==void 0&&(J.args=T.parameters),J.startedAt=Re((Xr=T.startedAt)!=null?Xr:T.timestamp),P.toolCall=J,P.streaming=!0,P.agentMetadata={executionId:T.executionId,iteration:T.iteration},f(P)}else if($e==="agent_tool_delta"){let U=(jo=T.toolCallId)!=null?jo:C.lastId;if(U){let P=(ks=W.get(U))!=null?ks:se(U);P.toolCall&&(P.toolCall.chunks=(sr=P.toolCall.chunks)!=null?sr:[],P.toolCall.chunks.push((Es=T.delta)!=null?Es:""),P.toolCall.status="running",P.streaming=!0,f(P))}}else if($e==="agent_tool_complete"){let U=(Ms=T.toolCallId)!=null?Ms:C.lastId;if(U){let P=(Ls=W.get(U))!=null?Ls:se(U);if(P.toolCall){P.toolCall.status="complete",T.result!==void 0&&(P.toolCall.result=T.result),typeof T.executionTime=="number"&&(P.toolCall.durationMs=T.executionTime),P.toolCall.completedAt=Re((Is=T.completedAt)!=null?Is:T.timestamp),P.streaming=!1,f(P);let J=K(T);J&&C.byCall.delete(J)}}}else if($e==="agent_media"){let U=Array.isArray(T.media)?T.media:[],P=[];for(let J of U){if(!J||typeof J!="object")continue;let ae=J,Y=typeof ae.type=="string"?ae.type:void 0,Me=typeof ae.mediaType=="string"?ae.mediaType.toLowerCase():"",Fe=null,lt="";if(Y==="media"){let Je=typeof ae.data=="string"?ae.data:void 0;if(!Je)continue;lt=Me.length>0?Me:"application/octet-stream",Fe=`data:${lt};base64,${Je}`}else if(Y==="image-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else if(Y==="file-url"){let Je=typeof ae.url=="string"?ae.url:void 0;if(!Je)continue;lt=Me,Fe=Je}else continue;if(Fe)if(Y==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:Fe,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:Fe,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:Fe,mimeType:lt});else{let Je=lt||"application/octet-stream";P.push({type:"file",data:Fe,mimeType:Je,filename:Eb(Je)})}}if(P.length>0){let J=l(),ae=T.toolCallId,Me={id:`agent-media-${typeof ae=="string"&&ae.length>0?`${ae}-${J}`:String(J)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:J,agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(Me);let Fe=m;Fe&&(Fe.streaming=!1,f(Fe)),m=null,v.current=null}}else if($e!=="agent_iteration_complete"){if($e==="agent_reflection"||$e==="agent_reflect"){let U=`agent-reflection-${T.executionId}-${T.iteration}`,P={id:U,role:"assistant",content:($n=T.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(Jr=T.reflection)!=null?Jr:""]},agentMetadata:{executionId:T.executionId,iteration:T.iteration}};f(P)}else if($e==="agent_complete"){te&&(te.status=T.success?"complete":"error",te.completedAt=Re(T.completedAt),te.stopReason=T.stopReason);let U=m;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if($e==="agent_error"){let U=typeof T.error=="string"?T.error:(Ho=(Bo=T.error)==null?void 0:Bo.message)!=null?Ho:"Agent execution error";T.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if($e!=="agent_ping"){if($e==="agent_approval_start"){let U=(Rs=T.approvalId)!=null?Rs:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Ma=te==null?void 0:te.agentId)!=null?Ma:"virtual",executionId:(Ws=(Ps=T.executionId)!=null?Ps:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Cr=T.toolName)!=null?Cr:"",toolType:T.toolType,description:(Ia=T.description)!=null?Ia:`Execute ${(La=T.toolName)!=null?La:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="step_await"&&T.awaitReason==="approval_required"){let U=(Ra=T.approvalId)!=null?Ra:`approval-${l()}`,P={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Pa=te==null?void 0:te.agentId)!=null?Pa:"virtual",executionId:(Sr=(rl=T.executionId)!=null?rl:te==null?void 0:te.executionId)!=null?Sr:"",toolName:(ar=T.toolName)!=null?ar:"",toolType:T.toolType,description:(Bs=T.description)!=null?Bs:`Execute ${(Wa=T.toolName)!=null?Wa:"tool"}`,...typeof T.reason=="string"&&T.reason?{reason:T.reason}:{},parameters:T.parameters}};f(P)}else if($e==="agent_approval_complete"){let U=T.approvalId;if(U){let J={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(ir=T.decision)!=null?ir:"approved",agentId:(Ba=te==null?void 0:te.agentId)!=null?Ba:"virtual",executionId:(lr=(Hs=T.executionId)!=null?Hs:te==null?void 0:te.executionId)!=null?lr:"",toolName:(Ds=T.toolName)!=null?Ds:"",description:(Ha=T.description)!=null?Ha:"",resolvedAt:Date.now()}};f(J)}}else if($e==="artifact_start"||$e==="artifact_delta"||$e==="artifact_update"||$e==="artifact_complete"){if($e==="artifact_start"){let U=T.artifactType,P=String(T.id),J=typeof T.title=="string"?T.title:void 0;if(n({type:"artifact_start",id:P,artifactType:U,title:J,component:typeof T.component=="string"?T.component:void 0}),be.set(P,{markdown:"",title:J}),!re.has(P)){re.add(P);let ae={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:J,artifactType:U,status:"streaming"}})};Q.set(P,ae),f(ae)}}else if($e==="artifact_delta"){let U=String(T.id),P=typeof T.delta=="string"?T.delta:String((Ko=T.delta)!=null?Ko:"");n({type:"artifact_delta",id:U,artDelta:P});let J=be.get(U);J&&(J.markdown+=P)}else if($e==="artifact_update"){let U=T.props&&typeof T.props=="object"&&!Array.isArray(T.props)?T.props:{};n({type:"artifact_update",id:String(T.id),props:U,component:typeof T.component=="string"?T.component:void 0})}else if($e==="artifact_complete"){let U=String(T.id);n({type:"artifact_complete",id:U});let P=Q.get(U);if(P){P.streaming=!1;try{let J=JSON.parse((Da=P.rawContent)!=null?Da:"{}");if(J.props){J.props.status="complete";let ae=be.get(U);ae!=null&&ae.markdown&&(J.props.markdown=ae.markdown)}P.rawContent=JSON.stringify(J)}catch{}be.delete(U),f(P),Q.delete(U)}}}else if($e==="transcript_insert"){let U=T.message;if(!U||typeof U!="object")continue;let P=String((cr=U.id)!=null?cr:`msg-${l()}`),J=U.role,Y={id:P,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(Y),Y.rawContent)try{let Me=JSON.parse(Y.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}m=null,v.current=null,Z.delete(P),oe.delete(P)}else if($e==="error"||$e==="step_error"||$e==="dispatch_error"||$e==="flow_error"){let U=null;if(T.error instanceof Error)U=T.error;else if($e==="dispatch_error"){let P=(Zr=T.message)!=null?Zr:T.error;P!=null&&P!==""&&(U=new Error(String(P)))}else if($e==="step_error"||$e==="flow_error"){let P=T.error;typeof P=="string"&&P!==""?U=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&(U=new Error(String((es=P.message)!=null?es:P)))}else $e==="error"&&T.error!=null&&T.error!==""&&(U=new Error(String(T.error)));if(U){n({type:"error",error:U});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}We.length=0};;){let{done:D,value:pe}=await r.read();if(D)break;a+=s.decode(pe,{stream:!0});let De=a.split(`
10
10
 
11
11
  `);a=(an=De.pop())!=null?an:"";for(let Ke of De){let Ne=Ke.split(`
12
12
  `),Ve="message",ot="";for(let Xt of Ne)Xt.startsWith("event:")?Ve=Xt.replace("event:","").trim():Xt.startsWith("data:")&&(ot+=Xt.replace("data:","").trim());if(!ot)continue;let It;try{It=JSON.parse(ot)}catch(Xt){n({type:"error",error:Xt instanceof Error?Xt:new Error("Failed to parse chat stream payload")});continue}let qt=Ve!=="message"?Ve:(ro=It.type)!=null?ro:"message";if((Eo=this.onSSEEvent)==null||Eo.call(this,qt,It),this.parseSSEEvent){v.current=m;let Xt=await this.handleCustomSSEEvent(It,n,v,f,l,E);if(v.current&&v.current!==m&&(m=v.current),Xt)continue}Tt.push(qt,It),me()}}Tt.flushPending(),me(),Tt.destroy()}};function mi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function Fl(e){return{type:"text",text:e}}var Im=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ib=["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"],Qo=[...Im,...Ib];function Rb(e){return Im.includes(e)||e.startsWith("image/")}function fi(e){return Rb(e.type)}async function Rm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;fi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Pm(e,t=Qo,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 Pb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wm(e,t){let n=Pb(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 hi=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 o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({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 o=this.ensureContext(),r=this.pcmToFloat32(n),s=o.createBuffer(1,r.length,this.sampleRate);s.getChannelData(0).set(r);let a=o.createBufferSource();a.buffer=s,a.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}};var bi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,o,r,s){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 u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(o==="silence"?d<r.threshold:d>=r.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=r.duration&&(this.fired=!0,s()):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 ta=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 bi;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,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let r=this.w;if(!r||!r.location)throw new Error("Window object or location not available");let s=r.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(o=this.config)==null?void 0:o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${s}//${a}/ws/agents/${i}/voice?token=...`,g=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let x=!1,v=L=>{x||(x=!0,clearTimeout(E),m(new Error(L)))},E=setTimeout(()=>v("WebSocket connection timed out."+g),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+g)},{once:!0}),this.ws.addEventListener("close",L=>{if(!L.wasClean&&!x){let I=L.code!==1006?` (code ${L.code})`:"";v("WebSocket connection failed"+I+"."+g)}},{once:!0})}),this.sendHeartbeat()}catch(r){throw this.ws=null,this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}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(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,o;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(r=>r({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(r=>r("speaking")),this.playAudio(t.response.audio).catch(r=>this.errorCallbacks.forEach(s=>s(r instanceof Error?r:new Error(String(r)))))):(o=t.response.audio)!=null&&o.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(r=>r("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(r=>r(new Error(t.error))),this.statusCallbacks.forEach(r=>r("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new hi(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,o,r;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(r=(o=this.config)==null?void 0:o.silenceThreshold)!=null?r:.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 u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",g=new Blob(this.audioChunks,{type:u});await this.sendAudio(g),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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,o=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:o,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(o=>o(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(o=>o("error"));return}try{let o=await this.blobToBase64(t),r=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:r,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(o){this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,o)=>{let r=new FileReader;r.onload=()=>{let a=r.result.split(",")[1];n(a)},r.onerror=o,r.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),o=new Uint8Array(n.length);for(let l=0;l<n.length;l++)o[l]=n.charCodeAt(l);let r=t.format||"mp3",s=r==="mp3"?"audio/mpeg":`audio/${r}`,a=new Blob([o],{type:s}),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 Fr=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 o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,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=r=>{var i;let s=Array.from(r.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=r.results[r.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=r=>{this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(r=>r("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(r=>r(o)),this.statusCallbacks.forEach(r=>r("error")),o}}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 na(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(e.runtype);case"browser":if(!Fr.isSupported())throw new Error("Browser speech recognition not supported");return new Fr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Bm(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return na({type:"runtype",runtype:e.runtype});if(Fr.isSupported())return na({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Nl(e){try{return Bm(e),!0}catch{return!1}}var Wb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Bb(e,t){return Wb.some(n=>e[n]!==t[n])}function Hm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry \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?`${o}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/persona",
3
- "version": "3.34.0",
3
+ "version": "3.34.1",
4
4
  "description": "Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -4121,3 +4121,58 @@ describe('AgentWidgetClient - non-client-token paths always send full clientTool
4121
4121
  }
4122
4122
  });
4123
4123
  });
4124
+
4125
+ describe('AgentWidgetClient - Feedback request builder', () => {
4126
+ const INIT_RESPONSE = {
4127
+ sessionId: 'sess_123',
4128
+ expiresAt: new Date(Date.now() + 60_000).toISOString(),
4129
+ flow: {},
4130
+ config: { welcomeMessage: 'hi', placeholder: 'type…', theme: {} },
4131
+ };
4132
+
4133
+ function mockInitAndFeedback() {
4134
+ const feedbackBodies: Array<Record<string, unknown>> = [];
4135
+ global.fetch = vi.fn().mockImplementation(async (url: string, options: { body: string }) => {
4136
+ if (typeof url === 'string' && url.endsWith('/v1/client/feedback')) {
4137
+ feedbackBodies.push(JSON.parse(options.body));
4138
+ return { ok: true, status: 200, json: async () => ({}) };
4139
+ }
4140
+ // init request
4141
+ return { ok: true, status: 200, json: async () => INIT_RESPONSE };
4142
+ });
4143
+ return feedbackBodies;
4144
+ }
4145
+
4146
+ it('includes the client token in the feedback request body', async () => {
4147
+ const feedbackBodies = mockInitAndFeedback();
4148
+ const client = new AgentWidgetClient({
4149
+ apiUrl: 'http://localhost:8000',
4150
+ clientToken: 'ct_live_abc123',
4151
+ });
4152
+ await client.initSession();
4153
+
4154
+ await client.sendFeedback({ sessionId: 'sess_123', messageId: 'm1', type: 'upvote' });
4155
+
4156
+ expect(feedbackBodies).toHaveLength(1);
4157
+ expect(feedbackBodies[0]).toEqual({
4158
+ sessionId: 'sess_123',
4159
+ messageId: 'm1',
4160
+ type: 'upvote',
4161
+ token: 'ct_live_abc123',
4162
+ });
4163
+ });
4164
+
4165
+ it('sends the token on csat/nps submissions too', async () => {
4166
+ const feedbackBodies = mockInitAndFeedback();
4167
+ const client = new AgentWidgetClient({
4168
+ apiUrl: 'http://localhost:8000',
4169
+ clientToken: 'ct_live_xyz789',
4170
+ });
4171
+ await client.initSession();
4172
+
4173
+ await client.sendFeedback({ sessionId: 'sess_123', type: 'csat', rating: 5 });
4174
+
4175
+ expect(feedbackBodies[0].token).toBe('ct_live_xyz789');
4176
+ expect(feedbackBodies[0].rating).toBe(5);
4177
+ });
4178
+ });
package/src/client.ts CHANGED
@@ -482,12 +482,21 @@ export class AgentWidgetClient {
482
482
  console.debug("[AgentWidgetClient] sending feedback", feedback);
483
483
  }
484
484
 
485
+ // Scope the feedback request to the caller's client token, sourced the same
486
+ // way as the chat/init requests. sendFeedback is client-token-mode only
487
+ // (guarded above), so clientToken is always present here and an API key can
488
+ // never leak into the body. Left undefined only when the embed has none.
489
+ const requestBody = {
490
+ ...feedback,
491
+ ...(this.config.clientToken && { token: this.config.clientToken }),
492
+ };
493
+
485
494
  const response = await fetch(this.getFeedbackApiUrl(), {
486
495
  method: 'POST',
487
496
  headers: {
488
497
  'Content-Type': 'application/json',
489
498
  },
490
- body: JSON.stringify(feedback),
499
+ body: JSON.stringify(requestBody),
491
500
  });
492
501
 
493
502
  if (!response.ok) {