@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/index.global.js
CHANGED
|
@@ -54,7 +54,7 @@ ${e}`:"")+(r.description?`
|
|
|
54
54
|
${r.description}`:"");return window.confirm(t)},N0=r=>{if(r==null)return"";try{let e=JSON.stringify(r,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(r)}},F0=r=>{if(r===void 0)return"{}";try{let e=JSON.stringify(r);return e===void 0?"{}":e}catch{return"{}"}},U0=r=>{if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}};var Un=Bi(ji(),1);var C=(r,e)=>{let t=document.createElement(r);return e&&(t.className=e),t},un=(r,e,t)=>{let o=r.createElement(e);return t&&(o.className=t),o};var $s="ask_user_question",zs=8,Ka="data-persona-ask-sheet-for",j0="Other",G0="Other\u2026",_h="Type your own answer here",Nh="Send",K0="Next",X0="Back",Q0="Submit all",Y0="Skip",J0=3,Bd="data-ask-current-index",Dd="data-ask-question-count",Fh="data-ask-answers",Od="data-ask-grouped",Uh="data-ask-layout",Z0=r=>r.layout==="pills"?"pills":"rows",ev=r=>r.getAttribute(Uh)==="pills"?"pills":"rows",Oh=!1,qh=r=>r.replace(/["\\]/g,"\\$&"),wn=r=>r.variant==="tool"&&!!r.toolCall&&r.toolCall.name===$s,Gi=r=>{var e,t;return(t=(e=r==null?void 0:r.features)==null?void 0:e.askUserQuestion)!=null?t:{}},An=r=>{let e=r.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:t};try{let n=o.join(""),a=(0,Un.parse)(n,Un.STR|Un.OBJ|Un.ARR);if(a&&typeof a=="object")return{payload:a,complete:t}}catch{}return{payload:null,complete:t}},Vs=r=>{let e=Array.isArray(r==null?void 0:r.questions)?r.questions:[];return e.length>zs&&!Oh&&(Oh=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${zs}.`)),e.slice(0,zs)},tv=r=>{var e;return(e=Vs(r)[0])!=null?e:null},rv=(r,e)=>{var t;return(t=Vs(r)[e])!=null?t:null},zh=(r,e)=>{let t=e.styles;t&&(t.sheetBackground&&r.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&r.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&r.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&r.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&r.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&r.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&r.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&r.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&r.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},$h=(r,e,t)=>{if(r!=="rows")return null;let o=C("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let n=C("span","persona-ask-row-check");o.appendChild(n)}else{let n=C("span","persona-ask-row-badge");n.textContent=String(t+1),o.appendChild(n)}return o},ov=(r,e,t,o)=>{let a=C("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(e)),a.setAttribute("data-option-label",r.label),t==="rows"){let s=C("span","persona-ask-row-content"),i=C("span","persona-ask-row-label");if(i.textContent=r.label,s.appendChild(i),r.description){let l=C("span","persona-ask-row-description");l.textContent=r.description,s.appendChild(l)}a.appendChild(s);let d=$h(t,o,e);d&&a.appendChild(d)}else a.textContent=r.label,r.description&&(a.title=r.description);return a},nv=r=>{let t=C("span",r==="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 t.setAttribute("aria-hidden","true"),t},av=(r,e,t,o)=>{var u,f,p;let a=C("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(r!=null&&r.multiSelect),d=(Array.isArray(r==null?void 0:r.options)?r.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<J0;m++)a.appendChild(nv(o));return a}if(d.forEach((m,y)=>{a.appendChild(ov(m,y,o,s))}),(r==null?void 0:r.allowFreeText)!==!1){let m=o==="rows"?j0:G0;if(o==="rows"){let y=C("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let h=C("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=e.freeTextPlaceholder)!=null?u:_h,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),h.appendChild(T),y.appendChild(h);let M=$h(o,s,d.length);M&&y.appendChild(M),a.appendChild(y)}else{let y=C("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(p=e.freeTextLabel)!=null?p:m,a.appendChild(y)}}return a},Vh=(r,e)=>{var a,s;let o=C("div",e==="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 n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=r.freeTextPlaceholder)!=null?a:_h,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),e!=="rows"){let i=C("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=r.submitLabel)!=null?s:Nh,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},sv=r=>{var o;let e=C("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=C("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(o=r.submitLabel)!=null?o:Nh,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},iv=(r,e,t)=>{var l,u,f,p;let o=C("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 n=C("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=t.backLabel)!=null?l:X0,n.setAttribute("data-ask-user-action","back"),n.disabled=r===0,o.appendChild(n);let a=C("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=C("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(u=t.skipLabel)!=null?u:Y0,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=C("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=r===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Q0:(p=t.nextLabel)!=null?p:K0,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},ha=r=>{let e=r.getAttribute(Fh);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},jh=(r,e)=>{r.setAttribute(Fh,JSON.stringify(e))},jo=r=>{var t;let e=Number((t=r.getAttribute(Bd))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},lv=(r,e)=>{r.setAttribute(Bd,String(Math.max(0,Math.floor(e))))},Xa=r=>{var t;let e=Number((t=r.getAttribute(Dd))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},qn=r=>r.getAttribute(Od)==="true",dv=(r,e)=>{var n;let t=(n=r.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let o={};return e.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(o[s]=d)}}),o},cv=(r,e)=>{var o;let t=(o=r.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},Ki=(r,e)=>{let{payload:t}=An(e),o=Vs(t),n=ha(r),a={},s=new Set;return o.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,d)&&(a[l]=n[d]))}),a},Gh=r=>{let e=ha(r),t=jo(r),o=e[t],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(d=>n.add(d));let a=r.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(d=>{var f;let l=(f=d.getAttribute("data-option-label"))!=null?f:"",u=n.has(l);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let s=new Set(Array.from(a).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=r.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.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=""},Kh=r=>{if(!qn(r))return;let e=ha(r),t=jo(r),o=e[t],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=r.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=r.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},_d=(r,e,t)=>{let o=Gi(t),n=ev(r),{payload:a,complete:s}=An(e),i=qn(r),d=jo(r),l=Xa(r),u=i?rv(a,d):tv(a),f=!!(u!=null&&u.multiSelect),p=r.querySelector('[data-ask-step-inline="true"]');p&&(p.textContent=i?`${d+1}/${l}`:"");let m=r.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=r.querySelector('[data-ask-question="true"]');if(y){let k=typeof(u==null?void 0:u.question)=="string"?u.question:"";y.textContent=k,y.classList.toggle("persona-ask-question-skeleton",!k&&!s)}let h=r.querySelector('[data-ask-pill-list="true"]');if(h){let k=av(u,o,s,n);h.replaceWith(k)}if(n!=="rows"){let k=r.querySelector('[data-ask-free-text-row="true"]');k&&k.replaceWith(Vh(o,n))}let T=r.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!T?r.appendChild(sv(o)):(!f||i)&&T&&T.remove(),r.setAttribute("data-multi-select",f?"true":"false");let M=r.querySelector('[data-ask-nav-row="true"]');if(i){let k=iv(d,l,o);M?M.replaceWith(k):r.appendChild(k)}else M&&M.remove();Gh(r),Kh(r)},pv=(r,e,t)=>{let o=Gi(e),n=Z0(o),a=r.toolCall.id,s=Vs(t),i=Math.max(1,s.length),d=i>1,l=dv(r,s),u=d?cv(r,i):0,f=C("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Ka,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",r.id),f.setAttribute(Dd,String(i)),f.setAttribute(Bd,String(u)),f.setAttribute(Od,d?"true":"false"),f.setAttribute(Uh,n),jh(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),zh(f,o);let p=C("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=C("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",p.appendChild(m);let y=C("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",p.appendChild(y),f.appendChild(p);let T=C("div",n==="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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),n!=="rows"&&f.appendChild(Vh(o,n)),_d(f,r,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},uv=(r,e,t)=>{let{payload:o}=An(e),n=Math.max(1,Vs(o).length);n>Xa(r)&&(r.setAttribute(Dd,String(n)),n>1&&!qn(r)&&r.setAttribute(Od,"true")),_d(r,e,t)},Xh=(r,e)=>{let t=C("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");t.id=`bubble-${r.id}`,t.setAttribute("data-message-id",r.id),t.setAttribute("data-bubble-type","ask-user-question");let o=Gi(e);zh(t,o);let n=C("span","persona-ask-stub-label"),{complete:a}=An(r);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",t.appendChild(n),t},Qa=(r,e,t)=>{if(!t||!wn(r)||Gi(e).enabled===!1)return;let n=r.toolCall.id;t.querySelectorAll(`[${Ka}]`).forEach(l=>{l.getAttribute(Ka)!==n&&l.remove()});let s=t.querySelector(`[${Ka}="${qh(n)}"]`);if(s){uv(s,r,e);return}let{payload:i}=An(r),d=pv(r,e,i);t.appendChild(d)},zn=(r,e)=>{if(!r)return;let t=e?`[${Ka}="${qh(e)}"]`:`[${Ka}]`;r.querySelectorAll(t).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Nd=r=>Array.from(r.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),$n=(r,e)=>{let t=ha(r),o=jo(r);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[o]:t[o]=e,jh(r,t),Gh(r),Kh(r)},Xi=(r,e,t,o)=>{let n=Xa(r),a=Math.max(0,Math.min(n-1,o));lv(r,a),_d(r,e,t)};var en="suggest_replies";var Fd={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Qi={name:en,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:Fd,origin:"sdk",annotations:{readOnlyHint:!0}},Ud=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),js=r=>{var e;return r.variant==="tool"&&((e=r.toolCall)==null?void 0:e.name)===en},qd=r=>{let e=r;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let o=t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.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},Yi=r=>{var e;for(let t=r.length-1;t>=0;t--){let o=r[t];if(o.role==="user")return null;if(!js(o))continue;let n=qd((e=o.toolCall)==null?void 0:e.args);return n.length>0?n:null}return null},Qh=r=>{var t;let e=(t=r==null?void 0:r.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var zd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option \u2014 free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},$d={name:$s,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:zd,origin:"sdk",annotations:{readOnlyHint:!0}},Gs=r=>{var o;let e=[],t=(o=r==null?void 0:r.features)==null?void 0:o.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push($d),Qh(r)&&e.push(Qi),e};var Sn=Bi(ji(),1),Ji=r=>r.replace(/\\n/g,`
|
|
55
55
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ya=r=>{if(r===null)return"null";if(r===void 0)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);try{return JSON.stringify(r,null,2)}catch{return String(r)}},fv=r=>{var s,i;let e=(s=r.completedAt)!=null?s:Date.now(),t=(i=r.startedAt)!=null?i:e,n=(r.durationMs!==void 0?r.durationMs:Math.max(0,e-t))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Yh=r=>r.status==="complete"?fv(r):r.status==="pending"?"Waiting":"",mv=r=>{var n,a,s;let t=(typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((n=r.completedAt)!=null?n:Date.now())-((s=(a=r.startedAt)!=null?a:r.completedAt)!=null?s:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Jh=r=>r.status==="complete"?mv(r):"Using tool...",Zi=r=>{let e=r/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Xs=r=>{var t,o,n;let e=typeof r.duration=="number"?r.duration:typeof r.durationMs=="number"?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((n=(o=r.startedAt)!=null?o:r.completedAt)!=null?n:Date.now()));return Zi(e)},el=r=>{var t,o,n;let e=r.durationMs!==void 0?r.durationMs:Math.max(0,((t=r.completedAt)!=null?t:Date.now())-((n=(o=r.startedAt)!=null?o:r.completedAt)!=null?n:Date.now()));return Zi(e)},Vd=(r,e,t)=>{var a;if(!e)return t;let o=((a=r.name)==null?void 0:a.trim())||"tool",n=Xs(r);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},tl=(r,e)=>{let t=r.replace(/\{toolName\}/g,e),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(t))!==null;)s.index>a&&Ks(o,t.slice(a,s.index),[]),s[1]!==void 0?Ks(o,s[1],["bold"]):s[2]!==void 0?Ks(o,s[2],["italic"]):s[3]!==void 0&&Ks(o,s[3],["dim"]),a=s.index+s[0].length;return a<t.length&&Ks(o,t.slice(a),[]),o},Ks=(r,e,t)=>{let o=e.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&r.push({text:o[n],styles:t}),n<o.length-1&&r.push({text:"{duration}",styles:t,isDuration:!0})},gv=()=>{let r=null,e=0,t=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
56
56
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
57
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>r,processChunk:async o=>{if(o.length<=e)return r!==null?{text:r,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=t(o);return a!==null&&(r=a),e=o.length,r!==null?{text:r,raw:o}:null},close:async()=>{}}},xa=r=>{try{let e=JSON.parse(r);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},rl=()=>{let r={processChunk:e=>null,getExtractedText:()=>null};return r.__isPlainTextParser=!0,r},ol=()=>{var e;let r=gv();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:r.processChunk(t)},getExtractedText:r.getExtractedText.bind(r),close:(e=r.close)==null?void 0:e.bind(r)}},nl=()=>{let r=null,e=0;return{getExtractedText:()=>r,processChunk:t=>{let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=e)return r!==null||r===""?{text:r||"",raw:t}:null;try{let n=(0,Sn.parse)(t,Sn.STR|Sn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?r=typeof n.text=="string"?Ji(n.text):"":n.type==="init"&&n.form?r="":typeof n.text=="string"&&(r=Ji(n.text)))}catch{}return e=t.length,r!==null?{text:r,raw:t}:null},close:()=>{}}},Zh=r=>{let e=null,t=0,n=r||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Ji(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ji(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>e,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return e!==null?{text:e,raw:a}:null;try{let i=(0,Sn.parse)(a,Sn.STR|Sn.OBJ),d=n(i);d!==null&&(e=d)}catch{}return t=a.length,{text:e||"",raw:a}},close:()=>{}}},al=()=>{let r=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(r=o[1],{text:r,raw:e}):null},getExtractedText:()=>r}};var sl=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var a,s,i;let o=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(e,t);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:e,payload:t,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.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 e=[...this.buffer.entries()].sort((t,o)=>t[0]-o[0]);for(let[t,o]of e)this.buffer.delete(t),this.emitter(o.payloadType,o.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var hv="https://api.runtype.com/v1/dispatch",il="https://api.runtype.com";function xv(r){var a,s;let e=r.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let n=e.indexOf("/");if(n>0){let i=(s=(a=e.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var jd=r=>!!(r.contentParts&&r.contentParts.length>0||r.llmContent&&r.llmContent.trim().length>0||r.rawContent&&r.rawContent.trim().length>0||r.content&&r.content.trim().length>0);function yv(r){switch(r){case"json":return nl;case"regex-json":return ol;case"xml":return al;default:return rl}}var ex=r=>r.startsWith("{")||r.startsWith("[")||r.startsWith("<");function bv(r,e){if(!r)return e;let t=r.trim(),o=e.trim();if(t.length===0)return e;if(o.length===0)return r;let n=ex(t);if(!ex(o))return r;if(!n||o===t||o.startsWith(t))return e;let s=xa(r);return xa(e)!==null&&s===null?e:r}var ya=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,o,n,a;this.apiUrl=(t=e.apiUrl)!=null?t:hv,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(o=e.streamParser)!=null?o:yv(e.parserType),this.contextProviders=(n=e.contextProviders)!=null?n:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((a=e.webmcp)==null?void 0:a.enabled)===!0?new Ga(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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(),(t=(e=this.config).onSessionInit)==null||t.call(e,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let e=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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 n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/feedback`}async sendFeedback(e){var a,s;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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let n=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.json().catch(()=>({error:"Feedback submission failed"}));throw n.status===401?(this.clientSession=null,(s=(a=this.config).onSessionExpired)==null||s.call(a),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){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:e,comment:t})}async submitNPSFeedback(e,t){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:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var n,a,s,i;let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}let l=await this.buildPayload(e.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(jd).map(x=>{var w,v,E;return{id:x.id,role:x.role,content:(E=(v=(w=x.contentParts)!=null?w:x.llmContent)!=null?v:x.rawContent)!=null?E:x.content}}),...e.assistantMessageId&&{assistantMessageId:e.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}},p=l.clientTools,m=!!(p&&p.length>0),y=m?Bh(p):void 0,h=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&h&&this.lastSentClientToolsFingerprint===y,M=!1,k=null,L;for(let x=0;;x++){let v={...f,...m&&(M||!T)&&p?{clientTools:p}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),L.status===409&&x===0&&m){let E=await L.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}k=E!=null?E:{error:"Chat request failed"}}break}if(!L.ok){let x=k!=null?k:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(L.status===429){let v=new Error(x.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let w=new Error(x.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!L.body){let x=new Error("No response body received");throw t({type:"error",error:x}),x}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({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")&&t({type:"error",error:l}),l}}async dispatchProxy(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/agents/${e.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,o){var l,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||il}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(e){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(jd).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:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,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(e){var a,s;let o={messages:e.slice().filter(jd).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}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,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(e,t,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=f,n(f),f},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,o){var Rt,dr,Yr,zr;let n=e.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let fe=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Ie=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Je=O.tools?O.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...O,reasoning:fe,toolCall:Ie,tools:Je}},f=O=>{if(O.role!=="assistant"||O.variant)return!0;let fe=Array.isArray(O.contentParts)&&O.contentParts.length>0,Ie=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||fe||Ie||!!O.stopReason},p=O=>{f(O)&&t({type:"message",message:u(O)})},m=null,y=null,h={current:null},T={current:null},M=!1,k=new Map,L=new Map,x=new Map,w=new Map,v={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},H=(O,fe,Ie="")=>`${O}::${fe}::${Ie}`,I=(O,fe)=>`${O}::${fe}::`,P=(O,fe,Ie,Je)=>{let qe=H(O,fe,Ie),ze=x.get(qe);if(ze)return ze;let lt=Ie?`-${Ie}`:"",Mt={id:`nested-${O}-${fe}${lt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:Je,parentToolId:O,parentStepId:fe}};return x.set(qe,Mt),p(Mt),Mt},z=O=>{if(O==null)return null;try{return String(O)}catch{return null}},j=O=>{var fe,Ie,Je,qe,ze;return z((ze=(qe=(Je=(Ie=(fe=O.stepId)!=null?fe:O.step_id)!=null?Ie:O.step)!=null?Je:O.parentId)!=null?qe:O.flowStepId)!=null?ze:O.flow_step_id)},ie=O=>{var fe,Ie,Je,qe,ze,lt,Mt;return z((Mt=(lt=(ze=(qe=(Je=(Ie=(fe=O.callId)!=null?fe:O.call_id)!=null?Ie:O.requestId)!=null?Je:O.request_id)!=null?qe:O.toolCallId)!=null?ze:O.tool_call_id)!=null?lt:O.stepId)!=null?Mt:O.step_id)},ve=o,Xe=!1,Ae=()=>{if(m)return m;let O;return!Xe&&ve?(O=ve,Xe=!0):ve&&T.current?O=`${ve}_${T.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()},p(m),m},We=(O,fe)=>{v.lastId=fe,O&&v.byStep.set(O,fe)},Me=(O,fe)=>{var ze;let Ie=(ze=O.reasoningId)!=null?ze:O.id,Je=j(O);if(Ie){let lt=String(Ie);return We(Je,lt),lt}if(Je){let lt=v.byStep.get(Je);if(lt)return v.lastId=lt,lt}if(v.lastId&&!fe)return v.lastId;if(!fe)return null;let qe=`reason-${l()}`;return We(Je,qe),qe},Ue=O=>{let fe=k.get(O);if(fe)return fe;let Ie={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return k.set(O,Ie),p(Ie),Ie},Be=(O,fe)=>{E.lastId=fe,O&&E.byCall.set(O,fe)},Z=new Set,ne=new Map,me=new Set,be=new Map,ye=O=>{if(!O)return!1;let fe=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return fe==="emit_artifact_markdown"||fe==="emit_artifact_component"},Y=(O,fe)=>{var ze;let Ie=(ze=O.toolId)!=null?ze:O.id,Je=ie(O);if(Ie){let lt=String(Ie);return Be(Je,lt),lt}if(Je){let lt=E.byCall.get(Je);if(lt)return E.lastId=lt,lt}if(E.lastId&&!fe)return E.lastId;if(!fe)return null;let qe=`tool-${l()}`;return Be(Je,qe),qe},ge=O=>{let fe=L.get(O);if(fe)return fe;let Ie={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return L.set(O,Ie),p(Ie),Ie},Oe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let fe=Number(O);if(!Number.isNaN(fe)&&Number.isFinite(fe))return fe;let Ie=Date.parse(O);if(!Number.isNaN(Ie))return Ie}return Date.now()},ce=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ae=new Map,Q=new Map,Tt=new Map,Ye=new Map,De=null,le=(O,fe,Ie)=>{var Mt;let Je=Tt.get(O);Je||(Je=[],Tt.set(O,Je));let qe=0,ze=Je.length;for(;qe<ze;){let Dt=qe+ze>>>1;Je[Dt].seq<fe?qe=Dt+1:ze=Dt}((Mt=Je[qe])==null?void 0:Mt.seq)===fe?Je[qe]={seq:fe,text:Ie}:Je.splice(qe,0,{seq:fe,text:Ie});let lt="";for(let Dt=0;Dt<Je.length;Dt++)lt+=Je[Dt].text;return lt},nt=(O,fe)=>{let Ie=ce(fe),Je=Q.get(O.id),qe=bv(Je,Ie);O.rawContent=qe;let ze=ae.get(O.id),lt=wt=>{var Ce;let ct=(Ce=O.content)!=null?Ce:"";wt.trim()!==""&&(ct.trim().length===0||wt.startsWith(ct)||wt.trimStart().startsWith(ct.trim()))&&(O.content=wt)},Mt=()=>{var wt;if(ze){let ct=(wt=ze.close)==null?void 0:wt.call(ze);ct instanceof Promise&&ct.catch(()=>{})}ae.delete(O.id),Q.delete(O.id),O.streaming=!1,p(O)};if(!ze){lt(Ie),Mt();return}let Dt=xa(qe);if(Dt!==null&&Dt.trim()!==""){lt(Dt),Mt();return}let or=wt=>{var de;let ct=typeof wt=="string"?wt:(de=wt==null?void 0:wt.text)!=null?de:null;if(ct!==null&&ct.trim()!=="")return ct;let Ce=ze.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:Ie},X;try{X=ze.processChunk(qe)}catch{lt(Ie),Mt();return}if(X instanceof Promise){X.then(wt=>{lt(or(wt)),Mt()}).catch(()=>{lt(Ie),Mt()});return}lt(or(X)),Mt()},Re=[],K=!1,he,it=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,he()}))},Pt=new sl((O,fe)=>{Re.push({payloadType:O,payload:fe}),it()}),te=null,_e=new Map,Ar=(Rt=this.config.iterationDisplay)!=null?Rt:"separate";for(he=()=>{var O,fe,Ie,Je,qe,ze,lt,Mt,Dt,or,X,wt,ct,Ce,de,rt,Ft,zt,Pr,vr,xt,It,tt,jt,cr,Dr,hr,Sr,Oo,je,Tr,io,_o,lo,At,rn,No,mn,Jr,Ln,$r,Fo,mt,co,po,Or,Wt,Vr,Zr,_r,uo,fo,Nr,mo,$t,Fr,go,on,Uo,nn,qo,eo,to,gt,re,A,_,ue,$,at,ut,U,nr,mr,Cr,ko,sr,Ko,us,Eo,Lo,Xo,Qo,Qn,gn,ro,an,Pa,Yn,Ra,bi,Ia,vi,Ha,Lt,fs,zo,So,Ci,wi,Wa,hn,ms,Pn,gs,hs,xs,ys,To,Ba,sn,ln,bs,Ai,vs,Cs,Jn,Si,Ti,Mi,ki,dd,Zn,Rn,Ei,ws,In,Li,As,Hn,Ss,Pi,xn,Ri,Wn,Gt,Da,Oa;for(let ea=0;ea<Re.length;ea++){let Ke=Re[ea].payloadType,R=Re[ea].payload;if(Ke==="reason_start"){let V=(O=Me(R,!0))!=null?O:`reason-${l()}`,B=Ue(V);B.reasoning=(fe=B.reasoning)!=null?fe:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Je=B.reasoning.startedAt)!=null?Je:Oe((Ie=R.startedAt)!=null?Ie:R.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",p(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let V=(ze=(qe=Me(R,!1))!=null?qe:Me(R,!0))!=null?ze:`reason-${l()}`,B=Ue(V);B.reasoning=(lt=B.reasoning)!=null?lt:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Dt=B.reasoning.startedAt)!=null?Dt:Oe((Mt=R.startedAt)!=null?Mt:R.timestamp);let oe=(wt=(X=(or=R.reasoningText)!=null?or:R.text)!=null?X:R.delta)!=null?wt:"";if(oe&&R.hidden!==!0){let pe=typeof R.sequenceIndex=="number"?R.sequenceIndex:void 0;if(pe!==void 0){let J=le(V,pe,String(oe));B.reasoning.chunks=[J]}else B.reasoning.chunks.push(String(oe))}if(B.reasoning.status=R.done?"complete":"streaming",R.done){B.reasoning.completedAt=Oe((ct=R.completedAt)!=null?ct:R.timestamp);let pe=(Ce=B.reasoning.startedAt)!=null?Ce:Date.now();B.reasoning.durationMs=Math.max(0,((de=B.reasoning.completedAt)!=null?de:Date.now())-pe)}B.streaming=B.reasoning.status!=="complete",p(B)}else if(Ke==="reason_complete"){let V=(Ft=(rt=Me(R,!1))!=null?rt:Me(R,!0))!=null?Ft:`reason-${l()}`,B=k.get(V);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=Oe((zt=R.completedAt)!=null?zt:R.timestamp);let pe=(Pr=B.reasoning.startedAt)!=null?Pr:Date.now();B.reasoning.durationMs=Math.max(0,((vr=B.reasoning.completedAt)!=null?vr:Date.now())-pe),B.streaming=!1,p(B)}let oe=j(R);oe&&v.byStep.delete(oe)}else if(Ke==="tool_start"){let V=(xt=Y(R,!0))!=null?xt:`tool-${l()}`,B=(It=R.toolName)!=null?It:R.name;if(ye(B)){Z.add(V);continue}let oe=ge(V),pe=(tt=oe.toolCall)!=null?tt:{id:V,status:"pending"};pe.name=B!=null?B:pe.name,pe.status="running",R.args!==void 0?pe.args=R.args:R.parameters!==void 0&&(pe.args=R.parameters),pe.startedAt=(cr=pe.startedAt)!=null?cr:Oe((jt=R.startedAt)!=null?jt:R.timestamp),pe.completedAt=void 0,pe.durationMs=void 0,oe.toolCall=pe,oe.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(oe.agentMetadata={executionId:(Dr=J==null?void 0:J.executionId)!=null?Dr:R.executionId,iteration:(hr=J==null?void 0:J.iteration)!=null?hr:R.iteration}),p(oe)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let V=(Oo=(Sr=Y(R,!1))!=null?Sr:Y(R,!0))!=null?Oo:`tool-${l()}`;if(Z.has(V))continue;let B=ge(V),oe=(je=B.toolCall)!=null?je:{id:V,status:"running"};oe.startedAt=(io=oe.startedAt)!=null?io:Oe((Tr=R.startedAt)!=null?Tr:R.timestamp);let pe=(At=(lo=(_o=R.text)!=null?_o:R.delta)!=null?lo:R.message)!=null?At:"";pe&&(oe.chunks=(rn=oe.chunks)!=null?rn:[],oe.chunks.push(String(pe))),oe.status="running",B.toolCall=oe,B.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Jr=B.agentMetadata)!=null?Jr:{executionId:(No=J==null?void 0:J.executionId)!=null?No:R.executionId,iteration:(mn=J==null?void 0:J.iteration)!=null?mn:R.iteration}),p(B)}else if(Ke==="tool_complete"){let V=($r=(Ln=Y(R,!1))!=null?Ln:Y(R,!0))!=null?$r:`tool-${l()}`;if(Z.has(V)){Z.delete(V);continue}let B=ge(V),oe=(Fo=B.toolCall)!=null?Fo:{id:V,status:"running"};oe.status="complete",R.result!==void 0&&(oe.result=R.result),typeof R.duration=="number"&&(oe.duration=R.duration),oe.completedAt=Oe((mt=R.completedAt)!=null?mt:R.timestamp);let pe=(co=R.duration)!=null?co:R.executionTime;if(typeof pe=="number")oe.durationMs=pe;else{let Ve=(po=oe.startedAt)!=null?po:Date.now();oe.durationMs=Math.max(0,((Or=oe.completedAt)!=null?Or:Date.now())-Ve)}B.toolCall=oe,B.streaming=!1;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Zr=B.agentMetadata)!=null?Zr:{executionId:(Wt=J==null?void 0:J.executionId)!=null?Wt:R.executionId,iteration:(Vr=J==null?void 0:J.iteration)!=null?Vr:R.iteration}),p(B);let Le=ie(R);Le&&E.byCall.delete(Le)}else if(Ke==="step_await"&&R.awaitReason==="local_tool_required"&&R.toolName){let V=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,B=(_r=V!=null?V:R.toolId)!=null?_r:`local-${l()}`,oe=ge(B),pe=R.toolName,J=ga(pe),Le=(uo=oe.toolCall)!=null?uo:{id:B,status:"pending"};Le.name=pe,Le.args=R.parameters,Le.status=J?"running":"complete",Le.chunks=(fo=Le.chunks)!=null?fo:[],Le.startedAt=(mo=Le.startedAt)!=null?mo:Oe((Nr=R.startedAt)!=null?Nr:R.timestamp),J?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=($t=Le.completedAt)!=null?$t:Le.startedAt,oe.toolCall=Le,oe.streaming=!1,oe.agentMetadata={...oe.agentMetadata,executionId:(go=R.executionId)!=null?go:(Fr=oe.agentMetadata)==null?void 0:Fr.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},p(oe)}else if(Ke==="text_start"){if((on=R.toolContext)!=null&&on.toolId)continue;let V=R.partId;if(V!==void 0&&T.current!==null&&V!==T.current){let B=m;B&&(B.streaming=!1,p(B),De=B,m=null,M=!0)}V!==void 0&&(T.current=V)}else if(Ke==="text_end"){if((Uo=R.toolContext)!=null&&Uo.toolId)continue;let V=m;V&&(V.streaming=!1,p(V),De=V,m=null,M=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((qo=(nn=R.id)!=null?nn:oe.stepId)!=null?qo:`step-${l()}`),yt=R.partId!==void 0&&R.partId!==null?String(R.partId):"",dt=`${oe.toolId}::${Ve}`,Vt=w.get(dt);if(yt!==""&&Vt!==void 0&&Vt!==""&&Vt!==yt){let ht=x.get(H(oe.toolId,Ve,Vt));ht&&ht.streaming!==!1&&(ht.streaming=!1,p(ht))}yt!==""&&w.set(dt,yt);let Jt=P(oe.toolId,Ve,yt,oe.executionId),Rr=(re=(gt=(to=(eo=R.text)!=null?eo:R.delta)!=null?to:R.content)!=null?gt:R.chunk)!=null?re:"";Rr&&(Jt.content+=String(Rr),Jt.streaming=!0,p(Jt)),R.isComplete&&(Jt.streaming=!1,p(Jt));continue}let pe=R.partId;if(pe!==void 0&&T.current!==null&&pe!==T.current){let Ve=m;Ve&&(Ve.streaming=!1,p(Ve),De=Ve,m=null,M=!0)}pe!==void 0&&(T.current=pe);let J=pe!==void 0&&(A=Ye.get(pe))!=null?A:Ae();pe!==void 0&&(J.partId||(J.partId=pe),Ye.set(pe,J));let Le=(at=($=(ue=(_=R.text)!=null?_:R.delta)!=null?ue:R.content)!=null?$:R.chunk)!=null?at:"";if(Le){let Ve=typeof R.seq=="number"?R.seq:void 0,yt=pe!=null?pe:J.id,dt=Ve!==void 0?le(yt,Ve,String(Le)):((ut=Q.get(J.id))!=null?ut:"")+Le;J.rawContent=dt,ae.has(J.id)||ae.set(J.id,this.createStreamParser());let Vt=ae.get(J.id),Jt=dt.trim().startsWith("{")||dt.trim().startsWith("[");if(Jt&&Q.set(J.id,dt),Vt.__isPlainTextParser===!0){J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J);continue}let ht=Vt.processChunk(dt);if(ht instanceof Promise)ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null&&gr.trim()!=="")J.content=gr,p(J);else if(!Jt&&!dt.trim().startsWith("<")){let jr=m,pr=jr&&jr.id===J.id?jr:J;pr.id===J.id&&(pr.content=Ve!==void 0?dt:pr.content+Le,Q.delete(pr.id),ae.delete(pr.id),pr.rawContent=void 0,p(pr))}}).catch(()=>{J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J)});else{let kt=typeof ht=="string"?ht:(U=ht==null?void 0:ht.text)!=null?U:null;kt!==null&&kt.trim()!==""?(J.content=kt,p(J)):!Jt&&!dt.trim().startsWith("<")&&(J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J))}}if(R.isComplete){let Ve=(mr=(nr=R.result)==null?void 0:nr.response)!=null?mr:J.content;if(Ve){let yt=Q.get(J.id),dt=yt!=null?yt:ce(Ve);J.rawContent=dt;let Vt=ae.get(J.id),Jt=null,Rr=!1;if(Vt&&(Jt=Vt.getExtractedText(),Jt===null&&(Jt=xa(dt)),Jt===null)){let ht=Vt.processChunk(dt);ht instanceof Promise?(Rr=!0,ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null){let jr=m;jr&&jr.id===J.id&&(jr.content=gr,jr.streaming=!1,ae.delete(jr.id),Q.delete(jr.id),p(jr))}})):Jt=typeof ht=="string"?ht:(Cr=ht==null?void 0:ht.text)!=null?Cr:null}if(!Rr){Jt!==null&&Jt.trim()!==""?J.content=Jt:Q.has(J.id)||(J.content=ce(Ve));let ht=ae.get(J.id);if(ht){let kt=(ko=ht.close)==null?void 0:ko.call(ht);kt instanceof Promise&&kt.catch(()=>{}),ae.delete(J.id)}Q.delete(J.id),J.streaming=!1,p(J)}}}}else if(Ke==="step_complete"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((Ko=(sr=R.id)!=null?sr:oe.stepId)!=null?Ko:"");if(Ve){let yt=I(oe.toolId,Ve);for(let[dt,Vt]of x)dt.startsWith(yt)&&Vt.streaming!==!1&&(Vt.streaming=!1,p(Vt));w.delete(`${oe.toolId}::${Ve}`)}continue}let pe=R.stopReason;if(M){if(m!==null){let dt=m;pe&&(dt.stopReason=pe),ae.delete(dt.id),Q.delete(dt.id),dt.streaming!==!1&&(dt.streaming=!1,p(dt))}let Ve=(us=R.result)==null?void 0:us.response,yt=De;yt&&(pe&&(yt.stopReason=pe),Ve!=null?nt(yt,Ve):(ae.delete(yt.id),Q.delete(yt.id))),De=null;continue}let J=(Eo=R.result)==null?void 0:Eo.response,Le=Ae();if(pe&&(Le.stopReason=pe),J!=null){let Ve=ae.get(Le.id),yt=!1,dt=!1;if(Ve){let Vt=Ve.getExtractedText(),Jt=Q.get(Le.id),Rr=Jt!=null?Jt:ce(J);if(Le.rawContent=Rr,Vt!==null&&Vt.trim()!=="")Le.content=Vt,yt=!0;else{let ht=xa(Rr);if(ht!==null)Le.content=ht,yt=!0;else{let kt=Ve.processChunk(Rr);if(kt instanceof Promise)dt=!0,kt.then(gr=>{var jr;let et=typeof gr=="string"?gr:(jr=gr==null?void 0:gr.text)!=null?jr:null;if(et!==null&&et.trim()!==""){let pr=m;pr&&pr.id===Le.id&&(pr.content=et,pr.streaming=!1,ae.delete(pr.id),Q.delete(pr.id),p(pr))}else{let pr=Ve.getExtractedText(),Ur=m;Ur&&Ur.id===Le.id&&(pr!==null&&pr.trim()!==""?Ur.content=pr:Q.has(Ur.id)||(Ur.content=ce(J)),Ur.streaming=!1,ae.delete(Ur.id),Q.delete(Ur.id),p(Ur))}});else{let gr=typeof kt=="string"?kt:(Lo=kt==null?void 0:kt.text)!=null?Lo:null;if(gr!==null&&gr.trim()!=="")Le.content=gr,yt=!0;else{let et=Ve.getExtractedText();et!==null&&et.trim()!==""&&(Le.content=et,yt=!0)}}}}}if(!dt){if(!Le.rawContent){let Vt=Q.get(Le.id);Le.rawContent=Vt!=null?Vt:ce(J)}if(!yt&&!Q.has(Le.id)&&(Le.content=ce(J)),Ve){let Vt=(Xo=Ve.close)==null?void 0:Xo.call(Ve);Vt instanceof Promise&&Vt.catch(()=>{})}ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}}else ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}else if(Ke==="flow_complete"){let V=(Qo=R.result)==null?void 0:Qo.response;if(M){if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}}else if(V!=null){let B=Ae(),oe=Q.get(B.id),pe=oe!=null?oe:ce(V);B.rawContent=pe;let J=ce(V),Le=ae.get(B.id);if(Le){let dt=xa(pe);if(dt!==null)J=dt;else{let Vt=Le.processChunk(pe);Vt instanceof Promise&&Vt.then(Rr=>{var kt;let ht=typeof Rr=="string"?Rr:(kt=Rr==null?void 0:Rr.text)!=null?kt:null;ht!==null&&(B.content=ht,B.streaming=!1,p(B))});let Jt=Le.getExtractedText();Jt!==null&&(J=Jt)}}ae.delete(B.id),Q.delete(B.id);let Ve=J!==B.content,yt=B.streaming!==!1;Ve&&(B.content=J),B.streaming=!1,(Ve||yt)&&p(B)}else if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}t({type:"status",status:"idle"})}else if(Ke==="agent_start")te={executionId:R.executionId,agentId:(Qn=R.agentId)!=null?Qn:"virtual",agentName:(gn=R.agentName)!=null?gn:"",status:"running",currentIteration:0,maxTurns:(ro=R.maxTurns)!=null?ro:1,startedAt:Oe(R.startedAt)};else if(Ke==="agent_iteration_start"){if(te&&(te.currentIteration=R.iteration),Ar==="separate"&&R.iteration>1){let V=m;V&&(V.streaming=!1,p(V),_e.set(R.iteration-1,V),m=null)}}else if(Ke==="agent_turn_start")y=null;else if(Ke==="agent_turn_delta"){if(R.contentType==="text"){let V=Ae();V.content+=(an=R.delta)!=null?an:"",V.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId,agentName:te==null?void 0:te.agentName},y=V,p(V)}else if(R.contentType==="thinking"){let V=(Pa=R.turnId)!=null?Pa:`agent-think-${R.iteration}`,B=Ue(V);B.reasoning=(Yn=B.reasoning)!=null?Yn:{id:V,status:"streaming",chunks:[]},B.reasoning.chunks.push((Ra=R.delta)!=null?Ra:""),B.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId},p(B)}else if(R.contentType==="tool_input"){let V=(bi=R.toolCallId)!=null?bi:E.lastId;if(V){let B=L.get(V);B!=null&&B.toolCall&&(B.toolCall.chunks=(Ia=B.toolCall.chunks)!=null?Ia:[],B.toolCall.chunks.push((vi=R.delta)!=null?vi:""),p(B))}}}else if(Ke==="agent_turn_complete"){let V=R.turnId;if(V){let pe=k.get(V);if(pe!=null&&pe.reasoning){pe.reasoning.status="complete",pe.reasoning.completedAt=Oe(R.completedAt);let J=(Ha=pe.reasoning.startedAt)!=null?Ha:Date.now();pe.reasoning.durationMs=Math.max(0,((Lt=pe.reasoning.completedAt)!=null?Lt:Date.now())-J),pe.streaming=!1,p(pe)}}let B=R.stopReason,oe=m!=null?m:y;if(B&&oe!==null){let pe=R.turnId;(!pe||((fs=oe.agentMetadata)==null?void 0:fs.turnId)===pe)&&(oe.stopReason=B,p(oe))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let V=(zo=R.toolCallId)!=null?zo:`agent-tool-${l()}`;Be(ie(R),V);let B=ge(V),oe=(So=B.toolCall)!=null?So:{id:V,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};oe.name=(wi=(Ci=R.toolName)!=null?Ci:R.name)!=null?wi:oe.name,oe.status="running",R.parameters!==void 0&&(oe.args=R.parameters),oe.startedAt=Oe((Wa=R.startedAt)!=null?Wa:R.timestamp),B.toolCall=oe,B.streaming=!0,B.agentMetadata={executionId:R.executionId,iteration:R.iteration},p(B)}else if(Ke==="agent_tool_delta"){let V=(hn=R.toolCallId)!=null?hn:E.lastId;if(V){let B=(ms=L.get(V))!=null?ms:ge(V);B.toolCall&&(B.toolCall.chunks=(Pn=B.toolCall.chunks)!=null?Pn:[],B.toolCall.chunks.push((gs=R.delta)!=null?gs:""),B.toolCall.status="running",B.streaming=!0,p(B))}}else if(Ke==="agent_tool_complete"){let V=(hs=R.toolCallId)!=null?hs:E.lastId;if(V){let B=(xs=L.get(V))!=null?xs:ge(V);if(B.toolCall){B.toolCall.status="complete",R.result!==void 0&&(B.toolCall.result=R.result),typeof R.executionTime=="number"&&(B.toolCall.durationMs=R.executionTime),B.toolCall.completedAt=Oe((ys=R.completedAt)!=null?ys:R.timestamp),B.streaming=!1,p(B);let oe=ie(R);oe&&E.byCall.delete(oe)}}}else if(Ke==="agent_media"){let V=Array.isArray(R.media)?R.media:[],B=[];for(let oe of V){if(!oe||typeof oe!="object")continue;let pe=oe,J=typeof pe.type=="string"?pe.type:void 0,Le=typeof pe.mediaType=="string"?pe.mediaType.toLowerCase():"",Ve=null,yt="";if(J==="media"){let dt=typeof pe.data=="string"?pe.data:void 0;if(!dt)continue;yt=Le.length>0?Le:"application/octet-stream",Ve=`data:${yt};base64,${dt}`}else if(J==="image-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else if(J==="file-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else continue;if(Ve)if(J==="image-url"||yt.startsWith("image/"))B.push({type:"image",image:Ve,...yt?{mimeType:yt}:{}});else if(yt.startsWith("audio/"))B.push({type:"audio",audio:Ve,mimeType:yt});else if(yt.startsWith("video/"))B.push({type:"video",video:Ve,mimeType:yt});else{let dt=yt||"application/octet-stream";B.push({type:"file",data:Ve,mimeType:dt,filename:xv(dt)})}}if(B.length>0){let oe=l(),pe=R.toolCallId,Le={id:`agent-media-${typeof pe=="string"&&pe.length>0?`${pe}-${oe}`:String(oe)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:oe,agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(Le);let Ve=m;Ve&&(Ve.streaming=!1,p(Ve)),m=null,h.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let V=`agent-reflection-${R.executionId}-${R.iteration}`,B={id:V,role:"assistant",content:(To=R.reflection)!=null?To:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"complete",chunks:[(Ba=R.reflection)!=null?Ba:""]},agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(B)}else if(Ke==="agent_complete"){te&&(te.status=R.success?"complete":"error",te.completedAt=Oe(R.completedAt),te.stopReason=R.stopReason);let V=m;V&&(V.streaming=!1,p(V)),t({type:"status",status:"idle"})}else if(Ke==="agent_error"){let V=typeof R.error=="string"?R.error:(ln=(sn=R.error)==null?void 0:sn.message)!=null?ln:"Agent execution error";R.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",V):t({type:"error",error:new Error(V)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let V=(bs=R.approvalId)!=null?bs:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Ai=te==null?void 0:te.agentId)!=null?Ai:"virtual",executionId:(Cs=(vs=R.executionId)!=null?vs:te==null?void 0:te.executionId)!=null?Cs:"",toolName:(Jn=R.toolName)!=null?Jn:"",toolType:R.toolType,description:(Ti=R.description)!=null?Ti:`Execute ${(Si=R.toolName)!=null?Si:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="step_await"&&R.awaitReason==="approval_required"){let V=(Mi=R.approvalId)!=null?Mi:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(ki=te==null?void 0:te.agentId)!=null?ki:"virtual",executionId:(Zn=(dd=R.executionId)!=null?dd:te==null?void 0:te.executionId)!=null?Zn:"",toolName:(Rn=R.toolName)!=null?Rn:"",toolType:R.toolType,description:(ws=R.description)!=null?ws:`Execute ${(Ei=R.toolName)!=null?Ei:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="agent_approval_complete"){let V=R.approvalId;if(V){let oe={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(In=R.decision)!=null?In:"approved",agentId:(Li=te==null?void 0:te.agentId)!=null?Li:"virtual",executionId:(Hn=(As=R.executionId)!=null?As:te==null?void 0:te.executionId)!=null?Hn:"",toolName:(Ss=R.toolName)!=null?Ss:"",description:(Pi=R.description)!=null?Pi:"",resolvedAt:Date.now()}};p(oe)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let V=R.artifactType,B=String(R.id),oe=typeof R.title=="string"?R.title:void 0;if(t({type:"artifact_start",id:B,artifactType:V,title:oe,component:typeof R.component=="string"?R.component:void 0}),be.set(B,{markdown:"",title:oe}),!me.has(B)){me.add(B);let pe={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:oe,artifactType:V,status:"streaming"}})};ne.set(B,pe),p(pe)}}else if(Ke==="artifact_delta"){let V=String(R.id),B=typeof R.delta=="string"?R.delta:String((xn=R.delta)!=null?xn:"");t({type:"artifact_delta",id:V,artDelta:B});let oe=be.get(V);oe&&(oe.markdown+=B)}else if(Ke==="artifact_update"){let V=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};t({type:"artifact_update",id:String(R.id),props:V,component:typeof R.component=="string"?R.component:void 0})}else if(Ke==="artifact_complete"){let V=String(R.id);t({type:"artifact_complete",id:V});let B=ne.get(V);if(B){B.streaming=!1;try{let oe=JSON.parse((Ri=B.rawContent)!=null?Ri:"{}");if(oe.props){oe.props.status="complete";let pe=be.get(V);pe!=null&&pe.markdown&&(oe.props.markdown=pe.markdown)}B.rawContent=JSON.stringify(oe)}catch{}be.delete(V),p(B),ne.delete(V)}}}else if(Ke==="transcript_insert"){let V=R.message;if(!V||typeof V!="object")continue;let B=String((Wn=V.id)!=null?Wn:`msg-${l()}`),oe=V.role,J={id:B,role:oe==="user"?"user":oe==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:l()};if(p(J),J.rawContent)try{let Le=JSON.parse(J.rawContent),Ve=(Gt=Le==null?void 0:Le.props)==null?void 0:Gt.artifactId;typeof Ve=="string"&&me.add(Ve)}catch{}m=null,h.current=null,ae.delete(B),Q.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let V=null;if(R.error instanceof Error)V=R.error;else if(Ke==="dispatch_error"){let B=(Da=R.message)!=null?Da:R.error;B!=null&&B!==""&&(V=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=R.error;typeof B=="string"&&B!==""?V=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(V=new Error(String((Oa=B.message)!=null?Oa:B)))}else Ke==="error"&&R.error!=null&&R.error!==""&&(V=new Error(String(R.error)));if(V){t({type:"error",error:V});let B=m;B&&B.streaming&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}}}}}Re.length=0};;){let{done:O,value:fe}=await n.read();if(O)break;s+=a.decode(fe,{stream:!0});let Ie=s.split(`
|
|
57
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>r,processChunk:async o=>{if(o.length<=e)return r!==null?{text:r,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=t(o);return a!==null&&(r=a),e=o.length,r!==null?{text:r,raw:o}:null},close:async()=>{}}},xa=r=>{try{let e=JSON.parse(r);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},rl=()=>{let r={processChunk:e=>null,getExtractedText:()=>null};return r.__isPlainTextParser=!0,r},ol=()=>{var e;let r=gv();return{processChunk:async t=>{let o=t.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:r.processChunk(t)},getExtractedText:r.getExtractedText.bind(r),close:(e=r.close)==null?void 0:e.bind(r)}},nl=()=>{let r=null,e=0;return{getExtractedText:()=>r,processChunk:t=>{let o=t.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(t.length<=e)return r!==null||r===""?{text:r||"",raw:t}:null;try{let n=(0,Sn.parse)(t,Sn.STR|Sn.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?r=typeof n.text=="string"?Ji(n.text):"":n.type==="init"&&n.form?r="":typeof n.text=="string"&&(r=Ji(n.text)))}catch{}return e=t.length,r!==null?{text:r,raw:t}:null},close:()=>{}}},Zh=r=>{let e=null,t=0,n=r||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?Ji(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?Ji(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>e,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=t)return e!==null?{text:e,raw:a}:null;try{let i=(0,Sn.parse)(a,Sn.STR|Sn.OBJ),d=n(i);d!==null&&(e=d)}catch{}return t=a.length,{text:e||"",raw:a}},close:()=>{}}},al=()=>{let r=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(r=o[1],{text:r,raw:e}):null},getExtractedText:()=>r}};var sl=class{constructor(e,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=e,this.gapTimeoutMs=t}push(e,t){var a,s,i;let o=(i=(a=t==null?void 0:t.seq)!=null?a:t==null?void 0:t.sequenceIndex)!=null?i:(s=t==null?void 0:t.agentContext)==null?void 0:s.seq;if(o==null){this.buffer.size>0&&this.flushAll(),this.emitter(e,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),o===this.nextExpectedSeq){this.emitter(e,t),this.nextExpectedSeq=o+1,this.drainConsecutive();return}if(o<this.nextExpectedSeq){this.emitter(e,t);return}let n=this.buffer.get(o);n!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${o} (${n.payloadType} vs ${e}); emitting earlier event out-of-order to avoid loss`),this.emitter(n.payloadType,n.payload)),this.buffer.set(o,{payloadType:e,payload:t,seq:o}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let e=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(e.payloadType,e.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 e=[...this.buffer.entries()].sort((t,o)=>t[0]-o[0]);for(let[t,o]of e)this.buffer.delete(t),this.emitter(o.payloadType,o.payload);e.length>0&&(this.nextExpectedSeq=e[e.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var hv="https://api.runtype.com/v1/dispatch",il="https://api.runtype.com";function xv(r){var a,s;let e=r.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let n=e.indexOf("/");if(n>0){let i=(s=(a=e.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var jd=r=>!!(r.contentParts&&r.contentParts.length>0||r.llmContent&&r.llmContent.trim().length>0||r.rawContent&&r.rawContent.trim().length>0||r.content&&r.content.trim().length>0);function yv(r){switch(r){case"json":return nl;case"regex-json":return ol;case"xml":return al;default:return rl}}var ex=r=>r.startsWith("{")||r.startsWith("[")||r.startsWith("<");function bv(r,e){if(!r)return e;let t=r.trim(),o=e.trim();if(t.length===0)return e;if(o.length===0)return r;let n=ex(t);if(!ex(o))return r;if(!n||o===t||o.startsWith(t))return e;let s=xa(r);return xa(e)!==null&&s===null?e:r}var ya=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,o,n,a;this.apiUrl=(t=e.apiUrl)!=null?t:hv,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(o=e.streamParser)!=null?o:yv(e.parserType),this.contextProviders=(n=e.contextProviders)!=null?n:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((a=e.webmcp)==null?void 0:a.enabled)===!0?new Ga(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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(),(t=(e=this.config).onSessionInit)==null||t.call(e,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var a,s;let e=((s=(a=this.config).getStoredSessionId)==null?void 0:s.call(a))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},o=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});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 n=await o.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(n.sessionId),{sessionId:n.sessionId,expiresAt:new Date(n.expiresAt),flow:n.flow,config:{welcomeMessage:n.config.welcomeMessage,placeholder:n.config.placeholder,theme:n.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/client/feedback`}async sendFeedback(e){var s,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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let n={...e,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok){let d=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){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:e,comment:t})}async submitNPSFeedback(e,t){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:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var n,a,s,i;let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let x=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:x}),x}let l=await this.buildPayload(e.messages),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([x])=>x!=="sessionId"&&x!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(jd).map(x=>{var w,v,E;return{id:x.id,role:x.role,content:(E=(v=(w=x.contentParts)!=null?w:x.llmContent)!=null?v:x.rawContent)!=null?E:x.content}}),...e.assistantMessageId&&{assistantMessageId:e.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}},p=l.clientTools,m=!!(p&&p.length>0),y=m?Bh(p):void 0,h=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&h&&this.lastSentClientToolsFingerprint===y,M=!1,k=null,L;for(let x=0;;x++){let v={...f,...m&&(M||!T)&&p?{clientTools:p}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v),signal:o.signal}),L.status===409&&x===0&&m){let E=await L.json().catch(()=>null);if((E==null?void 0:E.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}k=E!=null?E:{error:"Chat request failed"}}break}if(!L.ok){let x=k!=null?k:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(L.status===429){let v=new Error(x.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let w=new Error(x.error||"Failed to send message");throw t({type:"error",error:w}),w}if(!L.body){let x=new Error("No response body received");throw t({type:"error",error:x}),x}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({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")&&t({type:"error",error:l}),l}}async dispatchProxy(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let o=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>o.abort()),t({type:"status",status:"connecting"});let n=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||il}/v1/agents/${e.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,o){var l,u;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||il}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=o==null?void 0:o.streamResponse)!=null?u:!0};return s&&(d.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(d),signal:o==null?void 0:o.signal})}async buildAgentPayload(e){var a,s;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(jd).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:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,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(e){var a,s;let o={messages:e.slice().filter(jd).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}},n=[...Gs(this.config),...(s=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?s:[]];if(n.length>0&&(o.clientTools=n),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:e,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(e,t,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...u!==void 0&&{partId:u}};return o.current=f,n(f),f},l=u=>o.current?o.current:d(u);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),d(i.partId)),i.partId!==void 0&&(s.current=i.partId);let u=l(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,n(u)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,t({type:"status",status:"idle"})),i.error&&(s.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,o){var Rt,dr,Yr,zr;let n=e.getReader(),a=new TextDecoder,s="",i=Date.now(),d=0,l=()=>i+d++,u=O=>{let fe=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,Ie=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,Je=O.tools?O.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...O,reasoning:fe,toolCall:Ie,tools:Je}},f=O=>{if(O.role!=="assistant"||O.variant)return!0;let fe=Array.isArray(O.contentParts)&&O.contentParts.length>0,Ie=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||fe||Ie||!!O.stopReason},p=O=>{f(O)&&t({type:"message",message:u(O)})},m=null,y=null,h={current:null},T={current:null},M=!1,k=new Map,L=new Map,x=new Map,w=new Map,v={lastId:null,byStep:new Map},E={lastId:null,byCall:new Map},H=(O,fe,Ie="")=>`${O}::${fe}::${Ie}`,I=(O,fe)=>`${O}::${fe}::`,P=(O,fe,Ie,Je)=>{let qe=H(O,fe,Ie),ze=x.get(qe);if(ze)return ze;let lt=Ie?`-${Ie}`:"",Mt={id:`nested-${O}-${fe}${lt}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:Je,parentToolId:O,parentStepId:fe}};return x.set(qe,Mt),p(Mt),Mt},z=O=>{if(O==null)return null;try{return String(O)}catch{return null}},j=O=>{var fe,Ie,Je,qe,ze;return z((ze=(qe=(Je=(Ie=(fe=O.stepId)!=null?fe:O.step_id)!=null?Ie:O.step)!=null?Je:O.parentId)!=null?qe:O.flowStepId)!=null?ze:O.flow_step_id)},ie=O=>{var fe,Ie,Je,qe,ze,lt,Mt;return z((Mt=(lt=(ze=(qe=(Je=(Ie=(fe=O.callId)!=null?fe:O.call_id)!=null?Ie:O.requestId)!=null?Je:O.request_id)!=null?qe:O.toolCallId)!=null?ze:O.tool_call_id)!=null?lt:O.stepId)!=null?Mt:O.step_id)},ve=o,Xe=!1,Ae=()=>{if(m)return m;let O;return!Xe&&ve?(O=ve,Xe=!0):ve&&T.current?O=`${ve}_${T.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()},p(m),m},We=(O,fe)=>{v.lastId=fe,O&&v.byStep.set(O,fe)},Me=(O,fe)=>{var ze;let Ie=(ze=O.reasoningId)!=null?ze:O.id,Je=j(O);if(Ie){let lt=String(Ie);return We(Je,lt),lt}if(Je){let lt=v.byStep.get(Je);if(lt)return v.lastId=lt,lt}if(v.lastId&&!fe)return v.lastId;if(!fe)return null;let qe=`reason-${l()}`;return We(Je,qe),qe},Ue=O=>{let fe=k.get(O);if(fe)return fe;let Ie={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:O,status:"streaming",chunks:[]}};return k.set(O,Ie),p(Ie),Ie},Be=(O,fe)=>{E.lastId=fe,O&&E.byCall.set(O,fe)},Z=new Set,ne=new Map,me=new Set,be=new Map,ye=O=>{if(!O)return!1;let fe=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return fe==="emit_artifact_markdown"||fe==="emit_artifact_component"},Y=(O,fe)=>{var ze;let Ie=(ze=O.toolId)!=null?ze:O.id,Je=ie(O);if(Ie){let lt=String(Ie);return Be(Je,lt),lt}if(Je){let lt=E.byCall.get(Je);if(lt)return E.lastId=lt,lt}if(E.lastId&&!fe)return E.lastId;if(!fe)return null;let qe=`tool-${l()}`;return Be(Je,qe),qe},ge=O=>{let fe=L.get(O);if(fe)return fe;let Ie={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:O,status:"pending"}};return L.set(O,Ie),p(Ie),Ie},Oe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let fe=Number(O);if(!Number.isNaN(fe)&&Number.isFinite(fe))return fe;let Ie=Date.parse(O);if(!Number.isNaN(Ie))return Ie}return Date.now()},ce=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},ae=new Map,Q=new Map,Tt=new Map,Ye=new Map,De=null,le=(O,fe,Ie)=>{var Mt;let Je=Tt.get(O);Je||(Je=[],Tt.set(O,Je));let qe=0,ze=Je.length;for(;qe<ze;){let Dt=qe+ze>>>1;Je[Dt].seq<fe?qe=Dt+1:ze=Dt}((Mt=Je[qe])==null?void 0:Mt.seq)===fe?Je[qe]={seq:fe,text:Ie}:Je.splice(qe,0,{seq:fe,text:Ie});let lt="";for(let Dt=0;Dt<Je.length;Dt++)lt+=Je[Dt].text;return lt},nt=(O,fe)=>{let Ie=ce(fe),Je=Q.get(O.id),qe=bv(Je,Ie);O.rawContent=qe;let ze=ae.get(O.id),lt=wt=>{var Ce;let ct=(Ce=O.content)!=null?Ce:"";wt.trim()!==""&&(ct.trim().length===0||wt.startsWith(ct)||wt.trimStart().startsWith(ct.trim()))&&(O.content=wt)},Mt=()=>{var wt;if(ze){let ct=(wt=ze.close)==null?void 0:wt.call(ze);ct instanceof Promise&&ct.catch(()=>{})}ae.delete(O.id),Q.delete(O.id),O.streaming=!1,p(O)};if(!ze){lt(Ie),Mt();return}let Dt=xa(qe);if(Dt!==null&&Dt.trim()!==""){lt(Dt),Mt();return}let or=wt=>{var de;let ct=typeof wt=="string"?wt:(de=wt==null?void 0:wt.text)!=null?de:null;if(ct!==null&&ct.trim()!=="")return ct;let Ce=ze.getExtractedText();return Ce!==null&&Ce.trim()!==""?Ce:Ie},X;try{X=ze.processChunk(qe)}catch{lt(Ie),Mt();return}if(X instanceof Promise){X.then(wt=>{lt(or(wt)),Mt()}).catch(()=>{lt(Ie),Mt()});return}lt(or(X)),Mt()},Re=[],K=!1,he,it=()=>{K||(K=!0,queueMicrotask(()=>{K=!1,he()}))},Pt=new sl((O,fe)=>{Re.push({payloadType:O,payload:fe}),it()}),te=null,_e=new Map,Ar=(Rt=this.config.iterationDisplay)!=null?Rt:"separate";for(he=()=>{var O,fe,Ie,Je,qe,ze,lt,Mt,Dt,or,X,wt,ct,Ce,de,rt,Ft,zt,Pr,vr,xt,It,tt,jt,cr,Dr,hr,Sr,Oo,je,Tr,io,_o,lo,At,rn,No,mn,Jr,Ln,$r,Fo,mt,co,po,Or,Wt,Vr,Zr,_r,uo,fo,Nr,mo,$t,Fr,go,on,Uo,nn,qo,eo,to,gt,re,A,_,ue,$,at,ut,U,nr,mr,Cr,ko,sr,Ko,us,Eo,Lo,Xo,Qo,Qn,gn,ro,an,Pa,Yn,Ra,bi,Ia,vi,Ha,Lt,fs,zo,So,Ci,wi,Wa,hn,ms,Pn,gs,hs,xs,ys,To,Ba,sn,ln,bs,Ai,vs,Cs,Jn,Si,Ti,Mi,ki,dd,Zn,Rn,Ei,ws,In,Li,As,Hn,Ss,Pi,xn,Ri,Wn,Gt,Da,Oa;for(let ea=0;ea<Re.length;ea++){let Ke=Re[ea].payloadType,R=Re[ea].payload;if(Ke==="reason_start"){let V=(O=Me(R,!0))!=null?O:`reason-${l()}`,B=Ue(V);B.reasoning=(fe=B.reasoning)!=null?fe:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Je=B.reasoning.startedAt)!=null?Je:Oe((Ie=R.startedAt)!=null?Ie:R.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",p(B)}else if(Ke==="reason_delta"||Ke==="reason_chunk"){let V=(ze=(qe=Me(R,!1))!=null?qe:Me(R,!0))!=null?ze:`reason-${l()}`,B=Ue(V);B.reasoning=(lt=B.reasoning)!=null?lt:{id:V,status:"streaming",chunks:[]},B.reasoning.startedAt=(Dt=B.reasoning.startedAt)!=null?Dt:Oe((Mt=R.startedAt)!=null?Mt:R.timestamp);let oe=(wt=(X=(or=R.reasoningText)!=null?or:R.text)!=null?X:R.delta)!=null?wt:"";if(oe&&R.hidden!==!0){let pe=typeof R.sequenceIndex=="number"?R.sequenceIndex:void 0;if(pe!==void 0){let J=le(V,pe,String(oe));B.reasoning.chunks=[J]}else B.reasoning.chunks.push(String(oe))}if(B.reasoning.status=R.done?"complete":"streaming",R.done){B.reasoning.completedAt=Oe((ct=R.completedAt)!=null?ct:R.timestamp);let pe=(Ce=B.reasoning.startedAt)!=null?Ce:Date.now();B.reasoning.durationMs=Math.max(0,((de=B.reasoning.completedAt)!=null?de:Date.now())-pe)}B.streaming=B.reasoning.status!=="complete",p(B)}else if(Ke==="reason_complete"){let V=(Ft=(rt=Me(R,!1))!=null?rt:Me(R,!0))!=null?Ft:`reason-${l()}`,B=k.get(V);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=Oe((zt=R.completedAt)!=null?zt:R.timestamp);let pe=(Pr=B.reasoning.startedAt)!=null?Pr:Date.now();B.reasoning.durationMs=Math.max(0,((vr=B.reasoning.completedAt)!=null?vr:Date.now())-pe),B.streaming=!1,p(B)}let oe=j(R);oe&&v.byStep.delete(oe)}else if(Ke==="tool_start"){let V=(xt=Y(R,!0))!=null?xt:`tool-${l()}`,B=(It=R.toolName)!=null?It:R.name;if(ye(B)){Z.add(V);continue}let oe=ge(V),pe=(tt=oe.toolCall)!=null?tt:{id:V,status:"pending"};pe.name=B!=null?B:pe.name,pe.status="running",R.args!==void 0?pe.args=R.args:R.parameters!==void 0&&(pe.args=R.parameters),pe.startedAt=(cr=pe.startedAt)!=null?cr:Oe((jt=R.startedAt)!=null?jt:R.timestamp),pe.completedAt=void 0,pe.durationMs=void 0,oe.toolCall=pe,oe.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(oe.agentMetadata={executionId:(Dr=J==null?void 0:J.executionId)!=null?Dr:R.executionId,iteration:(hr=J==null?void 0:J.iteration)!=null?hr:R.iteration}),p(oe)}else if(Ke==="tool_chunk"||Ke==="tool_delta"){let V=(Oo=(Sr=Y(R,!1))!=null?Sr:Y(R,!0))!=null?Oo:`tool-${l()}`;if(Z.has(V))continue;let B=ge(V),oe=(je=B.toolCall)!=null?je:{id:V,status:"running"};oe.startedAt=(io=oe.startedAt)!=null?io:Oe((Tr=R.startedAt)!=null?Tr:R.timestamp);let pe=(At=(lo=(_o=R.text)!=null?_o:R.delta)!=null?lo:R.message)!=null?At:"";pe&&(oe.chunks=(rn=oe.chunks)!=null?rn:[],oe.chunks.push(String(pe))),oe.status="running",B.toolCall=oe,B.streaming=!0;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Jr=B.agentMetadata)!=null?Jr:{executionId:(No=J==null?void 0:J.executionId)!=null?No:R.executionId,iteration:(mn=J==null?void 0:J.iteration)!=null?mn:R.iteration}),p(B)}else if(Ke==="tool_complete"){let V=($r=(Ln=Y(R,!1))!=null?Ln:Y(R,!0))!=null?$r:`tool-${l()}`;if(Z.has(V)){Z.delete(V);continue}let B=ge(V),oe=(Fo=B.toolCall)!=null?Fo:{id:V,status:"running"};oe.status="complete",R.result!==void 0&&(oe.result=R.result),typeof R.duration=="number"&&(oe.duration=R.duration),oe.completedAt=Oe((mt=R.completedAt)!=null?mt:R.timestamp);let pe=(co=R.duration)!=null?co:R.executionTime;if(typeof pe=="number")oe.durationMs=pe;else{let Ve=(po=oe.startedAt)!=null?po:Date.now();oe.durationMs=Math.max(0,((Or=oe.completedAt)!=null?Or:Date.now())-Ve)}B.toolCall=oe,B.streaming=!1;let J=R.agentContext;(J||R.executionId)&&(B.agentMetadata=(Zr=B.agentMetadata)!=null?Zr:{executionId:(Wt=J==null?void 0:J.executionId)!=null?Wt:R.executionId,iteration:(Vr=J==null?void 0:J.iteration)!=null?Vr:R.iteration}),p(B);let Le=ie(R);Le&&E.byCall.delete(Le)}else if(Ke==="step_await"&&R.awaitReason==="local_tool_required"&&R.toolName){let V=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,B=(_r=V!=null?V:R.toolId)!=null?_r:`local-${l()}`,oe=ge(B),pe=R.toolName,J=ga(pe),Le=(uo=oe.toolCall)!=null?uo:{id:B,status:"pending"};Le.name=pe,Le.args=R.parameters,Le.status=J?"running":"complete",Le.chunks=(fo=Le.chunks)!=null?fo:[],Le.startedAt=(mo=Le.startedAt)!=null?mo:Oe((Nr=R.startedAt)!=null?Nr:R.timestamp),J?(Le.completedAt=void 0,Le.duration=void 0,Le.durationMs=void 0):Le.completedAt=($t=Le.completedAt)!=null?$t:Le.startedAt,oe.toolCall=Le,oe.streaming=!1,oe.agentMetadata={...oe.agentMetadata,executionId:(go=R.executionId)!=null?go:(Fr=oe.agentMetadata)==null?void 0:Fr.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},p(oe)}else if(Ke==="text_start"){if((on=R.toolContext)!=null&&on.toolId)continue;let V=R.partId;if(V!==void 0&&T.current!==null&&V!==T.current){let B=m;B&&(B.streaming=!1,p(B),De=B,m=null,M=!0)}V!==void 0&&(T.current=V)}else if(Ke==="text_end"){if((Uo=R.toolContext)!=null&&Uo.toolId)continue;let V=m;V&&(V.streaming=!1,p(V),De=V,m=null,M=!0)}else if(Ke==="step_chunk"||Ke==="step_delta"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((qo=(nn=R.id)!=null?nn:oe.stepId)!=null?qo:`step-${l()}`),yt=R.partId!==void 0&&R.partId!==null?String(R.partId):"",dt=`${oe.toolId}::${Ve}`,Vt=w.get(dt);if(yt!==""&&Vt!==void 0&&Vt!==""&&Vt!==yt){let ht=x.get(H(oe.toolId,Ve,Vt));ht&&ht.streaming!==!1&&(ht.streaming=!1,p(ht))}yt!==""&&w.set(dt,yt);let Jt=P(oe.toolId,Ve,yt,oe.executionId),Rr=(re=(gt=(to=(eo=R.text)!=null?eo:R.delta)!=null?to:R.content)!=null?gt:R.chunk)!=null?re:"";Rr&&(Jt.content+=String(Rr),Jt.streaming=!0,p(Jt)),R.isComplete&&(Jt.streaming=!1,p(Jt));continue}let pe=R.partId;if(pe!==void 0&&T.current!==null&&pe!==T.current){let Ve=m;Ve&&(Ve.streaming=!1,p(Ve),De=Ve,m=null,M=!0)}pe!==void 0&&(T.current=pe);let J=pe!==void 0&&(A=Ye.get(pe))!=null?A:Ae();pe!==void 0&&(J.partId||(J.partId=pe),Ye.set(pe,J));let Le=(at=($=(ue=(_=R.text)!=null?_:R.delta)!=null?ue:R.content)!=null?$:R.chunk)!=null?at:"";if(Le){let Ve=typeof R.seq=="number"?R.seq:void 0,yt=pe!=null?pe:J.id,dt=Ve!==void 0?le(yt,Ve,String(Le)):((ut=Q.get(J.id))!=null?ut:"")+Le;J.rawContent=dt,ae.has(J.id)||ae.set(J.id,this.createStreamParser());let Vt=ae.get(J.id),Jt=dt.trim().startsWith("{")||dt.trim().startsWith("[");if(Jt&&Q.set(J.id,dt),Vt.__isPlainTextParser===!0){J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J);continue}let ht=Vt.processChunk(dt);if(ht instanceof Promise)ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null&&gr.trim()!=="")J.content=gr,p(J);else if(!Jt&&!dt.trim().startsWith("<")){let jr=m,pr=jr&&jr.id===J.id?jr:J;pr.id===J.id&&(pr.content=Ve!==void 0?dt:pr.content+Le,Q.delete(pr.id),ae.delete(pr.id),pr.rawContent=void 0,p(pr))}}).catch(()=>{J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J)});else{let kt=typeof ht=="string"?ht:(U=ht==null?void 0:ht.text)!=null?U:null;kt!==null&&kt.trim()!==""?(J.content=kt,p(J)):!Jt&&!dt.trim().startsWith("<")&&(J.content=Ve!==void 0?dt:J.content+Le,Q.delete(J.id),ae.delete(J.id),J.rawContent=void 0,p(J))}}if(R.isComplete){let Ve=(mr=(nr=R.result)==null?void 0:nr.response)!=null?mr:J.content;if(Ve){let yt=Q.get(J.id),dt=yt!=null?yt:ce(Ve);J.rawContent=dt;let Vt=ae.get(J.id),Jt=null,Rr=!1;if(Vt&&(Jt=Vt.getExtractedText(),Jt===null&&(Jt=xa(dt)),Jt===null)){let ht=Vt.processChunk(dt);ht instanceof Promise?(Rr=!0,ht.then(kt=>{var et;let gr=typeof kt=="string"?kt:(et=kt==null?void 0:kt.text)!=null?et:null;if(gr!==null){let jr=m;jr&&jr.id===J.id&&(jr.content=gr,jr.streaming=!1,ae.delete(jr.id),Q.delete(jr.id),p(jr))}})):Jt=typeof ht=="string"?ht:(Cr=ht==null?void 0:ht.text)!=null?Cr:null}if(!Rr){Jt!==null&&Jt.trim()!==""?J.content=Jt:Q.has(J.id)||(J.content=ce(Ve));let ht=ae.get(J.id);if(ht){let kt=(ko=ht.close)==null?void 0:ko.call(ht);kt instanceof Promise&&kt.catch(()=>{}),ae.delete(J.id)}Q.delete(J.id),J.streaming=!1,p(J)}}}}else if(Ke==="step_complete"){let V=R.stepType,B=R.executionType;if(V==="tool"||B==="context")continue;let oe=R.toolContext;if(oe!=null&&oe.toolId){let Ve=String((Ko=(sr=R.id)!=null?sr:oe.stepId)!=null?Ko:"");if(Ve){let yt=I(oe.toolId,Ve);for(let[dt,Vt]of x)dt.startsWith(yt)&&Vt.streaming!==!1&&(Vt.streaming=!1,p(Vt));w.delete(`${oe.toolId}::${Ve}`)}continue}let pe=R.stopReason;if(M){if(m!==null){let dt=m;pe&&(dt.stopReason=pe),ae.delete(dt.id),Q.delete(dt.id),dt.streaming!==!1&&(dt.streaming=!1,p(dt))}let Ve=(us=R.result)==null?void 0:us.response,yt=De;yt&&(pe&&(yt.stopReason=pe),Ve!=null?nt(yt,Ve):(ae.delete(yt.id),Q.delete(yt.id))),De=null;continue}let J=(Eo=R.result)==null?void 0:Eo.response,Le=Ae();if(pe&&(Le.stopReason=pe),J!=null){let Ve=ae.get(Le.id),yt=!1,dt=!1;if(Ve){let Vt=Ve.getExtractedText(),Jt=Q.get(Le.id),Rr=Jt!=null?Jt:ce(J);if(Le.rawContent=Rr,Vt!==null&&Vt.trim()!=="")Le.content=Vt,yt=!0;else{let ht=xa(Rr);if(ht!==null)Le.content=ht,yt=!0;else{let kt=Ve.processChunk(Rr);if(kt instanceof Promise)dt=!0,kt.then(gr=>{var jr;let et=typeof gr=="string"?gr:(jr=gr==null?void 0:gr.text)!=null?jr:null;if(et!==null&&et.trim()!==""){let pr=m;pr&&pr.id===Le.id&&(pr.content=et,pr.streaming=!1,ae.delete(pr.id),Q.delete(pr.id),p(pr))}else{let pr=Ve.getExtractedText(),Ur=m;Ur&&Ur.id===Le.id&&(pr!==null&&pr.trim()!==""?Ur.content=pr:Q.has(Ur.id)||(Ur.content=ce(J)),Ur.streaming=!1,ae.delete(Ur.id),Q.delete(Ur.id),p(Ur))}});else{let gr=typeof kt=="string"?kt:(Lo=kt==null?void 0:kt.text)!=null?Lo:null;if(gr!==null&&gr.trim()!=="")Le.content=gr,yt=!0;else{let et=Ve.getExtractedText();et!==null&&et.trim()!==""&&(Le.content=et,yt=!0)}}}}}if(!dt){if(!Le.rawContent){let Vt=Q.get(Le.id);Le.rawContent=Vt!=null?Vt:ce(J)}if(!yt&&!Q.has(Le.id)&&(Le.content=ce(J)),Ve){let Vt=(Xo=Ve.close)==null?void 0:Xo.call(Ve);Vt instanceof Promise&&Vt.catch(()=>{})}ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}}else ae.delete(Le.id),Q.delete(Le.id),Le.streaming=!1,p(Le)}else if(Ke==="flow_complete"){let V=(Qo=R.result)==null?void 0:Qo.response;if(M){if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}}else if(V!=null){let B=Ae(),oe=Q.get(B.id),pe=oe!=null?oe:ce(V);B.rawContent=pe;let J=ce(V),Le=ae.get(B.id);if(Le){let dt=xa(pe);if(dt!==null)J=dt;else{let Vt=Le.processChunk(pe);Vt instanceof Promise&&Vt.then(Rr=>{var kt;let ht=typeof Rr=="string"?Rr:(kt=Rr==null?void 0:Rr.text)!=null?kt:null;ht!==null&&(B.content=ht,B.streaming=!1,p(B))});let Jt=Le.getExtractedText();Jt!==null&&(J=Jt)}}ae.delete(B.id),Q.delete(B.id);let Ve=J!==B.content,yt=B.streaming!==!1;Ve&&(B.content=J),B.streaming=!1,(Ve||yt)&&p(B)}else if(m!==null){let B=m;ae.delete(B.id),Q.delete(B.id),B.streaming!==!1&&(B.streaming=!1,p(B))}t({type:"status",status:"idle"})}else if(Ke==="agent_start")te={executionId:R.executionId,agentId:(Qn=R.agentId)!=null?Qn:"virtual",agentName:(gn=R.agentName)!=null?gn:"",status:"running",currentIteration:0,maxTurns:(ro=R.maxTurns)!=null?ro:1,startedAt:Oe(R.startedAt)};else if(Ke==="agent_iteration_start"){if(te&&(te.currentIteration=R.iteration),Ar==="separate"&&R.iteration>1){let V=m;V&&(V.streaming=!1,p(V),_e.set(R.iteration-1,V),m=null)}}else if(Ke==="agent_turn_start")y=null;else if(Ke==="agent_turn_delta"){if(R.contentType==="text"){let V=Ae();V.content+=(an=R.delta)!=null?an:"",V.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId,agentName:te==null?void 0:te.agentName},y=V,p(V)}else if(R.contentType==="thinking"){let V=(Pa=R.turnId)!=null?Pa:`agent-think-${R.iteration}`,B=Ue(V);B.reasoning=(Yn=B.reasoning)!=null?Yn:{id:V,status:"streaming",chunks:[]},B.reasoning.chunks.push((Ra=R.delta)!=null?Ra:""),B.agentMetadata={executionId:R.executionId,iteration:R.iteration,turnId:R.turnId},p(B)}else if(R.contentType==="tool_input"){let V=(bi=R.toolCallId)!=null?bi:E.lastId;if(V){let B=L.get(V);B!=null&&B.toolCall&&(B.toolCall.chunks=(Ia=B.toolCall.chunks)!=null?Ia:[],B.toolCall.chunks.push((vi=R.delta)!=null?vi:""),p(B))}}}else if(Ke==="agent_turn_complete"){let V=R.turnId;if(V){let pe=k.get(V);if(pe!=null&&pe.reasoning){pe.reasoning.status="complete",pe.reasoning.completedAt=Oe(R.completedAt);let J=(Ha=pe.reasoning.startedAt)!=null?Ha:Date.now();pe.reasoning.durationMs=Math.max(0,((Lt=pe.reasoning.completedAt)!=null?Lt:Date.now())-J),pe.streaming=!1,p(pe)}}let B=R.stopReason,oe=m!=null?m:y;if(B&&oe!==null){let pe=R.turnId;(!pe||((fs=oe.agentMetadata)==null?void 0:fs.turnId)===pe)&&(oe.stopReason=B,p(oe))}}else if(Ke==="agent_tool_start"){m&&(m.streaming=!1,p(m),m=null);let V=(zo=R.toolCallId)!=null?zo:`agent-tool-${l()}`;Be(ie(R),V);let B=ge(V),oe=(So=B.toolCall)!=null?So:{id:V,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};oe.name=(wi=(Ci=R.toolName)!=null?Ci:R.name)!=null?wi:oe.name,oe.status="running",R.parameters!==void 0&&(oe.args=R.parameters),oe.startedAt=Oe((Wa=R.startedAt)!=null?Wa:R.timestamp),B.toolCall=oe,B.streaming=!0,B.agentMetadata={executionId:R.executionId,iteration:R.iteration},p(B)}else if(Ke==="agent_tool_delta"){let V=(hn=R.toolCallId)!=null?hn:E.lastId;if(V){let B=(ms=L.get(V))!=null?ms:ge(V);B.toolCall&&(B.toolCall.chunks=(Pn=B.toolCall.chunks)!=null?Pn:[],B.toolCall.chunks.push((gs=R.delta)!=null?gs:""),B.toolCall.status="running",B.streaming=!0,p(B))}}else if(Ke==="agent_tool_complete"){let V=(hs=R.toolCallId)!=null?hs:E.lastId;if(V){let B=(xs=L.get(V))!=null?xs:ge(V);if(B.toolCall){B.toolCall.status="complete",R.result!==void 0&&(B.toolCall.result=R.result),typeof R.executionTime=="number"&&(B.toolCall.durationMs=R.executionTime),B.toolCall.completedAt=Oe((ys=R.completedAt)!=null?ys:R.timestamp),B.streaming=!1,p(B);let oe=ie(R);oe&&E.byCall.delete(oe)}}}else if(Ke==="agent_media"){let V=Array.isArray(R.media)?R.media:[],B=[];for(let oe of V){if(!oe||typeof oe!="object")continue;let pe=oe,J=typeof pe.type=="string"?pe.type:void 0,Le=typeof pe.mediaType=="string"?pe.mediaType.toLowerCase():"",Ve=null,yt="";if(J==="media"){let dt=typeof pe.data=="string"?pe.data:void 0;if(!dt)continue;yt=Le.length>0?Le:"application/octet-stream",Ve=`data:${yt};base64,${dt}`}else if(J==="image-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else if(J==="file-url"){let dt=typeof pe.url=="string"?pe.url:void 0;if(!dt)continue;yt=Le,Ve=dt}else continue;if(Ve)if(J==="image-url"||yt.startsWith("image/"))B.push({type:"image",image:Ve,...yt?{mimeType:yt}:{}});else if(yt.startsWith("audio/"))B.push({type:"audio",audio:Ve,mimeType:yt});else if(yt.startsWith("video/"))B.push({type:"video",video:Ve,mimeType:yt});else{let dt=yt||"application/octet-stream";B.push({type:"file",data:Ve,mimeType:dt,filename:xv(dt)})}}if(B.length>0){let oe=l(),pe=R.toolCallId,Le={id:`agent-media-${typeof pe=="string"&&pe.length>0?`${pe}-${oe}`:String(oe)}`,role:"assistant",content:"",contentParts:B,createdAt:new Date().toISOString(),streaming:!1,sequence:oe,agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(Le);let Ve=m;Ve&&(Ve.streaming=!1,p(Ve)),m=null,h.current=null}}else if(Ke!=="agent_iteration_complete"){if(Ke==="agent_reflection"||Ke==="agent_reflect"){let V=`agent-reflection-${R.executionId}-${R.iteration}`,B={id:V,role:"assistant",content:(To=R.reflection)!=null?To:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:V,status:"complete",chunks:[(Ba=R.reflection)!=null?Ba:""]},agentMetadata:{executionId:R.executionId,iteration:R.iteration}};p(B)}else if(Ke==="agent_complete"){te&&(te.status=R.success?"complete":"error",te.completedAt=Oe(R.completedAt),te.stopReason=R.stopReason);let V=m;V&&(V.streaming=!1,p(V)),t({type:"status",status:"idle"})}else if(Ke==="agent_error"){let V=typeof R.error=="string"?R.error:(ln=(sn=R.error)==null?void 0:sn.message)!=null?ln:"Agent execution error";R.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",V):t({type:"error",error:new Error(V)})}else if(Ke!=="agent_ping"){if(Ke==="agent_approval_start"){let V=(bs=R.approvalId)!=null?bs:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Ai=te==null?void 0:te.agentId)!=null?Ai:"virtual",executionId:(Cs=(vs=R.executionId)!=null?vs:te==null?void 0:te.executionId)!=null?Cs:"",toolName:(Jn=R.toolName)!=null?Jn:"",toolType:R.toolType,description:(Ti=R.description)!=null?Ti:`Execute ${(Si=R.toolName)!=null?Si:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="step_await"&&R.awaitReason==="approval_required"){let V=(Mi=R.approvalId)!=null?Mi:`approval-${l()}`,B={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(ki=te==null?void 0:te.agentId)!=null?ki:"virtual",executionId:(Zn=(dd=R.executionId)!=null?dd:te==null?void 0:te.executionId)!=null?Zn:"",toolName:(Rn=R.toolName)!=null?Rn:"",toolType:R.toolType,description:(ws=R.description)!=null?ws:`Execute ${(Ei=R.toolName)!=null?Ei:"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters}};p(B)}else if(Ke==="agent_approval_complete"){let V=R.approvalId;if(V){let oe={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(In=R.decision)!=null?In:"approved",agentId:(Li=te==null?void 0:te.agentId)!=null?Li:"virtual",executionId:(Hn=(As=R.executionId)!=null?As:te==null?void 0:te.executionId)!=null?Hn:"",toolName:(Ss=R.toolName)!=null?Ss:"",description:(Pi=R.description)!=null?Pi:"",resolvedAt:Date.now()}};p(oe)}}else if(Ke==="artifact_start"||Ke==="artifact_delta"||Ke==="artifact_update"||Ke==="artifact_complete"){if(Ke==="artifact_start"){let V=R.artifactType,B=String(R.id),oe=typeof R.title=="string"?R.title:void 0;if(t({type:"artifact_start",id:B,artifactType:V,title:oe,component:typeof R.component=="string"?R.component:void 0}),be.set(B,{markdown:"",title:oe}),!me.has(B)){me.add(B);let pe={id:`artifact-ref-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:B,title:oe,artifactType:V,status:"streaming"}})};ne.set(B,pe),p(pe)}}else if(Ke==="artifact_delta"){let V=String(R.id),B=typeof R.delta=="string"?R.delta:String((xn=R.delta)!=null?xn:"");t({type:"artifact_delta",id:V,artDelta:B});let oe=be.get(V);oe&&(oe.markdown+=B)}else if(Ke==="artifact_update"){let V=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};t({type:"artifact_update",id:String(R.id),props:V,component:typeof R.component=="string"?R.component:void 0})}else if(Ke==="artifact_complete"){let V=String(R.id);t({type:"artifact_complete",id:V});let B=ne.get(V);if(B){B.streaming=!1;try{let oe=JSON.parse((Ri=B.rawContent)!=null?Ri:"{}");if(oe.props){oe.props.status="complete";let pe=be.get(V);pe!=null&&pe.markdown&&(oe.props.markdown=pe.markdown)}B.rawContent=JSON.stringify(oe)}catch{}be.delete(V),p(B),ne.delete(V)}}}else if(Ke==="transcript_insert"){let V=R.message;if(!V||typeof V!="object")continue;let B=String((Wn=V.id)!=null?Wn:`msg-${l()}`),oe=V.role,J={id:B,role:oe==="user"?"user":oe==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:l()};if(p(J),J.rawContent)try{let Le=JSON.parse(J.rawContent),Ve=(Gt=Le==null?void 0:Le.props)==null?void 0:Gt.artifactId;typeof Ve=="string"&&me.add(Ve)}catch{}m=null,h.current=null,ae.delete(B),Q.delete(B)}else if(Ke==="error"||Ke==="step_error"||Ke==="dispatch_error"||Ke==="flow_error"){let V=null;if(R.error instanceof Error)V=R.error;else if(Ke==="dispatch_error"){let B=(Da=R.message)!=null?Da:R.error;B!=null&&B!==""&&(V=new Error(String(B)))}else if(Ke==="step_error"||Ke==="flow_error"){let B=R.error;typeof B=="string"&&B!==""?V=new Error(B):B!=null&&typeof B=="object"&&"message"in B&&(V=new Error(String((Oa=B.message)!=null?Oa:B)))}else Ke==="error"&&R.error!=null&&R.error!==""&&(V=new Error(String(R.error)));if(V){t({type:"error",error:V});let B=m;B&&B.streaming&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}}}}}Re.length=0};;){let{done:O,value:fe}=await n.read();if(O)break;s+=a.decode(fe,{stream:!0});let Ie=s.split(`
|
|
58
58
|
|
|
59
59
|
`);s=(dr=Ie.pop())!=null?dr:"";for(let Je of Ie){let qe=Je.split(`
|
|
60
60
|
`),ze="message",lt="";for(let or of qe)or.startsWith("event:")?ze=or.replace("event:","").trim():or.startsWith("data:")&&(lt+=or.replace("data:","").trim());if(!lt)continue;let Mt;try{Mt=JSON.parse(lt)}catch(or){t({type:"error",error:or instanceof Error?or:new Error("Failed to parse chat stream payload")});continue}let Dt=ze!=="message"?ze:(Yr=Mt.type)!=null?Yr:"message";if((zr=this.onSSEEvent)==null||zr.call(this,Dt,Mt),this.parseSSEEvent){h.current=m;let or=await this.handleCustomSSEEvent(Mt,t,h,p,l,T);if(h.current&&h.current!==m&&(m=h.current),or)continue}Pt.push(Dt,Mt),he()}}Pt.flushPending(),he(),Pt.destroy()}};function tx(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`msg_${r}_${e}`}function Ja(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${r}_${e}`}function ba(){let r=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${r}_${e}`}var ll="[Image]";function rx(r){return typeof r=="string"?[{type:"text",text:r}]:r}function ox(r){return typeof r=="string"?r:r.filter(e=>e.type==="text").map(e=>e.text).join("")}function nx(r){return typeof r=="string"?!1:r.some(e=>e.type==="image")}function ax(r){return typeof r=="string"?[]:r.filter(e=>e.type==="image")}function Qs(r){return{type:"text",text:r}}function sx(r,e){return{type:"image",image:r,...(e==null?void 0:e.mimeType)&&{mimeType:e.mimeType},...(e==null?void 0:e.alt)&&{alt:e.alt}}}async function ix(r){return new Promise((e,t)=>{let o=new FileReader;o.onload=()=>{let n=o.result;e({type:"image",image:n,mimeType:r.type,alt:r.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(r)})}function lx(r,e=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${e.join(", ")}`}}var dx=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vv=["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"],Tn=[...dx,...vv];function Cv(r){return dx.includes(r)||r.startsWith("image/")}function dl(r){return Cv(r.type)}async function cx(r){return new Promise((e,t)=>{let o=new FileReader;o.onload=()=>{let n=o.result;dl(r)?e({type:"image",image:n,mimeType:r.type,alt:r.name}):e({type:"file",data:n,mimeType:r.type,filename:r.name})},o.onerror=()=>t(new Error("Failed to read file")),o.readAsDataURL(r)})}function px(r,e=Tn,t=10*1024*1024){return e.includes(r.type)?r.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${r.type}". Accepted types: ${e.join(", ")}`}}function wv(r){let e=r.split(".");return e.length>1?e.pop().toLowerCase():""}function ux(r,e){let t=wv(e).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"}[r]||t||"FILE"}var cl=class{constructor(e=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=e}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let o=t.AudioContext||t.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let d=new Uint8Array(this.remainder.length+e.length);d.set(this.remainder),d.set(e,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let o=this.ensureContext(),n=this.pcmToFloat32(t),a=o.createBuffer(1,n.length,this.sampleRate);a.getChannelData(0).set(n);let s=o.createBufferSource();s.buffer=a,s.connect(o.destination);let i=o.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),s.start(this.nextStartTime),this.nextStartTime+=a.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,s.onended=()=>{let d=this.activeSources.indexOf(s);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),o=new Float32Array(t),n=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let a=0;a<t;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var pl=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(e,t,o,n,a){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=e.createMediaStreamSource(t),this.analyserNode=e.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let s=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(s);let i=0;for(let u=0;u<s.length;u++)i+=s[u]*s[u];let d=Math.sqrt(i/s.length);(o==="silence"?d<n.threshold:d>=n.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=n.duration&&(this.fired=!0,a()):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 Ys=class{constructor(e){this.config=e;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 pl;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(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var e,t,o;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let n=this.w;if(!n||!n.location)throw new Error("Window object or location not available");let a=n.location.protocol==="https:"?"wss:":"ws:",s=(e=this.config)==null?void 0:e.host,i=(t=this.config)==null?void 0:t.agentId,d=(o=this.config)==null?void 0:o.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!s)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${a}//${s}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let u=`${a}//${s}/ws/agents/${i}/voice?token=...`,f=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((p,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let y=!1,h=M=>{y||(y=!0,clearTimeout(T),m(new Error(M)))},T=setTimeout(()=>h("WebSocket connection timed out."+f),1e4);this.ws.addEventListener("open",()=>{y||(y=!0,clearTimeout(T),p())},{once:!0}),this.ws.addEventListener("error",()=>{h("WebSocket connection failed to "+u+"."+f)},{once:!0}),this.ws.addEventListener("close",M=>{if(!M.wasClean&&!y){let k=M.code!==1006?` (code ${M.code})`:"";h("WebSocket connection failed"+k+"."+f)}},{once:!0})}),this.sendHeartbeat()}catch(n){throw this.ws=null,this.errorCallbacks.forEach(a=>a(n)),this.statusCallbacks.forEach(a=>a("error")),n}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(e=>e("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(e=>e("disconnected"))},this.ws.onerror=e=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=e=>{if(e.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(e.data));return}try{let t=JSON.parse(e.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(o=>o(new Error("Message parsing failed")))}})}handleWebSocketMessage(e){var t,o;switch(e.type){case"session_config":e.interruptionMode&&(this.interruptionMode=e.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(n=>n({text:e.response.agentResponseText||e.response.transcript,transcript:e.response.transcript,audio:e.response.audio,confidence:.95,provider:"runtype"})),(t=e.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.playAudio(e.response.audio).catch(n=>this.errorCallbacks.forEach(a=>a(n instanceof Error?n:new Error(String(n)))))):(o=e.response.audio)!=null&&o.base64;break;case"audio_end":if(e.requestId&&e.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(n=>n("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(n=>n(new Error(e.error))),this.statusCallbacks.forEach(n=>n("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(e){e.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new cl(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(e))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(e=>e("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 e,t,o,n;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 a=this.w;this.audioContext||(this.audioContext=new(a.AudioContext||a.webkitAudioContext));let s=this.audioContext,i=(t=(e=this.config)==null?void 0:e.pauseDuration)!=null?t:2e3,d=(n=(o=this.config)==null?void 0:o.silenceThreshold)!=null?n:.01;this.vad.start(s,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(p=>p("processing")),this.processingStartCallbacks.forEach(p=>p());let u=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",f=new Blob(this.audioChunks,{type:u});await this.sendAudio(f),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(a){throw this.errorCallbacks.forEach(s=>s(a)),this.statusCallbacks.forEach(s=>s("error")),a}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(e=>e.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(e=>e("idle"))}async startBargeInMonitoring(){var a,s;if(this.interruptionMode!=="barge-in")return;let e=this.w;if(!this.mediaStream&&e&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&e&&(this.audioContext=new(e.AudioContext||e.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,o=(s=(a=this.config)==null?void 0:a.silenceThreshold)!=null?s:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:o,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(e=>{this.errorCallbacks.forEach(t=>t(e instanceof Error?e:new Error(String(e))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(e){var t;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(e),n=this.getFormatFromMimeType(e.type),a=this.generateRequestId();this.currentRequestId=a,this.ws.send(JSON.stringify({type:"audio_input",audio:o,format:n,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:a}))}catch(o){this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error"))}}getFormatFromMimeType(e){return e.includes("wav")?"wav":e.includes("mpeg")||e.includes("mp3")?"mp3":"webm"}blobToBase64(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let s=n.result.split(",")[1];t(s)},n.onerror=o,n.readAsDataURL(e)})}async playAudio(e){if(!e.base64)return;let t=atob(e.base64),o=new Uint8Array(t.length);for(let l=0;l<t.length;l++)o[l]=t.charCodeAt(l);let n=e.format||"mp3",a=n==="mp3"?"audio/mpeg":`audio/${n}`,s=new Blob([o],{type:a}),i=URL.createObjectURL(s),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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onProcessingStart(e){this.processingStartCallbacks.push(e)}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(e=>e.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(e=>e("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var va=class{constructor(e={}){this.config=e;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(e=>e("connected"))}async startListening(){var e,t;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=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(d=>d[0]).map(d=>d.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ca(r){switch(r.type){case"runtype":if(!r.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(r.runtype);case"browser":if(!va.isSupported())throw new Error("Browser speech recognition not supported");return new va(r.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${r.type}`)}}function ul(r){if((r==null?void 0:r.type)==="runtype"&&r.runtype)return Ca({type:"runtype",runtype:r.runtype});if(va.isSupported())return Ca({type:"browser",browser:(r==null?void 0:r.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Js(r){try{return ul(r),!0}catch{return!1}}var Av=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Sv(r,e){return Av.some(t=>r[t]!==e[t])}function fx(r,e){let t=r instanceof Error?r:new Error(String(r));if(typeof e=="string")return e;if(typeof e=="function")return e(t);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 t.message?`${o}
|
|
@@ -168,7 +168,7 @@ ${s.join(`
|
|
|
168
168
|
${s.join(`
|
|
169
169
|
`)}`)}return o.join(`
|
|
170
170
|
|
|
171
|
-
`)}var Wy="3.34.
|
|
171
|
+
`)}var Wy="3.34.1";var By=Wy;function Dy(){return{name:"@persona/accessibility",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,interactive:{...r.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Oy(){return{name:"@persona/animations",version:"1.0.0",transform(r){return{...r,palette:{...r.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function _y(r){return{name:"@persona/brand",version:"1.0.0",transform(e){var o;let t={...e.palette};return(o=r.colors)!=null&&o.primary&&(t.colors={...t.colors,primary:{50:fn(r.colors.primary,.95),100:fn(r.colors.primary,.9),200:fn(r.colors.primary,.8),300:fn(r.colors.primary,.7),400:fn(r.colors.primary,.6),500:r.colors.primary,600:fn(r.colors.primary,.8),700:fn(r.colors.primary,.7),800:fn(r.colors.primary,.6),900:fn(r.colors.primary,.5),950:fn(r.colors.primary,.45)}}),{...e,palette:t}}}}function Ny(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(r){return{...r,palette:{...r.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(r){return{...r,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Fy(){return{name:"@persona/high-contrast",version:"1.0.0",transform(r){return{...r,semantic:{...r.semantic,colors:{...r.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function fn(r,e){let t=parseInt(r.slice(1,3),16),o=parseInt(r.slice(3,5),16),n=parseInt(r.slice(5,7),16),a=Math.round(t+(255-t)*(1-e)),s=Math.round(o+(255-o)*(1-e)),i=Math.round(n+(255-n)*(1-e));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Uy(r){return{name:r.name,version:r.version,transform:r.transform||(e=>e),cssVariables:r.cssVariables,afterResolve:r.afterResolve}}var Pw={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},qy={components:{panel:{borderRadius:"0",shadow:"none"}}},Mu={id:"shop",label:"Shopping Assistant",config:{theme:Pw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Wo},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},ku={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:qy}},Eu={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:qy}},Lu={shop:Mu,minimal:ku,fullscreen:Eu};function zy(r){return Lu[r]}var Rw=`
|
|
172
172
|
@keyframes persona-stream-wipe {
|
|
173
173
|
from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
|
|
174
174
|
to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
|