@runtypelabs/persona 3.34.0 → 3.34.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +1 -1
- package/dist/theme-editor.js +1 -1
- package/package.json +1 -1
- package/src/client.test.ts +55 -0
- package/src/client.ts +10 -1
package/dist/theme-editor.cjs
CHANGED
|
@@ -6,7 +6,7 @@ ${t}`:"")+(e.description?`
|
|
|
6
6
|
${e.description}`:"");return window.confirm(n)},ib=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)}},lb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},cb=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var hr=require("partial-json");var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},No=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o};var Xl="ask_user_question",ga=8,bs="data-persona-ask-sheet-for",db="Other",pb="Other\u2026",Om="Type your own answer here",Fm="Send",ub="Next",mb="Back",gb="Submit all",fb="Skip",hb=3,Jl="data-ask-current-index",Zl="data-ask-question-count",Nm="data-ask-answers",ec="data-ask-grouped",_m="data-ask-layout",bb=e=>e.layout==="pills"?"pills":"rows",yb=e=>e.getAttribute(_m)==="pills"?"pills":"rows",Dm=!1,Vm=e=>e.replace(/["\\]/g,"\\$&"),Vr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Xl,tc=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},ys=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=(0,hr.parse)(r,hr.STR|hr.OBJ|hr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},fa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ga&&!Dm&&(Dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ga}.`)),t.slice(0,ga)},vb=e=>{var t;return(t=fa(e)[0])!=null?t:null},xb=(e,t)=>{var n;return(n=fa(e)[t])!=null?n:null},wb=(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))},$m=(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},Cb=(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=$m(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sb=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},Ab=(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<hb;m++)s.appendChild(Sb(o));return s}if(d.forEach((m,x)=>{s.appendChild(Cb(m,x,o,a))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?db:pb;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"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=t.freeTextPlaceholder)!=null?u:Om,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(g=t.freeTextLabel)!=null?g:m),v.appendChild(M),x.appendChild(v);let I=$m(o,a,d.length);I&&x.appendChild(I),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},Um=(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:Om,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:Fm,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Tb=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:Fm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},kb=(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:mb,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:fb,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:gb:(f=n.nextLabel)!=null?f:ub,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},$r=e=>{let t=e.getAttribute(Nm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},zm=(e,t)=>{e.setAttribute(Nm,JSON.stringify(t))},fo=e=>{var n;let t=Number((n=e.getAttribute(Jl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Eb=(e,t)=>{e.setAttribute(Jl,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(Zl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},br=e=>e.getAttribute(ec)==="true",Mb=(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},Lb=(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)))},Ei=(e,t)=>{let{payload:n}=ys(t),o=fa(n),r=$r(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},qm=e=>{let t=$r(e),n=fo(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=""},jm=e=>{if(!br(e))return;let t=$r(e),n=fo(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}},nc=(e,t,n)=>{let o=tc(n),r=yb(e),{payload:s,complete:a}=ys(t),i=br(e),d=fo(e),l=vs(e),u=i?xb(s,d):vb(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 R=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let R=Ab(u,o,a,r);v.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Um(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!M?e.appendChild(Tb(o)):(!g||i)&&M&&M.remove(),e.setAttribute("data-multi-select",g?"true":"false");let I=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=kb(d,l,o);I?I.replaceWith(R):e.appendChild(R)}else I&&I.remove();qm(e),jm(e)},Ib=(e,t,n)=>{let o=tc(t),r=bb(o),s=e.toolCall.id,a=fa(n),i=Math.max(1,a.length),d=i>1,l=Mb(e,a),u=d?Lb(e,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(bs,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(Zl,String(i)),g.setAttribute(Jl,String(u)),g.setAttribute(ec,d?"true":"false"),g.setAttribute(_m,r),zm(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`),wb(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 M=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 M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),g.appendChild(M),r!=="rows"&&g.appendChild(Um(o,r)),nc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Rb=(e,t,n)=>{let{payload:o}=ys(t),r=Math.max(1,fa(o).length);r>vs(e)&&(e.setAttribute(Zl,String(r)),r>1&&!br(e)&&e.setAttribute(ec,"true")),nc(e,t,n)};var Mi=(e,t,n)=>{if(!n||!Vr(e)||tc(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${bs}]`).forEach(l=>{l.getAttribute(bs)!==r&&l.remove()});let a=n.querySelector(`[${bs}="${Vm(r)}"]`);if(a){Rb(a,e,t);return}let{payload:i}=ys(e),d=Ib(e,t,i);n.appendChild(d)},xs=(e,t)=>{if(!e)return;let n=t?`[${bs}="${Vm(t)}"]`:`[${bs}]`;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)})},oc=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),yr=(e,t)=>{let n=$r(e),o=fo(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,zm(e,n),qm(e),jm(e)},Li=(e,t,n,o)=>{let r=vs(e),s=Math.max(0,Math.min(r-1,o));Eb(e,s),nc(e,t,n)};var Xo="suggest_replies";var Pb={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},Km={name:Xo,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:Pb,origin:"sdk",annotations:{readOnlyHint:!0}},rc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),sc=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Xo},Wb=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},Gm=e=>{var t;for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return null;if(!sc(o))continue;let r=Wb((t=o.toolCall)==null?void 0:t.args);return r.length>0?r:null}return null},Ym=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 Bb={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ga,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},Hb={name:Xl,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:Bb,origin:"sdk",annotations:{readOnlyHint:!0}},ac=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(Hb),Ym(e)&&t.push(Km),t};var ws=require("partial-json"),Qm=e=>e.replace(/\\n/g,`
|
|
7
7
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Cs=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)}},Db=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`},Xm=e=>e.status==="complete"?Db(e):e.status==="pending"?"Waiting":"",Ob=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 Jm=e=>e.status==="complete"?Ob(e):"Using tool...",Ii=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ba=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 Ii(t)},Ri=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 Ii(t)},ic=(e,t,n)=>{var s;if(!t)return n;let o=((s=e.name)==null?void 0:s.trim())||"tool",r=ba(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Pi=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&ha(o,n.slice(s,a.index),[]),a[1]!==void 0?ha(o,a[1],["bold"]):a[2]!==void 0?ha(o,a[2],["italic"]):a[3]!==void 0&&ha(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ha(o,n.slice(s),[]),o},ha=(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})},Fb=()=>{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()=>{}}},Ur=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},eg=()=>{var t;let e=Fb();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)}},tg=()=>{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=(0,ws.parse)(n,ws.STR|ws.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var ng=()=>{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 Wi=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 Nb="https://api.runtype.com/v1/dispatch",Bi="https://api.runtype.com";function _b(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 lc=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 Vb(e){switch(e){case"json":return tg;case"regex-json":return eg;case"xml":return ng;default:return Zm}}var og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function $b(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=og(n);if(!og(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ur(e);return Ur(t)!==null&&a===null?t:e}var ya=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:Nb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Vb(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 ki(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$/,""))||Bi}/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$/,""))||Bi}/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 D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(lc).map(D=>{var P,w,C;return{id:D.id,role:D.role,content:(C=(w=(P=D.contentParts)!=null?P:D.llmContent)!=null?w:D.rawContent)!=null?C:D.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?Bm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===x,I=!1,R=null,B;for(let D=0;;D++){let w={...g,...m&&(I||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),B=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),B.status===409&&D===0&&m){let C=await B.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=C!=null?C:{error:"Chat request failed"}}break}if(!B.ok){let D=R!=null?R:await B.json().catch(()=>({error:"Chat request failed"}));if(B.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(B.status===429){let w=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let P=new Error(D.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!B.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(B.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$/,""))||Bi}/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(/\/+$/,""))||Bi}/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(lc).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=[...ac(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(lc).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=[...ac(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 Ht,ln,so,Lo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let ue=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Oe=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Ge=O.tools?O.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...O,reasoning:ue,toolCall:Oe,tools:Ge}},g=O=>{if(O.role!=="assistant"||O.variant)return!0;let ue=Array.isArray(O.contentParts)&&O.contentParts.length>0,Oe=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||ue||Oe||!!O.stopReason},f=O=>{g(O)&&n({type:"message",message:u(O)})},m=null,x=null,v={current:null},M={current:null},I=!1,R=new Map,B=new Map,D=new Map,P=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},E=(O,ue,Oe="")=>`${O}::${ue}::${Oe}`,A=(O,ue)=>`${O}::${ue}::`,S=(O,ue,Oe,Ge)=>{let _e=E(O,ue,Oe),$e=D.get(_e);if($e)return $e;let rt=Oe?`-${Oe}`:"",Rt={id:`nested-${O}-${ue}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Ge,parentToolId:O,parentStepId:ue}};return D.set(_e,Rt),f(Rt),Rt},V=O=>{if(O==null)return null;try{return String(O)}catch{return null}},$=O=>{var ue,Oe,Ge,_e,$e;return V(($e=(_e=(Ge=(Oe=(ue=O.stepId)!=null?ue:O.step_id)!=null?Oe:O.step)!=null?Ge:O.parentId)!=null?_e:O.flowStepId)!=null?$e:O.flow_step_id)},G=O=>{var ue,Oe,Ge,_e,$e,rt,Rt;return V((Rt=(rt=($e=(_e=(Ge=(Oe=(ue=O.callId)!=null?ue:O.call_id)!=null?Oe:O.requestId)!=null?Ge:O.request_id)!=null?_e:O.toolCallId)!=null?$e:O.tool_call_id)!=null?rt:O.stepId)!=null?Rt:O.step_id)},he=o,me=!1,de=()=>{if(m)return m;let O;return!me&&he?(O=he,me=!0):he&&M.current?O=`${he}_${M.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Ee=(O,ue)=>{w.lastId=ue,O&&w.byStep.set(O,ue)},xe=(O,ue)=>{var $e;let Oe=($e=O.reasoningId)!=null?$e:O.id,Ge=$(O);if(Oe){let rt=String(Oe);return Ee(Ge,rt),rt}if(Ge){let rt=w.byStep.get(Ge);if(rt)return w.lastId=rt,rt}if(w.lastId&&!ue)return w.lastId;if(!ue)return null;let _e=`reason-${l()}`;return Ee(Ge,_e),_e},De=O=>{let ue=R.get(O);if(ue)return ue;let Oe={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return R.set(O,Oe),f(Oe),Oe},Ae=(O,ue)=>{C.lastId=ue,O&&C.byCall.set(O,ue)},le=new Set,X=new Map,se=new Set,ye=new Map,be=O=>{if(!O)return!1;let ue=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},K=(O,ue)=>{var $e;let Oe=($e=O.toolId)!=null?$e:O.id,Ge=G(O);if(Oe){let rt=String(Oe);return Ae(Ge,rt),rt}if(Ge){let rt=C.byCall.get(Ge);if(rt)return C.lastId=rt,rt}if(C.lastId&&!ue)return C.lastId;if(!ue)return null;let _e=`tool-${l()}`;return Ae(Ge,_e),_e},ae=O=>{let ue=B.get(O);if(ue)return ue;let Oe={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return B.set(O,Oe),f(Oe),Oe},Pe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let ue=Number(O);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Oe=Date.parse(O);if(!Number.isNaN(Oe))return Oe}return Date.now()},oe=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ee=new Map,re=new Map,it=new Map,lt=new Map,Ie=null,pe=(O,ue,Oe)=>{var Rt;let Ge=it.get(O);Ge||(Ge=[],it.set(O,Ge));let _e=0,$e=Ge.length;for(;_e<$e;){let jt=_e+$e>>>1;Ge[jt].seq<ue?_e=jt+1:$e=jt}((Rt=Ge[_e])==null?void 0:Rt.seq)===ue?Ge[_e]={seq:ue,text:Oe}:Ge.splice(_e,0,{seq:ue,text:Oe});let rt="";for(let jt=0;jt<Ge.length;jt++)rt+=Ge[jt].text;return rt},Xe=(O,ue)=>{let Oe=oe(ue),Ge=re.get(O.id),_e=$b(Ge,Oe);O.rawContent=_e;let $e=ee.get(O.id),rt=vt=>{var Se;let at=(Se=O.content)!=null?Se:"";vt.trim()!==""&&(at.trim().length===0||vt.startsWith(at)||vt.trimStart().startsWith(at.trim()))&&(O.content=vt)},Rt=()=>{var vt;if($e){let at=(vt=$e.close)==null?void 0:vt.call($e);at instanceof Promise&&at.catch(()=>{})}ee.delete(O.id),re.delete(O.id),O.streaming=!1,f(O)};if(!$e){rt(Oe),Rt();return}let jt=Ur(_e);if(jt!==null&&jt.trim()!==""){rt(jt),Rt();return}let Jt=vt=>{var ce;let at=typeof vt=="string"?vt:(ce=vt==null?void 0:vt.text)!=null?ce:null;if(at!==null&&at.trim()!=="")return at;let Se=$e.getExtractedText();return Se!==null&&Se.trim()!==""?Se:Oe},Y;try{Y=$e.processChunk(_e)}catch{rt(Oe),Rt();return}if(Y instanceof Promise){Y.then(vt=>{rt(Jt(vt)),Rt()}).catch(()=>{rt(Oe),Rt()});return}rt(Jt(Y)),Rt()},Be=[],j=!1,ge,nt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,ge()}))},kt=new Wi((O,ue)=>{Be.push({payloadType:O,payload:ue}),nt()}),ne=null,qe=new Map,_n=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ge=()=>{var O,ue,Oe,Ge,_e,$e,rt,Rt,jt,Jt,Y,vt,at,Se,ce,et,en,Kt,Pn,wn,mt,Et,Je,zt,cn,An,Tn,yn,Io,St,qn,jn,Vo,bo,xt,Sr,Ro,Ar,Vn,Jr,er,$o,At,Kn,Gn,Wn,It,ao,io,Yn,tr,Uo,nr,Qn,Dt,Bn,lo,or,zo,rr,Po,Xn,yo,ft,tn,nn,Jn,sr,we,vo,co,U,Zr,Wo,qo,jo,Bo,xo,Ps,Zn,eo,wo,Co,Tr,Ko,kn,Ho,es,kr,ts,Ga,ns,Ya,os,yt,Ws,po,$n,Qa,Xa,rs,Go,Bs,ar,Hs,Ds,Os,Fs,Un,ss,Do,Oo,Ns,Ja,_s,Vs,Er,Za,ei,ti,ni,Tl,Mr,ir,oi,$s,lr,ri,Us,cr,zs,si,Yo,ai,dr,Ot,as,is;for(let Lr=0;Lr<Be.length;Lr++){let Ue=Be[Lr].payloadType,k=Be[Lr].payload;if(Ue==="reason_start"){let z=(O=xe(k,!0))!=null?O:`reason-${l()}`,W=De(z);W.reasoning=(ue=W.reasoning)!=null?ue:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(Ge=W.reasoning.startedAt)!=null?Ge:Pe((Oe=k.startedAt)!=null?Oe:k.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let z=($e=(_e=xe(k,!1))!=null?_e:xe(k,!0))!=null?$e:`reason-${l()}`,W=De(z);W.reasoning=(rt=W.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(jt=W.reasoning.startedAt)!=null?jt:Pe((Rt=k.startedAt)!=null?Rt:k.timestamp);let Z=(vt=(Y=(Jt=k.reasoningText)!=null?Jt:k.text)!=null?Y:k.delta)!=null?vt:"";if(Z&&k.hidden!==!0){let ie=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(ie!==void 0){let Q=pe(z,ie,String(Z));W.reasoning.chunks=[Q]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=k.done?"complete":"streaming",k.done){W.reasoning.completedAt=Pe((at=k.completedAt)!=null?at:k.timestamp);let ie=(Se=W.reasoning.startedAt)!=null?Se:Date.now();W.reasoning.durationMs=Math.max(0,((ce=W.reasoning.completedAt)!=null?ce:Date.now())-ie)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(Ue==="reason_complete"){let z=(en=(et=xe(k,!1))!=null?et:xe(k,!0))!=null?en:`reason-${l()}`,W=R.get(z);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Pe((Kt=k.completedAt)!=null?Kt:k.timestamp);let ie=(Pn=W.reasoning.startedAt)!=null?Pn:Date.now();W.reasoning.durationMs=Math.max(0,((wn=W.reasoning.completedAt)!=null?wn:Date.now())-ie),W.streaming=!1,f(W)}let Z=$(k);Z&&w.byStep.delete(Z)}else if(Ue==="tool_start"){let z=(mt=K(k,!0))!=null?mt:`tool-${l()}`,W=(Et=k.toolName)!=null?Et:k.name;if(be(W)){le.add(z);continue}let Z=ae(z),ie=(Je=Z.toolCall)!=null?Je:{id:z,status:"pending"};ie.name=W!=null?W:ie.name,ie.status="running",k.args!==void 0?ie.args=k.args:k.parameters!==void 0&&(ie.args=k.parameters),ie.startedAt=(cn=ie.startedAt)!=null?cn:Pe((zt=k.startedAt)!=null?zt:k.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(Z.agentMetadata={executionId:(An=Q==null?void 0:Q.executionId)!=null?An:k.executionId,iteration:(Tn=Q==null?void 0:Q.iteration)!=null?Tn:k.iteration}),f(Z)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let z=(Io=(yn=K(k,!1))!=null?yn:K(k,!0))!=null?Io:`tool-${l()}`;if(le.has(z))continue;let W=ae(z),Z=(St=W.toolCall)!=null?St:{id:z,status:"running"};Z.startedAt=(jn=Z.startedAt)!=null?jn:Pe((qn=k.startedAt)!=null?qn:k.timestamp);let ie=(xt=(bo=(Vo=k.text)!=null?Vo:k.delta)!=null?bo:k.message)!=null?xt:"";ie&&(Z.chunks=(Sr=Z.chunks)!=null?Sr:[],Z.chunks.push(String(ie))),Z.status="running",W.toolCall=Z,W.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(Vn=W.agentMetadata)!=null?Vn:{executionId:(Ro=Q==null?void 0:Q.executionId)!=null?Ro:k.executionId,iteration:(Ar=Q==null?void 0:Q.iteration)!=null?Ar:k.iteration}),f(W)}else if(Ue==="tool_complete"){let z=(er=(Jr=K(k,!1))!=null?Jr:K(k,!0))!=null?er:`tool-${l()}`;if(le.has(z)){le.delete(z);continue}let W=ae(z),Z=($o=W.toolCall)!=null?$o:{id:z,status:"running"};Z.status="complete",k.result!==void 0&&(Z.result=k.result),typeof k.duration=="number"&&(Z.duration=k.duration),Z.completedAt=Pe((At=k.completedAt)!=null?At:k.timestamp);let ie=(Kn=k.duration)!=null?Kn:k.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Ne=(Gn=Z.startedAt)!=null?Gn:Date.now();Z.durationMs=Math.max(0,((Wn=Z.completedAt)!=null?Wn:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(io=W.agentMetadata)!=null?io:{executionId:(It=Q==null?void 0:Q.executionId)!=null?It:k.executionId,iteration:(ao=Q==null?void 0:Q.iteration)!=null?ao:k.iteration}),f(W);let Le=G(k);Le&&C.byCall.delete(Le)}else if(Ue==="step_await"&&k.awaitReason==="local_tool_required"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,W=(Yn=z!=null?z:k.toolId)!=null?Yn:`local-${l()}`,Z=ae(W),ie=k.toolName,Q=ma(ie),Le=(tr=Z.toolCall)!=null?tr:{id:W,status:"pending"};Le.name=ie,Le.args=k.parameters,Le.status=Q?"running":"complete",Le.chunks=(Uo=Le.chunks)!=null?Uo:[],Le.startedAt=(Qn=Le.startedAt)!=null?Qn:Pe((nr=k.startedAt)!=null?nr:k.timestamp),Q?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=(Dt=Le.completedAt)!=null?Dt:Le.startedAt,Z.toolCall=Le,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lo=k.executionId)!=null?lo:(Bn=Z.agentMetadata)==null?void 0:Bn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(Z)}else if(Ue==="text_start"){if((or=k.toolContext)!=null&&or.toolId)continue;let z=k.partId;if(z!==void 0&&M.current!==null&&z!==M.current){let W=m;W&&(W.streaming=!1,f(W),Ie=W,m=null,I=!0)}z!==void 0&&(M.current=z)}else if(Ue==="text_end"){if((zo=k.toolContext)!=null&&zo.toolId)continue;let z=m;z&&(z.streaming=!1,f(z),Ie=z,m=null,I=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Po=(rr=k.id)!=null?rr:Z.stepId)!=null?Po:`step-${l()}`),ct=k.partId!==void 0&&k.partId!==null?String(k.partId):"",Ze=`${Z.toolId}::${Ne}`,Bt=P.get(Ze);if(ct!==""&&Bt!==void 0&&Bt!==""&&Bt!==ct){let st=D.get(E(Z.toolId,Ne,Bt));st&&st.streaming!==!1&&(st.streaming=!1,f(st))}ct!==""&&P.set(Ze,ct);let Vt=S(Z.toolId,Ne,ct,Z.executionId),mn=(tn=(ft=(yo=(Xn=k.text)!=null?Xn:k.delta)!=null?yo:k.content)!=null?ft:k.chunk)!=null?tn:"";mn&&(Vt.content+=String(mn),Vt.streaming=!0,f(Vt)),k.isComplete&&(Vt.streaming=!1,f(Vt));continue}let ie=k.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let Ne=m;Ne&&(Ne.streaming=!1,f(Ne),Ie=Ne,m=null,I=!0)}ie!==void 0&&(M.current=ie);let Q=ie!==void 0&&(nn=lt.get(ie))!=null?nn:de();ie!==void 0&&(Q.partId||(Q.partId=ie),lt.set(ie,Q));let Le=(vo=(we=(sr=(Jn=k.text)!=null?Jn:k.delta)!=null?sr:k.content)!=null?we:k.chunk)!=null?vo:"";if(Le){let Ne=typeof k.seq=="number"?k.seq:void 0,ct=ie!=null?ie:Q.id,Ze=Ne!==void 0?pe(ct,Ne,String(Le)):((co=re.get(Q.id))!=null?co:"")+Le;Q.rawContent=Ze,ee.has(Q.id)||ee.set(Q.id,this.createStreamParser());let Bt=ee.get(Q.id),Vt=Ze.trim().startsWith("{")||Ze.trim().startsWith("[");if(Vt&&re.set(Q.id,Ze),Bt.__isPlainTextParser===!0){Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q);continue}let st=Bt.processChunk(Ze);if(st instanceof Promise)st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")Q.content=Zt,f(Q);else if(!Vt&&!Ze.trim().startsWith("<")){let Cn=m,Yt=Cn&&Cn.id===Q.id?Cn:Q;Yt.id===Q.id&&(Yt.content=Ne!==void 0?Ze:Yt.content+Le,re.delete(Yt.id),ee.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q)});else{let ht=typeof st=="string"?st:(U=st==null?void 0:st.text)!=null?U:null;ht!==null&&ht.trim()!==""?(Q.content=ht,f(Q)):!Vt&&!Ze.trim().startsWith("<")&&(Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q))}}if(k.isComplete){let Ne=(Wo=(Zr=k.result)==null?void 0:Zr.response)!=null?Wo:Q.content;if(Ne){let ct=re.get(Q.id),Ze=ct!=null?ct:oe(Ne);Q.rawContent=Ze;let Bt=ee.get(Q.id),Vt=null,mn=!1;if(Bt&&(Vt=Bt.getExtractedText(),Vt===null&&(Vt=Ur(Ze)),Vt===null)){let st=Bt.processChunk(Ze);st instanceof Promise?(mn=!0,st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null){let Cn=m;Cn&&Cn.id===Q.id&&(Cn.content=Zt,Cn.streaming=!1,ee.delete(Cn.id),re.delete(Cn.id),f(Cn))}})):Vt=typeof st=="string"?st:(qo=st==null?void 0:st.text)!=null?qo:null}if(!mn){Vt!==null&&Vt.trim()!==""?Q.content=Vt:re.has(Q.id)||(Q.content=oe(Ne));let st=ee.get(Q.id);if(st){let ht=(jo=st.close)==null?void 0:jo.call(st);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(Q.id)}re.delete(Q.id),Q.streaming=!1,f(Q)}}}}else if(Ue==="step_complete"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((xo=(Bo=k.id)!=null?Bo:Z.stepId)!=null?xo:"");if(Ne){let ct=A(Z.toolId,Ne);for(let[Ze,Bt]of D)Ze.startsWith(ct)&&Bt.streaming!==!1&&(Bt.streaming=!1,f(Bt));P.delete(`${Z.toolId}::${Ne}`)}continue}let ie=k.stopReason;if(I){if(m!==null){let Ze=m;ie&&(Ze.stopReason=ie),ee.delete(Ze.id),re.delete(Ze.id),Ze.streaming!==!1&&(Ze.streaming=!1,f(Ze))}let Ne=(Ps=k.result)==null?void 0:Ps.response,ct=Ie;ct&&(ie&&(ct.stopReason=ie),Ne!=null?Xe(ct,Ne):(ee.delete(ct.id),re.delete(ct.id))),Ie=null;continue}let Q=(Zn=k.result)==null?void 0:Zn.response,Le=de();if(ie&&(Le.stopReason=ie),Q!=null){let Ne=ee.get(Le.id),ct=!1,Ze=!1;if(Ne){let Bt=Ne.getExtractedText(),Vt=re.get(Le.id),mn=Vt!=null?Vt:oe(Q);if(Le.rawContent=mn,Bt!==null&&Bt.trim()!=="")Le.content=Bt,ct=!0;else{let st=Ur(mn);if(st!==null)Le.content=st,ct=!0;else{let ht=Ne.processChunk(mn);if(ht instanceof Promise)Ze=!0,ht.then(Zt=>{var Cn;let Ke=typeof Zt=="string"?Zt:(Cn=Zt==null?void 0:Zt.text)!=null?Cn:null;if(Ke!==null&&Ke.trim()!==""){let Yt=m;Yt&&Yt.id===Le.id&&(Yt.content=Ke,Yt.streaming=!1,ee.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),vn=m;vn&&vn.id===Le.id&&(Yt!==null&&Yt.trim()!==""?vn.content=Yt:re.has(vn.id)||(vn.content=oe(Q)),vn.streaming=!1,ee.delete(vn.id),re.delete(vn.id),f(vn))}});else{let Zt=typeof ht=="string"?ht:(eo=ht==null?void 0:ht.text)!=null?eo:null;if(Zt!==null&&Zt.trim()!=="")Le.content=Zt,ct=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Le.content=Ke,ct=!0)}}}}}if(!Ze){if(!Le.rawContent){let Bt=re.get(Le.id);Le.rawContent=Bt!=null?Bt:oe(Q)}if(!ct&&!re.has(Le.id)&&(Le.content=oe(Q)),Ne){let Bt=(wo=Ne.close)==null?void 0:wo.call(Ne);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}}else ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}else if(Ue==="flow_complete"){let z=(Co=k.result)==null?void 0:Co.response;if(I){if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(z!=null){let W=de(),Z=re.get(W.id),ie=Z!=null?Z:oe(z);W.rawContent=ie;let Q=oe(z),Le=ee.get(W.id);if(Le){let Ze=Ur(ie);if(Ze!==null)Q=Ze;else{let Bt=Le.processChunk(ie);Bt instanceof Promise&&Bt.then(mn=>{var ht;let st=typeof mn=="string"?mn:(ht=mn==null?void 0:mn.text)!=null?ht:null;st!==null&&(W.content=st,W.streaming=!1,f(W))});let Vt=Le.getExtractedText();Vt!==null&&(Q=Vt)}}ee.delete(W.id),re.delete(W.id);let Ne=Q!==W.content,ct=W.streaming!==!1;Ne&&(W.content=Q),W.streaming=!1,(Ne||ct)&&f(W)}else if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")ne={executionId:k.executionId,agentId:(Tr=k.agentId)!=null?Tr:"virtual",agentName:(Ko=k.agentName)!=null?Ko:"",status:"running",currentIteration:0,maxTurns:(kn=k.maxTurns)!=null?kn:1,startedAt:Pe(k.startedAt)};else if(Ue==="agent_iteration_start"){if(ne&&(ne.currentIteration=k.iteration),_n==="separate"&&k.iteration>1){let z=m;z&&(z.streaming=!1,f(z),qe.set(k.iteration-1,z),m=null)}}else if(Ue==="agent_turn_start")x=null;else if(Ue==="agent_turn_delta"){if(k.contentType==="text"){let z=de();z.content+=(Ho=k.delta)!=null?Ho:"",z.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId,agentName:ne==null?void 0:ne.agentName},x=z,f(z)}else if(k.contentType==="thinking"){let z=(es=k.turnId)!=null?es:`agent-think-${k.iteration}`,W=De(z);W.reasoning=(kr=W.reasoning)!=null?kr:{id:z,status:"streaming",chunks:[]},W.reasoning.chunks.push((ts=k.delta)!=null?ts:""),W.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId},f(W)}else if(k.contentType==="tool_input"){let z=(Ga=k.toolCallId)!=null?Ga:C.lastId;if(z){let W=B.get(z);W!=null&&W.toolCall&&(W.toolCall.chunks=(ns=W.toolCall.chunks)!=null?ns:[],W.toolCall.chunks.push((Ya=k.delta)!=null?Ya:""),f(W))}}}else if(Ue==="agent_turn_complete"){let z=k.turnId;if(z){let ie=R.get(z);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Pe(k.completedAt);let Q=(os=ie.reasoning.startedAt)!=null?os:Date.now();ie.reasoning.durationMs=Math.max(0,((yt=ie.reasoning.completedAt)!=null?yt:Date.now())-Q),ie.streaming=!1,f(ie)}}let W=k.stopReason,Z=m!=null?m:x;if(W&&Z!==null){let ie=k.turnId;(!ie||((Ws=Z.agentMetadata)==null?void 0:Ws.turnId)===ie)&&(Z.stopReason=W,f(Z))}}else if(Ue==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let z=(po=k.toolCallId)!=null?po:`agent-tool-${l()}`;Ae(G(k),z);let W=ae(z),Z=($n=W.toolCall)!=null?$n:{id:z,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};Z.name=(Xa=(Qa=k.toolName)!=null?Qa:k.name)!=null?Xa:Z.name,Z.status="running",k.parameters!==void 0&&(Z.args=k.parameters),Z.startedAt=Pe((rs=k.startedAt)!=null?rs:k.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:k.executionId,iteration:k.iteration},f(W)}else if(Ue==="agent_tool_delta"){let z=(Go=k.toolCallId)!=null?Go:C.lastId;if(z){let W=(Bs=B.get(z))!=null?Bs:ae(z);W.toolCall&&(W.toolCall.chunks=(ar=W.toolCall.chunks)!=null?ar:[],W.toolCall.chunks.push((Hs=k.delta)!=null?Hs:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(Ue==="agent_tool_complete"){let z=(Ds=k.toolCallId)!=null?Ds:C.lastId;if(z){let W=(Os=B.get(z))!=null?Os:ae(z);if(W.toolCall){W.toolCall.status="complete",k.result!==void 0&&(W.toolCall.result=k.result),typeof k.executionTime=="number"&&(W.toolCall.durationMs=k.executionTime),W.toolCall.completedAt=Pe((Fs=k.completedAt)!=null?Fs:k.timestamp),W.streaming=!1,f(W);let Z=G(k);Z&&C.byCall.delete(Z)}}}else if(Ue==="agent_media"){let z=Array.isArray(k.media)?k.media:[],W=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let ie=Z,Q=typeof ie.type=="string"?ie.type:void 0,Le=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Ne=null,ct="";if(Q==="media"){let Ze=typeof ie.data=="string"?ie.data:void 0;if(!Ze)continue;ct=Le.length>0?Le:"application/octet-stream",Ne=`data:${ct};base64,${Ze}`}else if(Q==="image-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else if(Q==="file-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else continue;if(Ne)if(Q==="image-url"||ct.startsWith("image/"))W.push({type:"image",image:Ne,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:ct});else if(ct.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:ct});else{let Ze=ct||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ze,filename:_b(Ze)})}}if(W.length>0){let Z=l(),ie=k.toolCallId,Le={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(Le);let Ne=m;Ne&&(Ne.streaming=!1,f(Ne)),m=null,v.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let z=`agent-reflection-${k.executionId}-${k.iteration}`,W={id:z,role:"assistant",content:(Un=k.reflection)!=null?Un:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(ss=k.reflection)!=null?ss:""]},agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(W)}else if(Ue==="agent_complete"){ne&&(ne.status=k.success?"complete":"error",ne.completedAt=Pe(k.completedAt),ne.stopReason=k.stopReason);let z=m;z&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let z=typeof k.error=="string"?k.error:(Oo=(Do=k.error)==null?void 0:Do.message)!=null?Oo:"Agent execution error";k.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let z=(Ns=k.approvalId)!=null?Ns:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ja=ne==null?void 0:ne.agentId)!=null?Ja:"virtual",executionId:(Vs=(_s=k.executionId)!=null?_s:ne==null?void 0:ne.executionId)!=null?Vs:"",toolName:(Er=k.toolName)!=null?Er:"",toolType:k.toolType,description:(ei=k.description)!=null?ei:`Execute ${(Za=k.toolName)!=null?Za:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="step_await"&&k.awaitReason==="approval_required"){let z=(ti=k.approvalId)!=null?ti:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(ni=ne==null?void 0:ne.agentId)!=null?ni:"virtual",executionId:(Mr=(Tl=k.executionId)!=null?Tl:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(ir=k.toolName)!=null?ir:"",toolType:k.toolType,description:($s=k.description)!=null?$s:`Execute ${(oi=k.toolName)!=null?oi:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="agent_approval_complete"){let z=k.approvalId;if(z){let Z={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(lr=k.decision)!=null?lr:"approved",agentId:(ri=ne==null?void 0:ne.agentId)!=null?ri:"virtual",executionId:(cr=(Us=k.executionId)!=null?Us:ne==null?void 0:ne.executionId)!=null?cr:"",toolName:(zs=k.toolName)!=null?zs:"",description:(si=k.description)!=null?si:"",resolvedAt:Date.now()}};f(Z)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let z=k.artifactType,W=String(k.id),Z=typeof k.title=="string"?k.title:void 0;if(n({type:"artifact_start",id:W,artifactType:z,title:Z,component:typeof k.component=="string"?k.component:void 0}),ye.set(W,{markdown:"",title:Z}),!se.has(W)){se.add(W);let ie={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:z,status:"streaming"}})};X.set(W,ie),f(ie)}}else if(Ue==="artifact_delta"){let z=String(k.id),W=typeof k.delta=="string"?k.delta:String((Yo=k.delta)!=null?Yo:"");n({type:"artifact_delta",id:z,artDelta:W});let Z=ye.get(z);Z&&(Z.markdown+=W)}else if(Ue==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};n({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(Ue==="artifact_complete"){let z=String(k.id);n({type:"artifact_complete",id:z});let W=X.get(z);if(W){W.streaming=!1;try{let Z=JSON.parse((ai=W.rawContent)!=null?ai:"{}");if(Z.props){Z.props.status="complete";let ie=ye.get(z);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}W.rawContent=JSON.stringify(Z)}catch{}ye.delete(z),f(W),X.delete(z)}}}else if(Ue==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let W=String((dr=z.id)!=null?dr:`msg-${l()}`),Z=z.role,Q={id:W,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(f(Q),Q.rawContent)try{let Le=JSON.parse(Q.rawContent),Ne=(Ot=Le==null?void 0:Le.props)==null?void 0:Ot.artifactId;typeof Ne=="string"&&se.add(Ne)}catch{}m=null,v.current=null,ee.delete(W),re.delete(W)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ue==="dispatch_error"){let W=(as=k.message)!=null?as:k.error;W!=null&&W!==""&&(z=new Error(String(W)))}else if(Ue==="step_error"||Ue==="flow_error"){let W=k.error;typeof W=="string"&&W!==""?z=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(z=new Error(String((is=W.message)!=null?is:W)))}else Ue==="error"&&k.error!=null&&k.error!==""&&(z=new Error(String(k.error)));if(z){n({type:"error",error:z});let W=m;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:O,value:ue}=await r.read();if(O)break;a+=s.decode(ue,{stream:!0});let Oe=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()=>{}}},Ur=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zm=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},eg=()=>{var t;let e=Fb();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)}},tg=()=>{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=(0,ws.parse)(n,ws.STR|ws.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Qm(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Qm(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var ng=()=>{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 Wi=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 Nb="https://api.runtype.com/v1/dispatch",Bi="https://api.runtype.com";function _b(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 lc=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 Vb(e){switch(e){case"json":return tg;case"regex-json":return eg;case"xml":return ng;default:return Zm}}var og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function $b(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=og(n);if(!og(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ur(e);return Ur(t)!==null&&a===null?t:e}var ya=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:Nb,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:Vb(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 ki(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$/,""))||Bi}/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$/,""))||Bi}/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 D=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:D}),D}let l=await this.buildPayload(t.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([D])=>D!=="sessionId"&&D!=="session_id")):void 0,g={sessionId:d.sessionId,messages:t.messages.filter(lc).map(D=>{var P,w,C;return{id:D.id,role:D.role,content:(C=(w=(P=D.contentParts)!=null?P:D.llmContent)!=null?w:D.rawContent)!=null?C:D.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?Bm(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===x,I=!1,R=null,B;for(let D=0;;D++){let w={...g,...m&&(I||!M)&&f?{clientTools:f}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",w),B=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w),signal:o.signal}),B.status===409&&D===0&&m){let C=await B.json().catch(()=>null);if((C==null?void 0:C.error)==="client_tools_resend_required"){I=!0,this.lastSentClientToolsFingerprint=null;continue}R=C!=null?C:{error:"Chat request failed"}}break}if(!B.ok){let D=R!=null?R:await B.json().catch(()=>({error:"Chat request failed"}));if(B.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(B.status===429){let w=new Error(D.hint||"Message limit reached for this session.");throw n({type:"error",error:w}),w}let P=new Error(D.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!B.body){let D=new Error("No response body received");throw n({type:"error",error:D}),D}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(B.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$/,""))||Bi}/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(/\/+$/,""))||Bi}/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(lc).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=[...ac(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(lc).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=[...ac(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 Ht,ln,so,Lo;let r=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let ue=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Oe=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Ge=O.tools?O.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...O,reasoning:ue,toolCall:Oe,tools:Ge}},g=O=>{if(O.role!=="assistant"||O.variant)return!0;let ue=Array.isArray(O.contentParts)&&O.contentParts.length>0,Oe=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||ue||Oe||!!O.stopReason},f=O=>{g(O)&&n({type:"message",message:u(O)})},m=null,x=null,v={current:null},M={current:null},I=!1,R=new Map,B=new Map,D=new Map,P=new Map,w={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},E=(O,ue,Oe="")=>`${O}::${ue}::${Oe}`,A=(O,ue)=>`${O}::${ue}::`,S=(O,ue,Oe,Ge)=>{let _e=E(O,ue,Oe),$e=D.get(_e);if($e)return $e;let rt=Oe?`-${Oe}`:"",Rt={id:`nested-${O}-${ue}${rt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Ge,parentToolId:O,parentStepId:ue}};return D.set(_e,Rt),f(Rt),Rt},V=O=>{if(O==null)return null;try{return String(O)}catch{return null}},$=O=>{var ue,Oe,Ge,_e,$e;return V(($e=(_e=(Ge=(Oe=(ue=O.stepId)!=null?ue:O.step_id)!=null?Oe:O.step)!=null?Ge:O.parentId)!=null?_e:O.flowStepId)!=null?$e:O.flow_step_id)},G=O=>{var ue,Oe,Ge,_e,$e,rt,Rt;return V((Rt=(rt=($e=(_e=(Ge=(Oe=(ue=O.callId)!=null?ue:O.call_id)!=null?Oe:O.requestId)!=null?Ge:O.request_id)!=null?_e:O.toolCallId)!=null?$e:O.tool_call_id)!=null?rt:O.stepId)!=null?Rt:O.step_id)},he=o,me=!1,de=()=>{if(m)return m;let O;return!me&&he?(O=he,me=!0):he&&M.current?O=`${he}_${M.current}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:O,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(m),m},Ee=(O,ue)=>{w.lastId=ue,O&&w.byStep.set(O,ue)},xe=(O,ue)=>{var $e;let Oe=($e=O.reasoningId)!=null?$e:O.id,Ge=$(O);if(Oe){let rt=String(Oe);return Ee(Ge,rt),rt}if(Ge){let rt=w.byStep.get(Ge);if(rt)return w.lastId=rt,rt}if(w.lastId&&!ue)return w.lastId;if(!ue)return null;let _e=`reason-${l()}`;return Ee(Ge,_e),_e},De=O=>{let ue=R.get(O);if(ue)return ue;let Oe={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return R.set(O,Oe),f(Oe),Oe},Ae=(O,ue)=>{C.lastId=ue,O&&C.byCall.set(O,ue)},le=new Set,X=new Map,se=new Set,ye=new Map,be=O=>{if(!O)return!1;let ue=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},K=(O,ue)=>{var $e;let Oe=($e=O.toolId)!=null?$e:O.id,Ge=G(O);if(Oe){let rt=String(Oe);return Ae(Ge,rt),rt}if(Ge){let rt=C.byCall.get(Ge);if(rt)return C.lastId=rt,rt}if(C.lastId&&!ue)return C.lastId;if(!ue)return null;let _e=`tool-${l()}`;return Ae(Ge,_e),_e},ae=O=>{let ue=B.get(O);if(ue)return ue;let Oe={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return B.set(O,Oe),f(Oe),Oe},Pe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let ue=Number(O);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Oe=Date.parse(O);if(!Number.isNaN(Oe))return Oe}return Date.now()},oe=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ee=new Map,re=new Map,it=new Map,lt=new Map,Ie=null,pe=(O,ue,Oe)=>{var Rt;let Ge=it.get(O);Ge||(Ge=[],it.set(O,Ge));let _e=0,$e=Ge.length;for(;_e<$e;){let jt=_e+$e>>>1;Ge[jt].seq<ue?_e=jt+1:$e=jt}((Rt=Ge[_e])==null?void 0:Rt.seq)===ue?Ge[_e]={seq:ue,text:Oe}:Ge.splice(_e,0,{seq:ue,text:Oe});let rt="";for(let jt=0;jt<Ge.length;jt++)rt+=Ge[jt].text;return rt},Xe=(O,ue)=>{let Oe=oe(ue),Ge=re.get(O.id),_e=$b(Ge,Oe);O.rawContent=_e;let $e=ee.get(O.id),rt=vt=>{var Se;let at=(Se=O.content)!=null?Se:"";vt.trim()!==""&&(at.trim().length===0||vt.startsWith(at)||vt.trimStart().startsWith(at.trim()))&&(O.content=vt)},Rt=()=>{var vt;if($e){let at=(vt=$e.close)==null?void 0:vt.call($e);at instanceof Promise&&at.catch(()=>{})}ee.delete(O.id),re.delete(O.id),O.streaming=!1,f(O)};if(!$e){rt(Oe),Rt();return}let jt=Ur(_e);if(jt!==null&&jt.trim()!==""){rt(jt),Rt();return}let Jt=vt=>{var ce;let at=typeof vt=="string"?vt:(ce=vt==null?void 0:vt.text)!=null?ce:null;if(at!==null&&at.trim()!=="")return at;let Se=$e.getExtractedText();return Se!==null&&Se.trim()!==""?Se:Oe},Y;try{Y=$e.processChunk(_e)}catch{rt(Oe),Rt();return}if(Y instanceof Promise){Y.then(vt=>{rt(Jt(vt)),Rt()}).catch(()=>{rt(Oe),Rt()});return}rt(Jt(Y)),Rt()},Be=[],j=!1,ge,nt=()=>{j||(j=!0,queueMicrotask(()=>{j=!1,ge()}))},kt=new Wi((O,ue)=>{Be.push({payloadType:O,payload:ue}),nt()}),ne=null,qe=new Map,_n=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ge=()=>{var O,ue,Oe,Ge,_e,$e,rt,Rt,jt,Jt,Y,vt,at,Se,ce,et,en,Kt,Pn,wn,mt,Et,Je,zt,cn,An,Tn,yn,Io,St,qn,jn,Vo,bo,xt,Sr,Ro,Ar,Vn,Jr,er,$o,At,Kn,Gn,Wn,It,ao,io,Yn,tr,Uo,nr,Qn,Dt,Bn,lo,or,zo,rr,Po,Xn,yo,ft,tn,nn,Jn,sr,we,vo,co,U,Zr,Wo,qo,jo,Bo,xo,Ps,Zn,eo,wo,Co,Tr,Ko,kn,Ho,es,kr,ts,Ga,ns,Ya,os,yt,Ws,po,$n,Qa,Xa,rs,Go,Bs,ar,Hs,Ds,Os,Fs,Un,ss,Do,Oo,Ns,Ja,_s,Vs,Er,Za,ei,ti,ni,Tl,Mr,ir,oi,$s,lr,ri,Us,cr,zs,si,Yo,ai,dr,Ot,as,is;for(let Lr=0;Lr<Be.length;Lr++){let Ue=Be[Lr].payloadType,k=Be[Lr].payload;if(Ue==="reason_start"){let z=(O=xe(k,!0))!=null?O:`reason-${l()}`,W=De(z);W.reasoning=(ue=W.reasoning)!=null?ue:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(Ge=W.reasoning.startedAt)!=null?Ge:Pe((Oe=k.startedAt)!=null?Oe:k.timestamp),W.reasoning.completedAt=void 0,W.reasoning.durationMs=void 0,W.streaming=!0,W.reasoning.status="streaming",f(W)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let z=($e=(_e=xe(k,!1))!=null?_e:xe(k,!0))!=null?$e:`reason-${l()}`,W=De(z);W.reasoning=(rt=W.reasoning)!=null?rt:{id:z,status:"streaming",chunks:[]},W.reasoning.startedAt=(jt=W.reasoning.startedAt)!=null?jt:Pe((Rt=k.startedAt)!=null?Rt:k.timestamp);let Z=(vt=(Y=(Jt=k.reasoningText)!=null?Jt:k.text)!=null?Y:k.delta)!=null?vt:"";if(Z&&k.hidden!==!0){let ie=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(ie!==void 0){let Q=pe(z,ie,String(Z));W.reasoning.chunks=[Q]}else W.reasoning.chunks.push(String(Z))}if(W.reasoning.status=k.done?"complete":"streaming",k.done){W.reasoning.completedAt=Pe((at=k.completedAt)!=null?at:k.timestamp);let ie=(Se=W.reasoning.startedAt)!=null?Se:Date.now();W.reasoning.durationMs=Math.max(0,((ce=W.reasoning.completedAt)!=null?ce:Date.now())-ie)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(Ue==="reason_complete"){let z=(en=(et=xe(k,!1))!=null?et:xe(k,!0))!=null?en:`reason-${l()}`,W=R.get(z);if(W!=null&&W.reasoning){W.reasoning.status="complete",W.reasoning.completedAt=Pe((Kt=k.completedAt)!=null?Kt:k.timestamp);let ie=(Pn=W.reasoning.startedAt)!=null?Pn:Date.now();W.reasoning.durationMs=Math.max(0,((wn=W.reasoning.completedAt)!=null?wn:Date.now())-ie),W.streaming=!1,f(W)}let Z=$(k);Z&&w.byStep.delete(Z)}else if(Ue==="tool_start"){let z=(mt=K(k,!0))!=null?mt:`tool-${l()}`,W=(Et=k.toolName)!=null?Et:k.name;if(be(W)){le.add(z);continue}let Z=ae(z),ie=(Je=Z.toolCall)!=null?Je:{id:z,status:"pending"};ie.name=W!=null?W:ie.name,ie.status="running",k.args!==void 0?ie.args=k.args:k.parameters!==void 0&&(ie.args=k.parameters),ie.startedAt=(cn=ie.startedAt)!=null?cn:Pe((zt=k.startedAt)!=null?zt:k.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,Z.toolCall=ie,Z.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(Z.agentMetadata={executionId:(An=Q==null?void 0:Q.executionId)!=null?An:k.executionId,iteration:(Tn=Q==null?void 0:Q.iteration)!=null?Tn:k.iteration}),f(Z)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let z=(Io=(yn=K(k,!1))!=null?yn:K(k,!0))!=null?Io:`tool-${l()}`;if(le.has(z))continue;let W=ae(z),Z=(St=W.toolCall)!=null?St:{id:z,status:"running"};Z.startedAt=(jn=Z.startedAt)!=null?jn:Pe((qn=k.startedAt)!=null?qn:k.timestamp);let ie=(xt=(bo=(Vo=k.text)!=null?Vo:k.delta)!=null?bo:k.message)!=null?xt:"";ie&&(Z.chunks=(Sr=Z.chunks)!=null?Sr:[],Z.chunks.push(String(ie))),Z.status="running",W.toolCall=Z,W.streaming=!0;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(Vn=W.agentMetadata)!=null?Vn:{executionId:(Ro=Q==null?void 0:Q.executionId)!=null?Ro:k.executionId,iteration:(Ar=Q==null?void 0:Q.iteration)!=null?Ar:k.iteration}),f(W)}else if(Ue==="tool_complete"){let z=(er=(Jr=K(k,!1))!=null?Jr:K(k,!0))!=null?er:`tool-${l()}`;if(le.has(z)){le.delete(z);continue}let W=ae(z),Z=($o=W.toolCall)!=null?$o:{id:z,status:"running"};Z.status="complete",k.result!==void 0&&(Z.result=k.result),typeof k.duration=="number"&&(Z.duration=k.duration),Z.completedAt=Pe((At=k.completedAt)!=null?At:k.timestamp);let ie=(Kn=k.duration)!=null?Kn:k.executionTime;if(typeof ie=="number")Z.durationMs=ie;else{let Ne=(Gn=Z.startedAt)!=null?Gn:Date.now();Z.durationMs=Math.max(0,((Wn=Z.completedAt)!=null?Wn:Date.now())-Ne)}W.toolCall=Z,W.streaming=!1;let Q=k.agentContext;(Q||k.executionId)&&(W.agentMetadata=(io=W.agentMetadata)!=null?io:{executionId:(It=Q==null?void 0:Q.executionId)!=null?It:k.executionId,iteration:(ao=Q==null?void 0:Q.iteration)!=null?ao:k.iteration}),f(W);let Le=G(k);Le&&C.byCall.delete(Le)}else if(Ue==="step_await"&&k.awaitReason==="local_tool_required"&&k.toolName){let z=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,W=(Yn=z!=null?z:k.toolId)!=null?Yn:`local-${l()}`,Z=ae(W),ie=k.toolName,Q=ma(ie),Le=(tr=Z.toolCall)!=null?tr:{id:W,status:"pending"};Le.name=ie,Le.args=k.parameters,Le.status=Q?"running":"complete",Le.chunks=(Uo=Le.chunks)!=null?Uo:[],Le.startedAt=(Qn=Le.startedAt)!=null?Qn:Pe((nr=k.startedAt)!=null?nr:k.timestamp),Q?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=(Dt=Le.completedAt)!=null?Dt:Le.startedAt,Z.toolCall=Le,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lo=k.executionId)!=null?lo:(Bn=Z.agentMetadata)==null?void 0:Bn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},f(Z)}else if(Ue==="text_start"){if((or=k.toolContext)!=null&&or.toolId)continue;let z=k.partId;if(z!==void 0&&M.current!==null&&z!==M.current){let W=m;W&&(W.streaming=!1,f(W),Ie=W,m=null,I=!0)}z!==void 0&&(M.current=z)}else if(Ue==="text_end"){if((zo=k.toolContext)!=null&&zo.toolId)continue;let z=m;z&&(z.streaming=!1,f(z),Ie=z,m=null,I=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((Po=(rr=k.id)!=null?rr:Z.stepId)!=null?Po:`step-${l()}`),ct=k.partId!==void 0&&k.partId!==null?String(k.partId):"",Ze=`${Z.toolId}::${Ne}`,Bt=P.get(Ze);if(ct!==""&&Bt!==void 0&&Bt!==""&&Bt!==ct){let st=D.get(E(Z.toolId,Ne,Bt));st&&st.streaming!==!1&&(st.streaming=!1,f(st))}ct!==""&&P.set(Ze,ct);let Vt=S(Z.toolId,Ne,ct,Z.executionId),mn=(tn=(ft=(yo=(Xn=k.text)!=null?Xn:k.delta)!=null?yo:k.content)!=null?ft:k.chunk)!=null?tn:"";mn&&(Vt.content+=String(mn),Vt.streaming=!0,f(Vt)),k.isComplete&&(Vt.streaming=!1,f(Vt));continue}let ie=k.partId;if(ie!==void 0&&M.current!==null&&ie!==M.current){let Ne=m;Ne&&(Ne.streaming=!1,f(Ne),Ie=Ne,m=null,I=!0)}ie!==void 0&&(M.current=ie);let Q=ie!==void 0&&(nn=lt.get(ie))!=null?nn:de();ie!==void 0&&(Q.partId||(Q.partId=ie),lt.set(ie,Q));let Le=(vo=(we=(sr=(Jn=k.text)!=null?Jn:k.delta)!=null?sr:k.content)!=null?we:k.chunk)!=null?vo:"";if(Le){let Ne=typeof k.seq=="number"?k.seq:void 0,ct=ie!=null?ie:Q.id,Ze=Ne!==void 0?pe(ct,Ne,String(Le)):((co=re.get(Q.id))!=null?co:"")+Le;Q.rawContent=Ze,ee.has(Q.id)||ee.set(Q.id,this.createStreamParser());let Bt=ee.get(Q.id),Vt=Ze.trim().startsWith("{")||Ze.trim().startsWith("[");if(Vt&&re.set(Q.id,Ze),Bt.__isPlainTextParser===!0){Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q);continue}let st=Bt.processChunk(Ze);if(st instanceof Promise)st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")Q.content=Zt,f(Q);else if(!Vt&&!Ze.trim().startsWith("<")){let Cn=m,Yt=Cn&&Cn.id===Q.id?Cn:Q;Yt.id===Q.id&&(Yt.content=Ne!==void 0?Ze:Yt.content+Le,re.delete(Yt.id),ee.delete(Yt.id),Yt.rawContent=void 0,f(Yt))}}).catch(()=>{Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q)});else{let ht=typeof st=="string"?st:(U=st==null?void 0:st.text)!=null?U:null;ht!==null&&ht.trim()!==""?(Q.content=ht,f(Q)):!Vt&&!Ze.trim().startsWith("<")&&(Q.content=Ne!==void 0?Ze:Q.content+Le,re.delete(Q.id),ee.delete(Q.id),Q.rawContent=void 0,f(Q))}}if(k.isComplete){let Ne=(Wo=(Zr=k.result)==null?void 0:Zr.response)!=null?Wo:Q.content;if(Ne){let ct=re.get(Q.id),Ze=ct!=null?ct:oe(Ne);Q.rawContent=Ze;let Bt=ee.get(Q.id),Vt=null,mn=!1;if(Bt&&(Vt=Bt.getExtractedText(),Vt===null&&(Vt=Ur(Ze)),Vt===null)){let st=Bt.processChunk(Ze);st instanceof Promise?(mn=!0,st.then(ht=>{var Ke;let Zt=typeof ht=="string"?ht:(Ke=ht==null?void 0:ht.text)!=null?Ke:null;if(Zt!==null){let Cn=m;Cn&&Cn.id===Q.id&&(Cn.content=Zt,Cn.streaming=!1,ee.delete(Cn.id),re.delete(Cn.id),f(Cn))}})):Vt=typeof st=="string"?st:(qo=st==null?void 0:st.text)!=null?qo:null}if(!mn){Vt!==null&&Vt.trim()!==""?Q.content=Vt:re.has(Q.id)||(Q.content=oe(Ne));let st=ee.get(Q.id);if(st){let ht=(jo=st.close)==null?void 0:jo.call(st);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(Q.id)}re.delete(Q.id),Q.streaming=!1,f(Q)}}}}else if(Ue==="step_complete"){let z=k.stepType,W=k.executionType;if(z==="tool"||W==="context")continue;let Z=k.toolContext;if(Z!=null&&Z.toolId){let Ne=String((xo=(Bo=k.id)!=null?Bo:Z.stepId)!=null?xo:"");if(Ne){let ct=A(Z.toolId,Ne);for(let[Ze,Bt]of D)Ze.startsWith(ct)&&Bt.streaming!==!1&&(Bt.streaming=!1,f(Bt));P.delete(`${Z.toolId}::${Ne}`)}continue}let ie=k.stopReason;if(I){if(m!==null){let Ze=m;ie&&(Ze.stopReason=ie),ee.delete(Ze.id),re.delete(Ze.id),Ze.streaming!==!1&&(Ze.streaming=!1,f(Ze))}let Ne=(Ps=k.result)==null?void 0:Ps.response,ct=Ie;ct&&(ie&&(ct.stopReason=ie),Ne!=null?Xe(ct,Ne):(ee.delete(ct.id),re.delete(ct.id))),Ie=null;continue}let Q=(Zn=k.result)==null?void 0:Zn.response,Le=de();if(ie&&(Le.stopReason=ie),Q!=null){let Ne=ee.get(Le.id),ct=!1,Ze=!1;if(Ne){let Bt=Ne.getExtractedText(),Vt=re.get(Le.id),mn=Vt!=null?Vt:oe(Q);if(Le.rawContent=mn,Bt!==null&&Bt.trim()!=="")Le.content=Bt,ct=!0;else{let st=Ur(mn);if(st!==null)Le.content=st,ct=!0;else{let ht=Ne.processChunk(mn);if(ht instanceof Promise)Ze=!0,ht.then(Zt=>{var Cn;let Ke=typeof Zt=="string"?Zt:(Cn=Zt==null?void 0:Zt.text)!=null?Cn:null;if(Ke!==null&&Ke.trim()!==""){let Yt=m;Yt&&Yt.id===Le.id&&(Yt.content=Ke,Yt.streaming=!1,ee.delete(Yt.id),re.delete(Yt.id),f(Yt))}else{let Yt=Ne.getExtractedText(),vn=m;vn&&vn.id===Le.id&&(Yt!==null&&Yt.trim()!==""?vn.content=Yt:re.has(vn.id)||(vn.content=oe(Q)),vn.streaming=!1,ee.delete(vn.id),re.delete(vn.id),f(vn))}});else{let Zt=typeof ht=="string"?ht:(eo=ht==null?void 0:ht.text)!=null?eo:null;if(Zt!==null&&Zt.trim()!=="")Le.content=Zt,ct=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Le.content=Ke,ct=!0)}}}}}if(!Ze){if(!Le.rawContent){let Bt=re.get(Le.id);Le.rawContent=Bt!=null?Bt:oe(Q)}if(!ct&&!re.has(Le.id)&&(Le.content=oe(Q)),Ne){let Bt=(wo=Ne.close)==null?void 0:wo.call(Ne);Bt instanceof Promise&&Bt.catch(()=>{})}ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}}else ee.delete(Le.id),re.delete(Le.id),Le.streaming=!1,f(Le)}else if(Ue==="flow_complete"){let z=(Co=k.result)==null?void 0:Co.response;if(I){if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}}else if(z!=null){let W=de(),Z=re.get(W.id),ie=Z!=null?Z:oe(z);W.rawContent=ie;let Q=oe(z),Le=ee.get(W.id);if(Le){let Ze=Ur(ie);if(Ze!==null)Q=Ze;else{let Bt=Le.processChunk(ie);Bt instanceof Promise&&Bt.then(mn=>{var ht;let st=typeof mn=="string"?mn:(ht=mn==null?void 0:mn.text)!=null?ht:null;st!==null&&(W.content=st,W.streaming=!1,f(W))});let Vt=Le.getExtractedText();Vt!==null&&(Q=Vt)}}ee.delete(W.id),re.delete(W.id);let Ne=Q!==W.content,ct=W.streaming!==!1;Ne&&(W.content=Q),W.streaming=!1,(Ne||ct)&&f(W)}else if(m!==null){let W=m;ee.delete(W.id),re.delete(W.id),W.streaming!==!1&&(W.streaming=!1,f(W))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")ne={executionId:k.executionId,agentId:(Tr=k.agentId)!=null?Tr:"virtual",agentName:(Ko=k.agentName)!=null?Ko:"",status:"running",currentIteration:0,maxTurns:(kn=k.maxTurns)!=null?kn:1,startedAt:Pe(k.startedAt)};else if(Ue==="agent_iteration_start"){if(ne&&(ne.currentIteration=k.iteration),_n==="separate"&&k.iteration>1){let z=m;z&&(z.streaming=!1,f(z),qe.set(k.iteration-1,z),m=null)}}else if(Ue==="agent_turn_start")x=null;else if(Ue==="agent_turn_delta"){if(k.contentType==="text"){let z=de();z.content+=(Ho=k.delta)!=null?Ho:"",z.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId,agentName:ne==null?void 0:ne.agentName},x=z,f(z)}else if(k.contentType==="thinking"){let z=(es=k.turnId)!=null?es:`agent-think-${k.iteration}`,W=De(z);W.reasoning=(kr=W.reasoning)!=null?kr:{id:z,status:"streaming",chunks:[]},W.reasoning.chunks.push((ts=k.delta)!=null?ts:""),W.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:k.turnId},f(W)}else if(k.contentType==="tool_input"){let z=(Ga=k.toolCallId)!=null?Ga:C.lastId;if(z){let W=B.get(z);W!=null&&W.toolCall&&(W.toolCall.chunks=(ns=W.toolCall.chunks)!=null?ns:[],W.toolCall.chunks.push((Ya=k.delta)!=null?Ya:""),f(W))}}}else if(Ue==="agent_turn_complete"){let z=k.turnId;if(z){let ie=R.get(z);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Pe(k.completedAt);let Q=(os=ie.reasoning.startedAt)!=null?os:Date.now();ie.reasoning.durationMs=Math.max(0,((yt=ie.reasoning.completedAt)!=null?yt:Date.now())-Q),ie.streaming=!1,f(ie)}}let W=k.stopReason,Z=m!=null?m:x;if(W&&Z!==null){let ie=k.turnId;(!ie||((Ws=Z.agentMetadata)==null?void 0:Ws.turnId)===ie)&&(Z.stopReason=W,f(Z))}}else if(Ue==="agent_tool_start"){m&&(m.streaming=!1,f(m),m=null);let z=(po=k.toolCallId)!=null?po:`agent-tool-${l()}`;Ae(G(k),z);let W=ae(z),Z=($n=W.toolCall)!=null?$n:{id:z,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};Z.name=(Xa=(Qa=k.toolName)!=null?Qa:k.name)!=null?Xa:Z.name,Z.status="running",k.parameters!==void 0&&(Z.args=k.parameters),Z.startedAt=Pe((rs=k.startedAt)!=null?rs:k.timestamp),W.toolCall=Z,W.streaming=!0,W.agentMetadata={executionId:k.executionId,iteration:k.iteration},f(W)}else if(Ue==="agent_tool_delta"){let z=(Go=k.toolCallId)!=null?Go:C.lastId;if(z){let W=(Bs=B.get(z))!=null?Bs:ae(z);W.toolCall&&(W.toolCall.chunks=(ar=W.toolCall.chunks)!=null?ar:[],W.toolCall.chunks.push((Hs=k.delta)!=null?Hs:""),W.toolCall.status="running",W.streaming=!0,f(W))}}else if(Ue==="agent_tool_complete"){let z=(Ds=k.toolCallId)!=null?Ds:C.lastId;if(z){let W=(Os=B.get(z))!=null?Os:ae(z);if(W.toolCall){W.toolCall.status="complete",k.result!==void 0&&(W.toolCall.result=k.result),typeof k.executionTime=="number"&&(W.toolCall.durationMs=k.executionTime),W.toolCall.completedAt=Pe((Fs=k.completedAt)!=null?Fs:k.timestamp),W.streaming=!1,f(W);let Z=G(k);Z&&C.byCall.delete(Z)}}}else if(Ue==="agent_media"){let z=Array.isArray(k.media)?k.media:[],W=[];for(let Z of z){if(!Z||typeof Z!="object")continue;let ie=Z,Q=typeof ie.type=="string"?ie.type:void 0,Le=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",Ne=null,ct="";if(Q==="media"){let Ze=typeof ie.data=="string"?ie.data:void 0;if(!Ze)continue;ct=Le.length>0?Le:"application/octet-stream",Ne=`data:${ct};base64,${Ze}`}else if(Q==="image-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else if(Q==="file-url"){let Ze=typeof ie.url=="string"?ie.url:void 0;if(!Ze)continue;ct=Le,Ne=Ze}else continue;if(Ne)if(Q==="image-url"||ct.startsWith("image/"))W.push({type:"image",image:Ne,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))W.push({type:"audio",audio:Ne,mimeType:ct});else if(ct.startsWith("video/"))W.push({type:"video",video:Ne,mimeType:ct});else{let Ze=ct||"application/octet-stream";W.push({type:"file",data:Ne,mimeType:Ze,filename:_b(Ze)})}}if(W.length>0){let Z=l(),ie=k.toolCallId,Le={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:W,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(Le);let Ne=m;Ne&&(Ne.streaming=!1,f(Ne)),m=null,v.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let z=`agent-reflection-${k.executionId}-${k.iteration}`,W={id:z,role:"assistant",content:(Un=k.reflection)!=null?Un:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:z,status:"complete",chunks:[(ss=k.reflection)!=null?ss:""]},agentMetadata:{executionId:k.executionId,iteration:k.iteration}};f(W)}else if(Ue==="agent_complete"){ne&&(ne.status=k.success?"complete":"error",ne.completedAt=Pe(k.completedAt),ne.stopReason=k.stopReason);let z=m;z&&(z.streaming=!1,f(z)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let z=typeof k.error=="string"?k.error:(Oo=(Do=k.error)==null?void 0:Do.message)!=null?Oo:"Agent execution error";k.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",z):n({type:"error",error:new Error(z)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let z=(Ns=k.approvalId)!=null?Ns:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Ja=ne==null?void 0:ne.agentId)!=null?Ja:"virtual",executionId:(Vs=(_s=k.executionId)!=null?_s:ne==null?void 0:ne.executionId)!=null?Vs:"",toolName:(Er=k.toolName)!=null?Er:"",toolType:k.toolType,description:(ei=k.description)!=null?ei:`Execute ${(Za=k.toolName)!=null?Za:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="step_await"&&k.awaitReason==="approval_required"){let z=(ti=k.approvalId)!=null?ti:`approval-${l()}`,W={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(ni=ne==null?void 0:ne.agentId)!=null?ni:"virtual",executionId:(Mr=(Tl=k.executionId)!=null?Tl:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(ir=k.toolName)!=null?ir:"",toolType:k.toolType,description:($s=k.description)!=null?$s:`Execute ${(oi=k.toolName)!=null?oi:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};f(W)}else if(Ue==="agent_approval_complete"){let z=k.approvalId;if(z){let Z={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(lr=k.decision)!=null?lr:"approved",agentId:(ri=ne==null?void 0:ne.agentId)!=null?ri:"virtual",executionId:(cr=(Us=k.executionId)!=null?Us:ne==null?void 0:ne.executionId)!=null?cr:"",toolName:(zs=k.toolName)!=null?zs:"",description:(si=k.description)!=null?si:"",resolvedAt:Date.now()}};f(Z)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let z=k.artifactType,W=String(k.id),Z=typeof k.title=="string"?k.title:void 0;if(n({type:"artifact_start",id:W,artifactType:z,title:Z,component:typeof k.component=="string"?k.component:void 0}),ye.set(W,{markdown:"",title:Z}),!se.has(W)){se.add(W);let ie={id:`artifact-ref-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:W,title:Z,artifactType:z,status:"streaming"}})};X.set(W,ie),f(ie)}}else if(Ue==="artifact_delta"){let z=String(k.id),W=typeof k.delta=="string"?k.delta:String((Yo=k.delta)!=null?Yo:"");n({type:"artifact_delta",id:z,artDelta:W});let Z=ye.get(z);Z&&(Z.markdown+=W)}else if(Ue==="artifact_update"){let z=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};n({type:"artifact_update",id:String(k.id),props:z,component:typeof k.component=="string"?k.component:void 0})}else if(Ue==="artifact_complete"){let z=String(k.id);n({type:"artifact_complete",id:z});let W=X.get(z);if(W){W.streaming=!1;try{let Z=JSON.parse((ai=W.rawContent)!=null?ai:"{}");if(Z.props){Z.props.status="complete";let ie=ye.get(z);ie!=null&&ie.markdown&&(Z.props.markdown=ie.markdown)}W.rawContent=JSON.stringify(Z)}catch{}ye.delete(z),f(W),X.delete(z)}}}else if(Ue==="transcript_insert"){let z=k.message;if(!z||typeof z!="object")continue;let W=String((dr=z.id)!=null?dr:`msg-${l()}`),Z=z.role,Q={id:W,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(f(Q),Q.rawContent)try{let Le=JSON.parse(Q.rawContent),Ne=(Ot=Le==null?void 0:Le.props)==null?void 0:Ot.artifactId;typeof Ne=="string"&&se.add(Ne)}catch{}m=null,v.current=null,ee.delete(W),re.delete(W)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let z=null;if(k.error instanceof Error)z=k.error;else if(Ue==="dispatch_error"){let W=(as=k.message)!=null?as:k.error;W!=null&&W!==""&&(z=new Error(String(W)))}else if(Ue==="step_error"||Ue==="flow_error"){let W=k.error;typeof W=="string"&&W!==""?z=new Error(W):W!=null&&typeof W=="object"&&"message"in W&&(z=new Error(String((is=W.message)!=null?is:W)))}else Ue==="error"&&k.error!=null&&k.error!==""&&(z=new Error(String(k.error)));if(z){n({type:"error",error:z});let W=m;W&&W.streaming&&(W.streaming=!1,f(W)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:O,value:ue}=await r.read();if(O)break;a+=s.decode(ue,{stream:!0});let Oe=a.split(`
|
|
10
10
|
|
|
11
11
|
`);a=(ln=Oe.pop())!=null?ln:"";for(let Ge of Oe){let _e=Ge.split(`
|
|
12
12
|
`),$e="message",rt="";for(let Jt of _e)Jt.startsWith("event:")?$e=Jt.replace("event:","").trim():Jt.startsWith("data:")&&(rt+=Jt.replace("data:","").trim());if(!rt)continue;let Rt;try{Rt=JSON.parse(rt)}catch(Jt){n({type:"error",error:Jt instanceof Error?Jt:new Error("Failed to parse chat stream payload")});continue}let jt=$e!=="message"?$e:(so=Rt.type)!=null?so:"message";if((Lo=this.onSSEEvent)==null||Lo.call(this,jt,Rt),this.parseSSEEvent){v.current=m;let Jt=await this.handleCustomSSEEvent(Rt,n,v,f,l,M);if(v.current&&v.current!==m&&(m=v.current),Jt)continue}kt.push(jt,Rt),ge()}}kt.flushPending(),ge(),kt.destroy()}};function Hi(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function va(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Di="[Image]";function cc(e){return{type:"text",text:e}}var rg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ub=["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"],Jo=[...rg,...Ub];function zb(e){return rg.includes(e)||e.startsWith("image/")}function Oi(e){return zb(e.type)}async function sg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Oi(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 ag(e,t=Jo,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 qb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ig(e,t){let n=qb(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 Fi=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 Ni=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 xa=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 Ni;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=I=>{x||(x=!0,clearTimeout(M),m(new Error(I)))},M=setTimeout(()=>v("WebSocket connection timed out."+g),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(M),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+u+"."+g)},{once:!0}),this.ws.addEventListener("close",I=>{if(!I.wasClean&&!x){let R=I.code!==1006?` (code ${I.code})`:"";v("WebSocket connection failed"+R+"."+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 Fi(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 zr=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 wa(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new xa(e.runtype);case"browser":if(!zr.isSupported())throw new Error("Browser speech recognition not supported");return new zr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function lg(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wa({type:"runtype",runtype:e.runtype});if(zr.isSupported())return wa({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function dc(e){try{return lg(e),!0}catch{return!1}}var jb=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Kb(e,t){return jb.some(n=>e[n]!==t[n])}function cg(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}
|