@runtypelabs/persona 4.3.0 → 4.3.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/README.md +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/theme-editor-preview.cjs +1 -1
- package/dist/theme-editor-preview.js +1 -1
- package/dist/widget.css +3 -0
- package/package.json +1 -1
- package/src/styles/widget.css +3 -0
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
|
|
|
8
8
|
${e.description}`:"");return window.confirm(n)},Xf=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Qf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Yf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zf="agent_",eh="flow_";function Nu(e){return e.startsWith(Zf)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Ou(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=Nu(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Nu(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as th,ARR as nh,OBJ as rh,STR as oh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Tt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},qs=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",zs=8,ms="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",_u="Type your own answer here",$u="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,$i="data-ask-current-index",ji="data-ask-question-count",ju="data-ask-answers",Ui="data-ask-grouped",Uu="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",mh=e=>e.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,qu=e=>e.replace(/["\\]/g,"\\$&"),po=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,Ia=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},uo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=th(o,oh|rh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!Fu&&(Fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},gh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},fh=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},zu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Vu=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},hh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Vu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},bh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<ph;f++)s.appendChild(yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(hh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?sh:ah;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:_u,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=Vu(r,a,d.length);T&&v.appendChild(T),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Ku=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:_u,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:$u,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:lh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:dh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ch:(g=n.nextLabel)!=null?g:ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let t=e.getAttribute(ju);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gu=(e,t)=>{e.setAttribute(ju,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute($i,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ui)==="true",Ch=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Ah=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ra=(e,t)=>{let{payload:n}=uo(t),r=Vs(n),o=Fo(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ju=e=>{let t=Fo(e),n=or(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Xu=e=>{if(!mo(e))return;let t=Fo(e),n=or(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(e,t,n)=>{let r=Ia(n),o=mh(e),{payload:s,complete:a}=uo(t),i=mo(e),d=or(e),l=gs(e),p=i?fh(s,d):gh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=bh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ku(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(xh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=vh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Ju(e),Xu(e)},Sh=(e,t,n)=>{let r=Ia(t),o=uh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=Ch(e,a),p=d?Ah(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ms,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(ji,String(i)),u.setAttribute($i,String(p)),u.setAttribute(Ui,d?"true":"false"),u.setAttribute(Uu,o),Gu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),zu(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(Ku(r,o)),qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:r}=uo(t),o=Math.max(1,Vs(r).length);o>gs(e)&&(e.setAttribute(ji,String(o)),o>1&&!mo(e)&&e.setAttribute(Ui,"true")),qi(e,t,n)},Eh=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ia(t);zu(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=uo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!po(e)||Ia(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==o&&l.remove()});let a=n.querySelector(`[${ms}="${qu(o)}"]`);if(a){Th(a,e,t);return}let{payload:i}=uo(e),d=Sh(e,t,i);n.appendChild(d)},_o=(e,t)=>{if(!e)return;let n=t?`[${ms}="${qu(t)}"]`:`[${ms}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},zi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),go=(e,t)=>{let n=Fo(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Gu(e,n),Ju(e),Xu(e)},Wa=(e,t,n,r)=>{let o=gs(e),s=Math.max(0,Math.min(o-1,r));wh(e,s),qi(e,t,n)};var Hr="suggest_replies";var Qu={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Vi={name:Hr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ha=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Yu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Gi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ha(r))continue;let o=Yu((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Zu=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var em={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},tm={name:Pa,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:em,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(tm),Zu(e)&&t.push(Vi),t};import{parse as nm,STR as rm,OBJ as om}from"partial-json";var Da=e=>e.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Mh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},sm=e=>e.status==="complete"?Mh(e):e.status==="pending"?"Waiting":"",kh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var am=e=>e.status==="complete"?kh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Oa=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Ji=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Gs(r,n.slice(s,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Gs(r,n.slice(s),[]),r},Gs=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Lh=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Yi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var im="4.3.0";var hr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":hr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new js(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Ou(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,Qt,Dr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Ee=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Be=A.tools?A.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Ee,tools:Be}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Ee=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Ee||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Ee,Be,Le,De;return W((De=(Le=(Be=(Ee=(te=A.stepId)!=null?te:A.step_id)!=null?Ee:A.step)!=null?Be:A.parentId)!=null?Le:A.flowStepId)!=null?De:A.flow_step_id)},N=A=>{var te,Ee,Be,Le,De,Ge,it;return W((it=(Ge=(De=(Le=(Be=(Ee=(te=A.callId)!=null?te:A.call_id)!=null?Ee:A.requestId)!=null?Be:A.request_id)!=null?Le:A.toolCallId)!=null?De:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Z=r,Te=!1,pe=()=>{if(f)return f;let A,te=T;return!Te&&Z?(A=Z,Te=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},xe=(A,te)=>{var De;let Ee=(De=A.reasoningId)!=null?De:A.id,Be=O(A);if(Ee){let Ge=String(Ee);return ee(Be,Ge),Ge}if(Be){let Ge=F.byStep.get(Be);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Le=`reason-${l()}`;return ee(Be,Le),Le},Me=A=>{let te=C.get(A);if(te)return te;let Ee={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Ee),g(Ee),Ee},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},be=new Set,de=new Map,ae=new Set,se=new Map,We=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Oe=(A,te)=>{var De;let Ee=(De=A.toolId)!=null?De:A.id,Be=N(A);if(Ee){let Ge=String(Ee);return oe(Be,Ge),Ge}if(Be){let Ge=j.byCall.get(Be);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Le=`tool-${l()}`;return oe(Be,Le),Le},V=A=>{let te=R.get(A);if(te)return te;let Ee={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Ee),g(Ee),Ee},K=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Ee=Date.parse(A);if(!Number.isNaN(Ee))return Ee}return Date.now()},ve=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},J=new Map,ce=new Map,Re=new Map,ge=(A,te,Ee)=>{var it;let Be=Re.get(A);Be||(Be=[],Re.set(A,Be));let Le=0,De=Be.length;for(;Le<De;){let Pt=Le+De>>>1;Be[Pt].seq<te?Le=Pt+1:De=Pt}((it=Be[Le])==null?void 0:it.seq)===te?Be[Le]={seq:te,text:Ee}:Be.splice(Le,0,{seq:te,text:Ee});let Ge="";for(let Pt=0;Pt<Be.length;Pt++)Ge+=Be[Pt].text;return Ge},Ke=(A,te)=>{let Ee=ve(te),Be=ce.get(A.id),Le=Bh(Be,Ee);A.rawContent=Le;let De=J.get(A.id),Ge=Q=>{var lt;let Se=(lt=A.content)!=null?lt:"";Q.trim()!==""&&(Se.trim().length===0||Q.startsWith(Se)||Q.trimStart().startsWith(Se.trim()))&&(A.content=Q)},it=()=>{var Q;if(De){let Se=(Q=De.close)==null?void 0:Q.call(De);Se instanceof Promise&&Se.catch(()=>{})}J.delete(A.id),ce.delete(A.id),A.streaming=!1,g(A)};if(!De){Ge(Ee),it();return}let Pt=Xs(Le);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),it();return}let bt=Q=>{var Qe;let Se=typeof Q=="string"?Q:(Qe=Q==null?void 0:Q.text)!=null?Qe:null;if(Se!==null&&Se.trim()!=="")return Se;let lt=De.getExtractedText();return lt!==null&<.trim()!==""?lt:Ee},H;try{H=De.processChunk(Le)}catch{Ge(Ee),it();return}if(H instanceof Promise){H.then(Q=>{Ge(bt(Q)),it()}).catch(()=>{Ge(Ee),it()});return}Ge(bt(H)),it()},tt=null,Lt=(A,te,Ee,Be)=>{var Pt;A.rawContent=te,J.has(A.id)||J.set(A.id,this.createStreamParser());let Le=J.get(A.id),De=te.trim().startsWith("{")||te.trim().startsWith("[");if(De&&ce.set(A.id,te),Le.__isPlainTextParser===!0){A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A);return}let it=Le.processChunk(te);if(it instanceof Promise)it.then(bt=>{var Q;let H=typeof bt=="string"?bt:(Q=bt==null?void 0:bt.text)!=null?Q:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof it=="string"?it:(Pt=it==null?void 0:it.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Ee=te!=null?te:A.content;if(Ee==null||Ee===""){A.streaming=!1,g(A);return}let Be=ce.get(A.id),Le=Be!=null?Be:ve(Ee);A.rawContent=Le;let De=J.get(A.id),Ge=null,it=!1;if(De&&(Ge=De.getExtractedText(),Ge===null&&(Ge=Xs(Le)),Ge===null)){let H=De.processChunk(Le);H instanceof Promise?(it=!0,H.then(Q=>{var lt;let Se=typeof Q=="string"?Q:(lt=Q==null?void 0:Q.text)!=null?lt:null;Se!==null&&(A.content=Se,A.streaming=!1,J.delete(A.id),ce.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:ce.has(A.id)||(A.content=ve(Ee));let H=J.get(A.id);if(H){let Q=(bt=H.close)==null?void 0:bt.call(H);Q instanceof Promise&&Q.catch(()=>{}),J.delete(A.id)}ce.delete(A.id),A.streaming=!1,g(A)}},_e=(A,te,Ee)=>{let Be=M.get(A);if(Be)return Be;let Le={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Le),g(Le),Le},G=[],ze,qe=new Map,we=0,Ae="agent",nt=!1,Ft=null,ne=null,$e=new Map,hn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ze=()=>{var A,te,Ee,Be,Le,De,Ge,it,Pt,bt,H,Q,Se,lt,Qe,jt,yn,xt,vt,It,wt,dn,_t,Nn,Sn,Tn,xn,En,lr,Ct,xr,vr,Nr,cr,ut,Co,wr,Ao,Rn,Xo,Qr,Or,Yr,Zr,So,To,eo,yt,On,Fn,Mn,At,Xn,Qn,_n,to,Fr,no,$n,Rt,kn,Yn,ro,_r,oo,he,Wn,Cr,mt,rn,on,Ar,ks,$r,Eo,Sr,$,Qo,Tr,Er,jr,Mr,dr,Yo,xa,jn,Un,pr,ur,Mo,Ur,vn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,Hn,Ca;for(let rs=0;rs<G.length;rs++){let et=G[rs].payloadType,w=G[rs].payload;if(!nt&&Ae!=="flow"&&typeof w.stepType=="string"&&(Ae="flow"),et==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),_e(z,U,"reasoning");continue}let X=(A=xe(w,!0))!=null?A:`reason-${l()}`,fe=Me(X);fe.reasoning=(te=fe.reasoning)!=null?te:{id:X,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:K((Ee=w.startedAt)!=null?Ee:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(et==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let Fe=M.get(z),gt=(Ge=(De=(Le=w.reasoningText)!=null?Le:w.text)!=null?De:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let U=(Pt=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?Pt:`reason-${l()}`,X=Me(U);X.reasoning=(bt=X.reasoning)!=null?bt:{id:U,status:"streaming",chunks:[]},X.reasoning.startedAt=(Q=X.reasoning.startedAt)!=null?Q:K((H=w.startedAt)!=null?H:w.timestamp);let fe=(Qe=(lt=(Se=w.reasoningText)!=null?Se:w.text)!=null?lt:w.delta)!=null?Qe:"";if(fe&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let gt=ge(U,Fe,String(fe));X.reasoning.chunks=[gt]}else X.reasoning.chunks.push(String(fe))}if(X.reasoning.status=w.done?"complete":"streaming",w.done){X.reasoning.completedAt=K((jt=w.completedAt)!=null?jt:w.timestamp);let Fe=(yn=X.reasoning.startedAt)!=null?yn:Date.now();X.reasoning.durationMs=Math.max(0,((xt=X.reasoning.completedAt)!=null?xt:Date.now())-Fe)}X.streaming=X.reasoning.status!=="complete",g(X)}else if(et==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&>.reasoning.chunks.length===0&>.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(It=(vt=xe(w,!1))!=null?vt:xe(w,!0))!=null?It:`reason-${l()}`,X=typeof w.text=="string"?w.text:"";!C.get(U)&&(X||w.scope==="loop")&&Me(U);let fe=C.get(U);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),X&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(X),fe.reasoning.status="complete",fe.reasoning.completedAt=K((wt=w.completedAt)!=null?wt:w.timestamp);let gt=(dn=fe.reasoning.startedAt)!=null?dn:Date.now();fe.reasoning.durationMs=Math.max(0,((_t=fe.reasoning.completedAt)!=null?_t:Date.now())-gt),fe.streaming=!1,g(fe)}let Fe=O(w);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(Sn=(Nn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Nn:Oe(w,!0))!=null?Sn:`tool-${l()}`,U=(Tn=w.toolName)!=null?Tn:w.name;if(We(U)){be.add(z);continue}oe(N(w),z);let X=V(z),fe=(xn=X.toolCall)!=null?xn:{id:z,status:"pending"};fe.name=U!=null?U:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(lr=fe.startedAt)!=null?lr:K((En=w.startedAt)!=null?En:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,X.toolCall=fe,X.streaming=!0,w.executionId&&(X.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(X)}else if(et==="tool_output_delta"){let z=(xr=(Ct=Oe(w,!1))!=null?Ct:Oe(w,!0))!=null?xr:`tool-${l()}`;if(be.has(z))continue;let U=V(z),X=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};X.startedAt=(cr=X.startedAt)!=null?cr:K((Nr=w.startedAt)!=null?Nr:w.timestamp);let fe=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";fe&&(X.chunks=(Ao=X.chunks)!=null?Ao:[],X.chunks.push(String(fe))),X.status="running",U.toolCall=X,U.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Rn=Fe==null?void 0:Fe.executionId)!=null?Rn:w.executionId,iteration:(Xo=Fe==null?void 0:Fe.iteration)!=null?Xo:w.iteration}),g(U)}else if(et==="tool_complete"){let z=(Yr=(Or=Oe(w,!1))!=null?Or:Oe(w,!0))!=null?Yr:`tool-${l()}`;if(be.has(z)){be.delete(z);continue}let U=V(z),X=(Zr=U.toolCall)!=null?Zr:{id:z,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),typeof w.duration=="number"&&(X.duration=w.duration),X.completedAt=K((So=w.completedAt)!=null?So:w.timestamp);let fe=(To=w.duration)!=null?To:w.executionTime;if(typeof fe=="number")X.durationMs=fe;else{let st=(eo=X.startedAt)!=null?eo:Date.now();X.durationMs=Math.max(0,((yt=X.completedAt)!=null?yt:Date.now())-st)}U.toolCall=X,U.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Mn=U.agentMetadata)!=null?Mn:{executionId:(On=Fe==null?void 0:Fe.executionId)!=null?On:w.executionId,iteration:(Fn=Fe==null?void 0:Fe.iteration)!=null?Fn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(et==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(At=z!=null?z:w.toolId)!=null?At:`local-${l()}`,X=V(U),fe=w.toolName,Fe=w.origin==="webmcp"&&!Oo(fe)?`webmcp:${fe}`:fe,gt=Oo(Fe),st=(Xn=X.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=Fe,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Fr=st.startedAt)!=null?Fr:K((to=(_n=w.startedAt)!=null?_n:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,X.toolCall=st,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:($n=X.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(X)}else if(et==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let X=f;X&&(Ae==="flow"?(Ye(X),tt=X):(X.streaming=!1,g(X)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(et==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let fe=typeof w.delta=="string"?w.delta:"",Fe=((kn=P.get(z))!=null?kn:"")+fe;if(P.set(z,Fe),Fe.trim()==="")continue;let gt=_e(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},Lt(gt,Fe,fe,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Ae==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(L+=fe,L.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Lt(Fe,L,fe,void 0),v=Fe;continue}let X=pe();X.content+=(Yn=w.delta)!=null?Yn:"",X.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ft!=null?Ft:void 0,agentName:ne==null?void 0:ne.agentName},v=X,g(X)}else if(et==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let X=M.get(z);X&&Ye(X),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Ae==="flow"?(Ye(U),tt=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(et==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let X=w.error,fe=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((_r=X.message)!=null?_r:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let X=tt;tt=null;let fe=w.stopReason,Fe=(oo=w.result)==null?void 0:oo.response;if(X)fe&&(X.stopReason=fe),Fe!=null?Ke(X,Fe):X.streaming!==!1&&(J.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X));else{let gt=Fe!=null&&Fe!=="";if(gt||fe){let st=pe();fe&&(st.stopReason=fe),gt?Ye(st,Fe):(st.streaming=!1,g(st))}}continue}}else if(et==="execution_start")Ae=w.kind==="flow"?"flow":"agent",nt=!0,Ae==="agent"&&(ne={executionId:w.executionId,agentId:(he=w.agentId)!=null?he:"virtual",agentName:(Wn=w.agentName)!=null?Wn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:K(w.startedAt)});else if(et==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(ne&&(ne.currentIteration=z),hn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),$e.set(z-1,U),f=null)}we=z}Ft=typeof w.id=="string"?w.id:null,v=null}else if(et==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let X=w.id;(!X||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===X)&&(U.stopReason=z,g(U))}Ft===w.id&&(Ft=null)}else if(et==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(et==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let X=($r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?$r:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(fe)gt={type:"media",data:fe,mediaType:X};else if(Fe){let pn=X.toLowerCase();gt={type:pn==="image"||pn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:X}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Bn=[];for(let pn of Ps){if(!pn||typeof pn!="object")continue;let un=pn,Lo=typeof un.type=="string"?un.type:void 0,qr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",Ln=null,bn="";if(Lo==="media"){let qn=typeof un.data=="string"?un.data:void 0;if(!qn)continue;bn=qr.length>0?qr:"application/octet-stream",Ln=`data:${bn};base64,${qn}`}else if(Lo==="image-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else if(Lo==="file-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else continue;if(Ln)if(Lo==="image-url"||bn.startsWith("image/"))Bn.push({type:"image",image:Ln,...bn.includes("/")?{mimeType:bn}:{}});else if(bn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:bn});else if(bn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:bn});else{let qn=bn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Wh(qn)})}}if(Bn.length>0){let pn=l(),un=st,qr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${pn}`:String(pn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(qr);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,x.current=null}}else if(et==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Ae;z==="agent"&&ne&&(ne.status=w.success?"complete":"error",ne.completedAt=K(w.completedAt),ne.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Ye(U):(U.streaming=!1,g(U)),f=null),T=null,L="",tt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(et!=="ping"){if(et==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ne==null?void 0:ne.agentId)!=null?Er:"virtual",executionId:(Mr=(jr=w.executionId)!=null?jr:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(dr=w.toolName)!=null?dr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let z=(jn=w.approvalId)!=null?jn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Un=ne==null?void 0:ne.agentId)!=null?Un:"virtual",executionId:(ur=(pr=w.executionId)!=null?pr:ne==null?void 0:ne.executionId)!=null?ur:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(vn=w.description)!=null?vn:`Execute ${(Ur=w.toolName)!=null?Ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="approval_complete"){let z=w.approvalId;if(z){let X={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ne==null?void 0:ne.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ne==null?void 0:ne.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(X)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=w.artifactType,U=String(w.id),X=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:X,component:typeof w.component=="string"?w.component:void 0}),se.set(U,{markdown:"",title:X}),!ae.has(U)){ae.add(U);let fe={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:X,artifactType:z,status:"streaming"}})};de.set(U,fe),g(fe)}}else if(et==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let X=se.get(z);X&&(X.markdown+=U)}else if(et==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=de.get(z);if(U){U.streaming=!1;try{let X=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(X.props){X.props.status="complete";let fe=se.get(z);fe!=null&&fe.markdown&&(X.props.markdown=fe.markdown)}U.rawContent=JSON.stringify(X)}catch{}se.delete(z),g(U),de.delete(z)}}}else if(et==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),X=z.role,Fe={id:U,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&ae.add(st)}catch{}f=null,x.current=null,J.delete(U),ce.delete(U)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(et==="dispatch_error"){let U=(Hn=w.message)!=null?Hn:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}G.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Ee=a.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Yi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var im="4.3.1";var hr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var el=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":hr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new js(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Ou(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,Qt,Dr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Ee=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Be=A.tools?A.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Ee,tools:Be}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Ee=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Ee||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Ee,Be,Le,De;return W((De=(Le=(Be=(Ee=(te=A.stepId)!=null?te:A.step_id)!=null?Ee:A.step)!=null?Be:A.parentId)!=null?Le:A.flowStepId)!=null?De:A.flow_step_id)},N=A=>{var te,Ee,Be,Le,De,Ge,it;return W((it=(Ge=(De=(Le=(Be=(Ee=(te=A.callId)!=null?te:A.call_id)!=null?Ee:A.requestId)!=null?Be:A.request_id)!=null?Le:A.toolCallId)!=null?De:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Z=r,Te=!1,pe=()=>{if(f)return f;let A,te=T;return!Te&&Z?(A=Z,Te=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},xe=(A,te)=>{var De;let Ee=(De=A.reasoningId)!=null?De:A.id,Be=O(A);if(Ee){let Ge=String(Ee);return ee(Be,Ge),Ge}if(Be){let Ge=F.byStep.get(Be);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Le=`reason-${l()}`;return ee(Be,Le),Le},Me=A=>{let te=C.get(A);if(te)return te;let Ee={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Ee),g(Ee),Ee},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},be=new Set,de=new Map,ae=new Set,se=new Map,We=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Oe=(A,te)=>{var De;let Ee=(De=A.toolId)!=null?De:A.id,Be=N(A);if(Ee){let Ge=String(Ee);return oe(Be,Ge),Ge}if(Be){let Ge=j.byCall.get(Be);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Le=`tool-${l()}`;return oe(Be,Le),Le},V=A=>{let te=R.get(A);if(te)return te;let Ee={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Ee),g(Ee),Ee},K=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Ee=Date.parse(A);if(!Number.isNaN(Ee))return Ee}return Date.now()},ve=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},J=new Map,ce=new Map,Re=new Map,ge=(A,te,Ee)=>{var it;let Be=Re.get(A);Be||(Be=[],Re.set(A,Be));let Le=0,De=Be.length;for(;Le<De;){let Pt=Le+De>>>1;Be[Pt].seq<te?Le=Pt+1:De=Pt}((it=Be[Le])==null?void 0:it.seq)===te?Be[Le]={seq:te,text:Ee}:Be.splice(Le,0,{seq:te,text:Ee});let Ge="";for(let Pt=0;Pt<Be.length;Pt++)Ge+=Be[Pt].text;return Ge},Ke=(A,te)=>{let Ee=ve(te),Be=ce.get(A.id),Le=Bh(Be,Ee);A.rawContent=Le;let De=J.get(A.id),Ge=Q=>{var lt;let Se=(lt=A.content)!=null?lt:"";Q.trim()!==""&&(Se.trim().length===0||Q.startsWith(Se)||Q.trimStart().startsWith(Se.trim()))&&(A.content=Q)},it=()=>{var Q;if(De){let Se=(Q=De.close)==null?void 0:Q.call(De);Se instanceof Promise&&Se.catch(()=>{})}J.delete(A.id),ce.delete(A.id),A.streaming=!1,g(A)};if(!De){Ge(Ee),it();return}let Pt=Xs(Le);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),it();return}let bt=Q=>{var Qe;let Se=typeof Q=="string"?Q:(Qe=Q==null?void 0:Q.text)!=null?Qe:null;if(Se!==null&&Se.trim()!=="")return Se;let lt=De.getExtractedText();return lt!==null&<.trim()!==""?lt:Ee},H;try{H=De.processChunk(Le)}catch{Ge(Ee),it();return}if(H instanceof Promise){H.then(Q=>{Ge(bt(Q)),it()}).catch(()=>{Ge(Ee),it()});return}Ge(bt(H)),it()},tt=null,Lt=(A,te,Ee,Be)=>{var Pt;A.rawContent=te,J.has(A.id)||J.set(A.id,this.createStreamParser());let Le=J.get(A.id),De=te.trim().startsWith("{")||te.trim().startsWith("[");if(De&&ce.set(A.id,te),Le.__isPlainTextParser===!0){A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A);return}let it=Le.processChunk(te);if(it instanceof Promise)it.then(bt=>{var Q;let H=typeof bt=="string"?bt:(Q=bt==null?void 0:bt.text)!=null?Q:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof it=="string"?it:(Pt=it==null?void 0:it.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Ee=te!=null?te:A.content;if(Ee==null||Ee===""){A.streaming=!1,g(A);return}let Be=ce.get(A.id),Le=Be!=null?Be:ve(Ee);A.rawContent=Le;let De=J.get(A.id),Ge=null,it=!1;if(De&&(Ge=De.getExtractedText(),Ge===null&&(Ge=Xs(Le)),Ge===null)){let H=De.processChunk(Le);H instanceof Promise?(it=!0,H.then(Q=>{var lt;let Se=typeof Q=="string"?Q:(lt=Q==null?void 0:Q.text)!=null?lt:null;Se!==null&&(A.content=Se,A.streaming=!1,J.delete(A.id),ce.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:ce.has(A.id)||(A.content=ve(Ee));let H=J.get(A.id);if(H){let Q=(bt=H.close)==null?void 0:bt.call(H);Q instanceof Promise&&Q.catch(()=>{}),J.delete(A.id)}ce.delete(A.id),A.streaming=!1,g(A)}},_e=(A,te,Ee)=>{let Be=M.get(A);if(Be)return Be;let Le={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Le),g(Le),Le},G=[],ze,qe=new Map,we=0,Ae="agent",nt=!1,Ft=null,ne=null,$e=new Map,hn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ze=()=>{var A,te,Ee,Be,Le,De,Ge,it,Pt,bt,H,Q,Se,lt,Qe,jt,yn,xt,vt,It,wt,dn,_t,Nn,Sn,Tn,xn,En,lr,Ct,xr,vr,Nr,cr,ut,Co,wr,Ao,Rn,Xo,Qr,Or,Yr,Zr,So,To,eo,yt,On,Fn,Mn,At,Xn,Qn,_n,to,Fr,no,$n,Rt,kn,Yn,ro,_r,oo,he,Wn,Cr,mt,rn,on,Ar,ks,$r,Eo,Sr,$,Qo,Tr,Er,jr,Mr,dr,Yo,xa,jn,Un,pr,ur,Mo,Ur,vn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,Hn,Ca;for(let rs=0;rs<G.length;rs++){let et=G[rs].payloadType,w=G[rs].payload;if(!nt&&Ae!=="flow"&&typeof w.stepType=="string"&&(Ae="flow"),et==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),_e(z,U,"reasoning");continue}let X=(A=xe(w,!0))!=null?A:`reason-${l()}`,fe=Me(X);fe.reasoning=(te=fe.reasoning)!=null?te:{id:X,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:K((Ee=w.startedAt)!=null?Ee:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(et==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let Fe=M.get(z),gt=(Ge=(De=(Le=w.reasoningText)!=null?Le:w.text)!=null?De:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let U=(Pt=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?Pt:`reason-${l()}`,X=Me(U);X.reasoning=(bt=X.reasoning)!=null?bt:{id:U,status:"streaming",chunks:[]},X.reasoning.startedAt=(Q=X.reasoning.startedAt)!=null?Q:K((H=w.startedAt)!=null?H:w.timestamp);let fe=(Qe=(lt=(Se=w.reasoningText)!=null?Se:w.text)!=null?lt:w.delta)!=null?Qe:"";if(fe&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let gt=ge(U,Fe,String(fe));X.reasoning.chunks=[gt]}else X.reasoning.chunks.push(String(fe))}if(X.reasoning.status=w.done?"complete":"streaming",w.done){X.reasoning.completedAt=K((jt=w.completedAt)!=null?jt:w.timestamp);let Fe=(yn=X.reasoning.startedAt)!=null?yn:Date.now();X.reasoning.durationMs=Math.max(0,((xt=X.reasoning.completedAt)!=null?xt:Date.now())-Fe)}X.streaming=X.reasoning.status!=="complete",g(X)}else if(et==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&>.reasoning.chunks.length===0&>.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(It=(vt=xe(w,!1))!=null?vt:xe(w,!0))!=null?It:`reason-${l()}`,X=typeof w.text=="string"?w.text:"";!C.get(U)&&(X||w.scope==="loop")&&Me(U);let fe=C.get(U);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),X&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(X),fe.reasoning.status="complete",fe.reasoning.completedAt=K((wt=w.completedAt)!=null?wt:w.timestamp);let gt=(dn=fe.reasoning.startedAt)!=null?dn:Date.now();fe.reasoning.durationMs=Math.max(0,((_t=fe.reasoning.completedAt)!=null?_t:Date.now())-gt),fe.streaming=!1,g(fe)}let Fe=O(w);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(Sn=(Nn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Nn:Oe(w,!0))!=null?Sn:`tool-${l()}`,U=(Tn=w.toolName)!=null?Tn:w.name;if(We(U)){be.add(z);continue}oe(N(w),z);let X=V(z),fe=(xn=X.toolCall)!=null?xn:{id:z,status:"pending"};fe.name=U!=null?U:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(lr=fe.startedAt)!=null?lr:K((En=w.startedAt)!=null?En:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,X.toolCall=fe,X.streaming=!0,w.executionId&&(X.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(X)}else if(et==="tool_output_delta"){let z=(xr=(Ct=Oe(w,!1))!=null?Ct:Oe(w,!0))!=null?xr:`tool-${l()}`;if(be.has(z))continue;let U=V(z),X=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};X.startedAt=(cr=X.startedAt)!=null?cr:K((Nr=w.startedAt)!=null?Nr:w.timestamp);let fe=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";fe&&(X.chunks=(Ao=X.chunks)!=null?Ao:[],X.chunks.push(String(fe))),X.status="running",U.toolCall=X,U.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Rn=Fe==null?void 0:Fe.executionId)!=null?Rn:w.executionId,iteration:(Xo=Fe==null?void 0:Fe.iteration)!=null?Xo:w.iteration}),g(U)}else if(et==="tool_complete"){let z=(Yr=(Or=Oe(w,!1))!=null?Or:Oe(w,!0))!=null?Yr:`tool-${l()}`;if(be.has(z)){be.delete(z);continue}let U=V(z),X=(Zr=U.toolCall)!=null?Zr:{id:z,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),typeof w.duration=="number"&&(X.duration=w.duration),X.completedAt=K((So=w.completedAt)!=null?So:w.timestamp);let fe=(To=w.duration)!=null?To:w.executionTime;if(typeof fe=="number")X.durationMs=fe;else{let st=(eo=X.startedAt)!=null?eo:Date.now();X.durationMs=Math.max(0,((yt=X.completedAt)!=null?yt:Date.now())-st)}U.toolCall=X,U.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Mn=U.agentMetadata)!=null?Mn:{executionId:(On=Fe==null?void 0:Fe.executionId)!=null?On:w.executionId,iteration:(Fn=Fe==null?void 0:Fe.iteration)!=null?Fn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(et==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(At=z!=null?z:w.toolId)!=null?At:`local-${l()}`,X=V(U),fe=w.toolName,Fe=w.origin==="webmcp"&&!Oo(fe)?`webmcp:${fe}`:fe,gt=Oo(Fe),st=(Xn=X.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=Fe,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Fr=st.startedAt)!=null?Fr:K((to=(_n=w.startedAt)!=null?_n:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,X.toolCall=st,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:($n=X.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(X)}else if(et==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let X=f;X&&(Ae==="flow"?(Ye(X),tt=X):(X.streaming=!1,g(X)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(et==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let fe=typeof w.delta=="string"?w.delta:"",Fe=((kn=P.get(z))!=null?kn:"")+fe;if(P.set(z,Fe),Fe.trim()==="")continue;let gt=_e(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},Lt(gt,Fe,fe,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Ae==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(L+=fe,L.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Lt(Fe,L,fe,void 0),v=Fe;continue}let X=pe();X.content+=(Yn=w.delta)!=null?Yn:"",X.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ft!=null?Ft:void 0,agentName:ne==null?void 0:ne.agentName},v=X,g(X)}else if(et==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let X=M.get(z);X&&Ye(X),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Ae==="flow"?(Ye(U),tt=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(et==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let X=w.error,fe=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((_r=X.message)!=null?_r:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let X=tt;tt=null;let fe=w.stopReason,Fe=(oo=w.result)==null?void 0:oo.response;if(X)fe&&(X.stopReason=fe),Fe!=null?Ke(X,Fe):X.streaming!==!1&&(J.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X));else{let gt=Fe!=null&&Fe!=="";if(gt||fe){let st=pe();fe&&(st.stopReason=fe),gt?Ye(st,Fe):(st.streaming=!1,g(st))}}continue}}else if(et==="execution_start")Ae=w.kind==="flow"?"flow":"agent",nt=!0,Ae==="agent"&&(ne={executionId:w.executionId,agentId:(he=w.agentId)!=null?he:"virtual",agentName:(Wn=w.agentName)!=null?Wn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:K(w.startedAt)});else if(et==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(ne&&(ne.currentIteration=z),hn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),$e.set(z-1,U),f=null)}we=z}Ft=typeof w.id=="string"?w.id:null,v=null}else if(et==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let X=w.id;(!X||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===X)&&(U.stopReason=z,g(U))}Ft===w.id&&(Ft=null)}else if(et==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(et==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let X=($r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?$r:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(fe)gt={type:"media",data:fe,mediaType:X};else if(Fe){let pn=X.toLowerCase();gt={type:pn==="image"||pn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:X}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Bn=[];for(let pn of Ps){if(!pn||typeof pn!="object")continue;let un=pn,Lo=typeof un.type=="string"?un.type:void 0,qr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",Ln=null,bn="";if(Lo==="media"){let qn=typeof un.data=="string"?un.data:void 0;if(!qn)continue;bn=qr.length>0?qr:"application/octet-stream",Ln=`data:${bn};base64,${qn}`}else if(Lo==="image-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else if(Lo==="file-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else continue;if(Ln)if(Lo==="image-url"||bn.startsWith("image/"))Bn.push({type:"image",image:Ln,...bn.includes("/")?{mimeType:bn}:{}});else if(bn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:bn});else if(bn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:bn});else{let qn=bn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Wh(qn)})}}if(Bn.length>0){let pn=l(),un=st,qr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${pn}`:String(pn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(qr);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,x.current=null}}else if(et==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Ae;z==="agent"&&ne&&(ne.status=w.success?"complete":"error",ne.completedAt=K(w.completedAt),ne.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Ye(U):(U.streaming=!1,g(U)),f=null),T=null,L="",tt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(et!=="ping"){if(et==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ne==null?void 0:ne.agentId)!=null?Er:"virtual",executionId:(Mr=(jr=w.executionId)!=null?jr:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(dr=w.toolName)!=null?dr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let z=(jn=w.approvalId)!=null?jn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Un=ne==null?void 0:ne.agentId)!=null?Un:"virtual",executionId:(ur=(pr=w.executionId)!=null?pr:ne==null?void 0:ne.executionId)!=null?ur:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(vn=w.description)!=null?vn:`Execute ${(Ur=w.toolName)!=null?Ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="approval_complete"){let z=w.approvalId;if(z){let X={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ne==null?void 0:ne.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ne==null?void 0:ne.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(X)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=w.artifactType,U=String(w.id),X=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:X,component:typeof w.component=="string"?w.component:void 0}),se.set(U,{markdown:"",title:X}),!ae.has(U)){ae.add(U);let fe={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:X,artifactType:z,status:"streaming"}})};de.set(U,fe),g(fe)}}else if(et==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let X=se.get(z);X&&(X.markdown+=U)}else if(et==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=de.get(z);if(U){U.streaming=!1;try{let X=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(X.props){X.props.status="complete";let fe=se.get(z);fe!=null&&fe.markdown&&(X.props.markdown=fe.markdown)}U.rawContent=JSON.stringify(X)}catch{}se.delete(z),g(U),de.delete(z)}}}else if(et==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),X=z.role,Fe={id:U,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&ae.add(st)}catch{}f=null,x.current=null,J.delete(U),ce.delete(U)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(et==="dispatch_error"){let U=(Hn=w.message)!=null?Hn:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}G.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Ee=a.split(`
|
|
12
12
|
|
|
13
13
|
`);a=(Qt=Ee.pop())!=null?Qt:"";for(let Be of Ee){let Le=Be.split(`
|
|
14
14
|
`),De="message",Ge="";for(let bt of Le)bt.startsWith("event:")?De=bt.replace("event:","").trim():bt.startsWith("data:")&&(Ge+=bt.replace("data:","").trim());if(!Ge)continue;let it;try{it=JSON.parse(Ge)}catch(bt){n({type:"error",error:bt instanceof Error?bt:new Error("Failed to parse chat stream payload")});continue}let Pt=De!=="message"?De:(Dr=it.type)!=null?Dr:"message";if((br=this.onSSEEvent)==null||br.call(this,Pt,it),this.parseSSEEvent){x.current=f;let bt=await this.handleCustomSSEEvent(it,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),bt)continue}G.push({payloadType:Pt,payload:it}),ze()}}ze()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var $a="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _h(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ja(e){return{type:"text",text:e}}function $h(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function jh(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Uh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var cm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Gr=[...cm,...qh];function zh(e){return cm.includes(e)||e.startsWith("image/")}function Ua(e){return zh(e.type)}async function dm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function pm(e,t=Gr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Vh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Vh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}tl();var mm=16e3,Kh=24e3,Gh=4096,Jh=1380533830;function Xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jh?new Uint8Array(e,44):new Uint8Array(e)}function Qh(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ys=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:mm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:mm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ys(Kh);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Qh(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Gh,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Xh(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return jo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if($o.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return nl(e),!0}catch{return!1}}function Zs(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Uo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Zs(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var bs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function rl(e){if(!e)return"";let t=Yh(e);return gm(t!==null?t:e)}function Yh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function gm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|