@runtypelabs/persona 4.11.1 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -10272,6 +10272,15 @@ type CodeGeneratorOptions = {
10272
10272
  * @default "body"
10273
10273
  */
10274
10274
  target?: string;
10275
+ /**
10276
+ * Base URL of the directory holding the widget assets (install.global.js,
10277
+ * index.global.js, widget.css) for the script formats (script-installer,
10278
+ * script-manual, script-advanced). Pass a first-party base such as
10279
+ * "https://cdn.runtype.com/persona/latest" when the embedding page's CSP
10280
+ * does not allow third-party CDNs. A trailing slash is tolerated.
10281
+ * @default the jsDelivr dist directory pinned to this package version
10282
+ */
10283
+ cdnBase?: string;
10275
10284
  };
10276
10285
  declare function generateCodeSnippet(config: any, format?: CodeFormat, options?: CodeGeneratorOptions): string;
10277
10286
 
package/dist/index.d.ts CHANGED
@@ -10272,6 +10272,15 @@ type CodeGeneratorOptions = {
10272
10272
  * @default "body"
10273
10273
  */
10274
10274
  target?: string;
10275
+ /**
10276
+ * Base URL of the directory holding the widget assets (install.global.js,
10277
+ * index.global.js, widget.css) for the script formats (script-installer,
10278
+ * script-manual, script-advanced). Pass a first-party base such as
10279
+ * "https://cdn.runtype.com/persona/latest" when the embedding page's CSP
10280
+ * does not allow third-party CDNs. A trailing slash is tolerated.
10281
+ * @default the jsDelivr dist directory pinned to this package version
10282
+ */
10283
+ cdnBase?: string;
10275
10284
  };
10276
10285
  declare function generateCodeSnippet(config: any, format?: CodeFormat, options?: CodeGeneratorOptions): string;
10277
10286
 
@@ -9,7 +9,7 @@ ${t}`:"")+(e.description?`
9
9
  ${e.description}`:"");return window.confirm(n)},ox=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)}},rx=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ax=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function jo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function Ws(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var sx="agent_",ix="flow_";function Of(e){return e.startsWith(sx)?{kind:"agentId",agentId:e}:e.startsWith(ix)?{kind:"flowId",flowId:e}:null}function Nf(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let d=Of(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Of(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(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.`)}var fo=po(Ds(),1);var x=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Uf=()=>document.createDocumentFragment(),Fe=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},zn=(...e)=>e.filter(Boolean).join(" ");var wa="ask_user_question",Ca=8,Sr="data-persona-ask-sheet-for",ux="Other",fx="Other\u2026",Vf="Type your own answer here",zf="Send",mx="Next",gx="Back",hx="Submit all",yx="Skip",xx=3,jl="data-ask-current-index",Gl="data-ask-question-count",$f="data-ask-answers",Kl="data-ask-grouped",jf="data-ask-layout",bx=e=>e.layout==="pills"?"pills":"rows",vx=e=>e.getAttribute(jf)==="pills"?"pills":"rows",qf=!1,Gf=e=>e.replace(/["\\]/g,"\\$&"),$n=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===wa,Fs=e=>e?.features?.askUserQuestion??{},jn=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),a=(0,fo.parse)(r,fo.STR|fo.OBJ|fo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},Aa=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ca&&!qf&&(qf=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ca}.`)),t.slice(0,Ca)},Cx=e=>Aa(e)[0]??null,wx=(e,t)=>Aa(e)[t]??null,Kf=(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))},Xf=(e,t,n)=>{if(e!=="rows")return null;let o=x("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=x("span","persona-ask-row-check");o.appendChild(r)}else{let r=x("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ax=(e,t,n,o)=>{let a=x("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),n==="rows"){let s=x("span","persona-ask-row-content"),l=x("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=x("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Xf(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Sx=e=>{let n=x("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},Mx=(e,t,n,o)=>{let a=x("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<xx;c++)a.appendChild(Sx(o));return a}if(p.forEach((c,u)=>{a.appendChild(Ax(c,u,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?ux:fx;if(o==="rows"){let u=x("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=x("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Vf,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(f),u.appendChild(g);let h=Xf(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=x("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,a.appendChild(u)}}return a},Jf=(e,t)=>{let o=x("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Vf,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=x("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??zf,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},Tx=e=>{let t=x("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=x("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??zf,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Ex=(e,t,n)=>{let o=x("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=x("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=x("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=x("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??yx,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=x("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??hx:n.nextLabel??mx,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Go=e=>{let t=e.getAttribute($f);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Qf=(e,t)=>{e.setAttribute($f,JSON.stringify(t))},hn=e=>{let t=Number(e.getAttribute(jl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kx=(e,t)=>{e.setAttribute(jl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Gl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Kl)==="true",Lx=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},Px=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Os=(e,t)=>{let{payload:n}=jn(t),o=Aa(n),r=Go(e),a={},s=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(s.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(a[d]=r[p]))}),a},Yf=e=>{let t=Go(e),n=hn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Zf=e=>{if(!mo(e))return;let t=Go(e),n=hn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},Xl=(e,t,n)=>{let o=Fs(n),r=vx(e),{payload:a,complete:s}=jn(t),l=mo(e),p=hn(e),d=Mr(e),c=l?wx(a,p):Cx(a),u=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof c?.question=="string"?c.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let S=e.querySelector('[data-ask-pill-list="true"]');if(S){let M=Mx(c,o,s,r);S.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Jf(o,r))}let L=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!L?e.appendChild(Tx(o)):(!u||l)&&L&&L.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=Ex(p,d,o);E?E.replaceWith(M):e.appendChild(M)}else E&&E.remove();Yf(e),Zf(e)},Rx=(e,t,n)=>{let o=Fs(t),r=bx(o),a=e.toolCall.id,s=Aa(n),l=Math.max(1,s.length),p=l>1,d=Lx(e,s),c=p?Px(e,l):0,u=x("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Sr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Gl,String(l)),u.setAttribute(jl,String(c)),u.setAttribute(Kl,p?"true":"false"),u.setAttribute(jf,r),Qf(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Kf(u,o);let g=x("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=x("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=x("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let L=x("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),u.appendChild(L),r!=="rows"&&u.appendChild(Jf(o,r)),Xl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Ix=(e,t,n)=>{let{payload:o}=jn(t),r=Math.max(1,Aa(o).length);r>Mr(e)&&(e.setAttribute(Gl,String(r)),r>1&&!mo(e)&&e.setAttribute(Kl,"true")),Xl(e,t,n)},em=(e,t)=>{let n=x("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 o=Fs(t);Kf(n,o);let r=x("span","persona-ask-stub-label"),{complete:a}=jn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Tr=(e,t,n)=>{if(!n||!$n(e)||Fs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let s=n.querySelector(`[${Sr}="${Gf(r)}"]`);if(s){Ix(s,e,t);return}let{payload:l}=jn(e),p=Rx(e,t,l);n.appendChild(p)},go=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Gf(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},Jl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ho=(e,t)=>{let n=Go(e),o=hn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Qf(e,n),Yf(e),Zf(e)},Ns=(e,t,n,o)=>{let r=Mr(e),a=Math.max(0,Math.min(r-1,o));kx(e,a),Xl(e,t,n)};var Tn="suggest_replies";var Ql={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},_s={name:Tn,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:Ql,origin:"sdk",annotations:{readOnlyHint:!0}},Yl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Sa=e=>e.variant==="tool"&&e.toolCall?.name===Tn,Zl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Us=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Sa(n))continue;let o=Zl(n.toolCall?.args);return o.length>0?o:null}return null},tm=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var ed={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ca,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},td={name:wa,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:ed,origin:"sdk",annotations:{readOnlyHint:!0}},Er=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(td),tm(e)&&t.push(_s),t};var Gn=po(Ds(),1),qs=e=>e.replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),yo=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)}},Wx=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},nm=e=>e.status==="complete"?Wx(e):e.status==="pending"?"Waiting":"",Hx=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??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 om=e=>e.status==="complete"?Hx(e):"Using tool...",Vs=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ta=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vs(t)},zs=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Vs(t)},nd=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ta(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},$s=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Ma(o,n.slice(a,s.index),[]),s[1]!==void 0?Ma(o,s[1],["bold"]):s[2]!==void 0?Ma(o,s[2],["italic"]):s[3]!==void 0&&Ma(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Ma(o,n.slice(a),[]),o},Ma=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Bx=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
11
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(s);if(l&&l[1])try{return l[1].replace(/\\n/g,`
12
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ea=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},js=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gs=()=>{let e=Bx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ks=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Gn.parse)(n,Gn.STR|Gn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?qs(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=qs(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},rm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?qs(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?qs(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Gn.parse)(a,Gn.STR|Gn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Xs=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var am="4.11.1";var Ko=am;var Fx="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com";function Ox(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var od=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 Nx(e){switch(e){case"json":return Ks;case"regex-json":return Gs;case"xml":return Xs;default:return js}}var sm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _x(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=sm(n);if(!sm(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Ea(e);return Ea(t)!==null&&s===null?t:e}var Xo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;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=t.apiUrl??Fx,this.headers={"Content-Type":"application/json","X-Persona-Version":Ko,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Nx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ar(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=Nf(o,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(r)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(od).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...s,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?Ff(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let g=0;;g++){if(u=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Js}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let d=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(s,d,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(od).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(od).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=R=>{let z=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,b=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,P=R.tools?R.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...R,reasoning:z,toolCall:b,tools:P}},g=R=>{if(R.role!=="assistant"||R.variant)return!0;let z=Array.isArray(R.contentParts)&&R.contentParts.length>0,b=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||z||b||!!R.stopReason},f=R=>{g(R)&&n({type:"message",message:u(R)})},h=null,S=null,L={current:null},E={current:null},M=null,A="",w=new Map,T=new Map,H=new Map,C=new Map,B=new Map,F={lastId:null,byStep:new Map},q={lastId:null,byCall:new Map},D=R=>{if(R==null)return null;try{return String(R)}catch{return null}},U=R=>D(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),se=R=>D(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),le=o,Ce=!1,Ie=()=>{if(h)return h;let R,z="",b=M;return!Ce&&le?(R=le,Ce=!0,z=r??""):le&&b?R=`${le}_${b}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:R,role:"assistant",content:z,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ae=(R,z)=>{F.lastId=z,R&&F.byStep.set(R,z)},me=(R,z)=>{let b=R.reasoningId??R.id,P=U(R);if(b){let N=String(b);return ae(P,N),N}if(P){let N=F.byStep.get(P);if(N)return F.lastId=N,N}if(F.lastId&&!z)return F.lastId;if(!z)return null;let I=`reason-${c()}`;return ae(P,I),I},Z=R=>{let z=C.get(R);if(z)return z;let b={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:R,status:"streaming",chunks:[]}};return C.set(R,b),f(b),b},de=(R,z)=>{q.lastId=z,R&&q.byCall.set(R,z)},Y=new Set,ve=new Map,Ae=new Set,xe=new Map,Be=R=>{if(!R)return!1;let z=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return z==="emit_artifact_markdown"||z==="emit_artifact_component"},Oe=(R,z)=>{let b=R.toolId??R.id,P=se(R);if(b){let N=String(b);return de(P,N),N}if(P){let N=q.byCall.get(P);if(N)return q.lastId=N,N}if(q.lastId&&!z)return q.lastId;if(!z)return null;let I=`tool-${c()}`;return de(P,I),I},ze=R=>{let z=B.get(R);if(z)return z;let b={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:R,status:"pending"}};return B.set(R,b),f(b),b},Ne=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let z=Number(R);if(!Number.isNaN(z)&&Number.isFinite(z))return z;let b=Date.parse(R);if(!Number.isNaN(b))return b}return Date.now()},rt=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},Je=new Map,We=new Map,Me=new Map,Qe=(R,z,b)=>{let P=Me.get(R);P||(P=[],Me.set(R,P));let I=0,N=P.length;for(;I<N;){let _=I+N>>>1;P[_].seq<z?I=_+1:N=_}P[I]?.seq===z?P[I]={seq:z,text:b}:P.splice(I,0,{seq:z,text:b});let G="";for(let _=0;_<P.length;_++)G+=P[_].text;return G},cn=(R,z)=>{let b=rt(z),P=We.get(R.id),I=_x(P,b);R.rawContent=I;let N=Je.get(R.id),G=Te=>{let at=R.content??"";Te.trim()!==""&&(at.trim().length===0||Te.startsWith(at)||Te.trimStart().startsWith(at.trim()))&&(R.content=Te)},_=()=>{if(N){let Te=N.close?.();Te instanceof Promise&&Te.catch(()=>{})}Je.delete(R.id),We.delete(R.id),R.streaming=!1,f(R)};if(!N){G(b),_();return}let j=Ea(I);if(j!==null&&j.trim()!==""){G(j),_();return}let re=Te=>{let at=typeof Te=="string"?Te:Te?.text??null;if(at!==null&&at.trim()!=="")return at;let K=N.getExtractedText();return K!==null&&K.trim()!==""?K:b},je;try{je=N.processChunk(I)}catch{G(b),_();return}if(je instanceof Promise){je.then(Te=>{G(re(Te)),_()}).catch(()=>{G(b),_()});return}G(re(je)),_()},Tt=null,yt=(R,z,b,P)=>{R.rawContent=z,Je.has(R.id)||Je.set(R.id,this.createStreamParser());let I=Je.get(R.id),N=z.trim().startsWith("{")||z.trim().startsWith("[");if(N&&We.set(R.id,z),I.__isPlainTextParser===!0){R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R);return}let _=I.processChunk(z);if(_ instanceof Promise)_.then(j=>{let re=typeof j=="string"?j:j?.text??null;re!==null&&re.trim()!==""?(R.content=re,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}).catch(()=>{R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(R.content=j,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}},He=(R,z)=>{let b=z??R.content;if(b==null||b===""){R.streaming=!1,f(R);return}let I=We.get(R.id)??rt(b);R.rawContent=I;let N=Je.get(R.id),G=null,_=!1;if(N&&(G=N.getExtractedText(),G===null&&(G=Ea(I)),G===null)){let j=N.processChunk(I);j instanceof Promise?(_=!0,j.then(re=>{let je=typeof re=="string"?re:re?.text??null;je!==null&&(R.content=je,R.streaming=!1,Je.delete(R.id),We.delete(R.id),f(R))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!_){G!==null&&G.trim()!==""?R.content=G:We.has(R.id)||(R.content=rt(b));let j=Je.get(R.id);if(j){let re=j.close?.();re instanceof Promise&&re.catch(()=>{}),Je.delete(R.id)}We.delete(R.id),R.streaming=!1,f(R)}},fe=(R,z,b)=>{let P=T.get(R);if(P)return P;let I={id:`nested-${z}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:z}};return T.set(R,I),f(I),I},Ke=[],Ee,pe=new Map,ie=0,ge="agent",xt=!1,he=null,ce=null,yn=new Map,Q=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let R=0;R<Ke.length;R++){let z=Ke[R].payloadType,b=Ke[R].payload;if(!xt&&ge!=="flow"&&typeof b.stepType=="string"&&(ge="flow"),z==="reasoning_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I),fe(P,I,"reasoning");continue}let N=me(b,!0)??`reason-${c()}`,G=Z(N);G.reasoning=G.reasoning??{id:N,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Ne(b.startedAt??b.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(z==="reasoning_delta"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let _=T.get(P),j=b.reasoningText??b.text??b.delta??"";j&&b.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=Z(I);N.reasoning=N.reasoning??{id:I,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Ne(b.startedAt??b.timestamp);let G=b.reasoningText??b.text??b.delta??"";if(G&&b.hidden!==!0){let _=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(_!==void 0){let j=Qe(I,_,String(G));N.reasoning.chunks=[j]}else N.reasoning.chunks.push(String(G))}if(N.reasoning.status=b.done?"complete":"streaming",b.done){N.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let _=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-_)}N.streaming=N.reasoning.status!=="complete",f(N)}else if(z==="reasoning_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let j=T.get(P);if(j.reasoning){let re=typeof b.text=="string"?b.text:"";re&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(re),j.reasoning.status="complete",j.streaming=!1,f(j)}w.delete(P),T.delete(P);continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=typeof b.text=="string"?b.text:"";!C.get(I)&&(N||b.scope==="loop")&&Z(I);let G=C.get(I);if(G?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),N&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(N),G.reasoning.status="complete",G.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let j=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-j),G.streaming=!1,f(G)}let _=U(b);_&&F.byStep.delete(_)}else if(z==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof b.iteration=="number"&&(ie=b.iteration);let P=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Oe(b,!0)??`tool-${c()}`,I=b.toolName??b.name;if(Be(I)){Y.add(P);continue}de(se(b),P);let N=ze(P),G=N.toolCall??{id:P,status:"pending"};G.name=I??G.name,G.status="running",b.parameters!==void 0?G.args=b.parameters:b.args!==void 0&&(G.args=b.args),G.startedAt=G.startedAt??Ne(b.startedAt??b.timestamp),G.completedAt=void 0,G.durationMs=void 0,N.toolCall=G,N.streaming=!0,b.executionId&&(N.agentMetadata={executionId:b.executionId,iteration:b.iteration}),f(N)}else if(z==="tool_output_delta"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P))continue;let I=ze(P),N=I.toolCall??{id:P,status:"running"};N.startedAt=N.startedAt??Ne(b.startedAt??b.timestamp);let G=b.text??b.delta??b.message??"";G&&(N.chunks=N.chunks??[],N.chunks.push(String(G))),N.status="running",I.toolCall=N,I.streaming=!0;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I)}else if(z==="tool_complete"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let I=ze(P),N=I.toolCall??{id:P,status:"running"};N.status="complete",b.result!==void 0&&(N.result=b.result),typeof b.duration=="number"&&(N.duration=b.duration),N.completedAt=Ne(b.completedAt??b.timestamp);let G=b.duration??b.executionTime;if(typeof G=="number")N.durationMs=G;else{let re=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-re)}I.toolCall=N,I.streaming=!1;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I);let j=se(b);j&&q.byCall.delete(j)}else if(z==="await"&&b.toolName){let P=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,I=P??b.toolId??`local-${c()}`,N=ze(I),G=b.toolName,_=b.origin==="webmcp"&&!uo(G)?`webmcp:${G}`:G,j=uo(_),re=N.toolCall??{id:I,status:"pending"};re.name=_,re.args=b.parameters,re.status=j?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ne(b.startedAt??b.timestamp??b.awaitedAt),j?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,N.toolCall=re,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:b.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(N)}else if(z==="text_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I);continue}let N=h;N&&(ge==="flow"?(He(N),Tt=N):(N.streaming=!1,f(N)),h=null),M=typeof b.id=="string"?b.id:M,A=""}else if(z==="text_delta"){let P=typeof b.id=="string"?b.id:null,I=P?w.get(P):void 0;if(P&&I){let G=typeof b.delta=="string"?b.delta:"",_=(H.get(P)??"")+G;if(H.set(P,_),_.trim()==="")continue;let j=fe(P,I);j.agentMetadata={...j.agentMetadata,executionId:b.executionId,parentToolId:I},yt(j,_,G,void 0);continue}if(M=typeof b.id=="string"?b.id:M,ge==="flow"){let G=typeof b.delta=="string"?b.delta:"";if(A+=G,A.trim()==="")continue;let _=Ie();_.agentMetadata={executionId:b.executionId,iteration:b.iteration},yt(_,A,G,void 0),S=_;continue}let N=Ie();N.content+=b.delta??"",N.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:he??void 0,agentName:ce?.agentName},S=N,f(N)}else if(z==="text_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)){let N=T.get(P);N&&He(N),w.delete(P),H.delete(P),T.delete(P);continue}let I=h;I&&(ge==="flow"?(He(I),Tt=I):((I.content??"")===""&&typeof b.text=="string"&&(I.content=b.text),I.streaming=!1,f(I)),h=null),M=null,A=""}else if(z==="step_complete"){let P=b.stepType,I=b.executionType;if(P==="tool"||I==="context")continue;if(b.success===!1){let N=b.error,G=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let N=Tt;Tt=null;let G=b.stopReason,_=b.result?.response;if(N)G&&(N.stopReason=G),_!=null?cn(N,_):N.streaming!==!1&&(Je.delete(N.id),We.delete(N.id),N.streaming=!1,f(N));else{let j=_!=null&&_!=="";if(j||G){let re=Ie();G&&(re.stopReason=G),j?He(re,_):(re.streaming=!1,f(re))}}continue}}else if(z==="execution_start")ge=b.kind==="flow"?"flow":"agent",xt=!0,ge==="agent"&&(ce={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:Ne(b.startedAt)});else if(z==="turn_start"){let P=typeof b.iteration=="number"?b.iteration:ie;if(P!==ie){if(ce&&(ce.currentIteration=P),Q==="separate"&&P>1){let I=h;I&&(I.streaming=!1,f(I),yn.set(P-1,I),h=null)}ie=P}he=typeof b.id=="string"?b.id:null,S=null}else if(z==="tool_input_delta"){let P=b.toolCallId??q.lastId;if(P){let I=B.get(P);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(b.delta??""),f(I))}}else{if(z==="tool_input_complete")continue;if(z==="turn_complete"){let P=b.stopReason,I=h??S;if(P&&I!==null){let N=b.id;(!N||I.agentMetadata?.turnId===N)&&(I.stopReason=P,f(I))}he===b.id&&(he=null)}else if(z==="media_start"){let P=String(b.id);pe.set(P,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(z==="media_delta"){let P=pe.get(String(b.id));P&&typeof b.delta=="string"&&P.parts.push(b.delta)}else if(z==="media_complete"){let P=String(b.id),I=pe.get(P);pe.delete(P);let N=(typeof b.mediaType=="string"?b.mediaType:void 0)??I?.mediaType??"application/octet-stream",G=typeof b.data=="string"?b.data:void 0,_=typeof b.url=="string"?b.url:I&&I.parts.length>0?I.parts.join(""):void 0,j=null;if(G)j={type:"media",data:G,mediaType:N};else if(_){let at=N.toLowerCase();j={type:at==="image"||at.startsWith("image/")?"image-url":"file-url",url:_,mediaType:N}}let re=b.toolCallId??I?.toolCallId,je=j?[j]:[],Te=[];for(let at of je){if(!at||typeof at!="object")continue;let K=at,qe=typeof K.type=="string"?K.type:void 0,we=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Re=null,ke="";if(qe==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;ke=we.length>0?we:"application/octet-stream",Re=`data:${ke};base64,${Ye}`}else if(qe==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else if(qe==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else continue;if(Re)if(qe==="image-url"||ke.startsWith("image/"))Te.push({type:"image",image:Re,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))Te.push({type:"audio",audio:Re,mimeType:ke});else if(ke.startsWith("video/"))Te.push({type:"video",video:Re,mimeType:ke});else{let Ye=ke||"application/octet-stream";Te.push({type:"file",data:Re,mimeType:Ye,filename:Ox(Ye)})}}if(Te.length>0){let at=c(),K=re,we={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${at}`:String(at)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:at,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:ie}};f(we);let Re=h;Re&&(Re.streaming=!1,f(Re)),h=null,L.current=null}}else if(z==="execution_complete"){let P=b.kind??ge;P==="agent"&&ce&&(ce.status=b.success?"complete":"error",ce.completedAt=Ne(b.completedAt),ce.stopReason=b.stopReason);let I=h;I&&(P==="flow"&&I.streaming!==!1?He(I):(I.streaming=!1,f(I)),h=null),M=null,A="",Tt=null,n({type:"status",status:"idle",terminal:!0})}else if(z==="execution_error"){let P=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(z!=="ping"){if(z==="approval_start"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="step_await"&&b.awaitReason==="approval_required"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="approval_complete"){let P=b.approvalId;if(P){let N={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:b.decision??"approved",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};f(N)}}else if(z==="artifact_start"||z==="artifact_delta"||z==="artifact_update"||z==="artifact_complete"){if(z==="artifact_start"){let P=b.artifactType,I=String(b.id),N=typeof b.title=="string"?b.title:void 0,G=b.file,_;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(_={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:I,artifactType:P,title:N,component:typeof b.component=="string"?b.component:void 0,..._?{file:_}:{}});let j=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(xe.set(I,{markdown:"",title:N,file:_,...j?{props:j}:{}}),!Ae.has(I)){Ae.add(I);let re=jo(this.config.features?.artifacts,P),je=typeof b.component=="string"?b.component:void 0,Te={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ws(re,{artifactId:I,title:N,artifactType:P,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};ve.set(I,Te),f(Te)}}else if(z==="artifact_delta"){let P=String(b.id),I=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:P,artDelta:I});let N=xe.get(P);N&&(N.markdown+=I)}else if(z==="artifact_update"){let P=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:P,component:typeof b.component=="string"?b.component:void 0});let I=xe.get(String(b.id));I&&(I.props={...I.props??{},...P})}else if(z==="artifact_complete"){let P=String(b.id);n({type:"artifact_complete",id:P});let I=ve.get(P);if(I){I.streaming=!1;try{let N=JSON.parse(I.rawContent??"{}");if(N.props){N.props.status="complete";let G=xe.get(P);G?.markdown&&(N.props.markdown=G.markdown),G?.file&&(N.props.file=G.file),N.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(N.props.componentProps=G.props)}I.rawContent=JSON.stringify(N)}catch{}xe.delete(P),f(I),ve.delete(P)}}}else if(z==="transcript_insert"){let P=b.message;if(!P||typeof P!="object")continue;let I=String(P.id??`msg-${c()}`),N=P.role,_={id:I,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(_),_.rawContent)try{let re=JSON.parse(_.rawContent)?.props?.artifactId;typeof re=="string"&&Ae.add(re)}catch{}h=null,L.current=null,Je.delete(I),We.delete(I)}else if(z==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let P=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(P)});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(z==="step_error"||z==="dispatch_error"||z==="flow_error"){let P=null;if(b.error instanceof Error)P=b.error;else if(z==="dispatch_error"){let I=b.message??b.error;I!=null&&I!==""&&(P=new Error(String(I)))}else{let I=b.error;typeof I=="string"&&I!==""?P=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(P=new Error(String(I.message??I)))}if(P){n({type:"error",error:P});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}Ke.length=0};;){let{done:R,value:z}=await a.read();if(R)break;l+=s.decode(z,{stream:!0});let b=l.split(`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ea=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},js=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Gs=()=>{let e=Bx();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Ks=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,Gn.parse)(n,Gn.STR|Gn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?qs(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=qs(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},rm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?qs(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?qs(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Gn.parse)(a,Gn.STR|Gn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Xs=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var am="4.12.0";var Ko=am;var Fx="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com";function Ox(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var od=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 Nx(e){switch(e){case"json":return Ks;case"regex-json":return Gs;case"xml":return Xs;default:return js}}var sm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function _x(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=sm(n);if(!sm(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Ea(e);return Ea(t)!==null&&s===null?t:e}var Xo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;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=t.apiUrl??Fx,this.headers={"Content-Type":"application/json","X-Persona-Version":Ko,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Nx(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ar(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let a=Nf(o,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(r)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(od).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...s,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ko},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Js}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?Ff(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let g=0;;g++){if(u=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Js}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let d=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(s,d,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(a,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(od).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(od).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Er(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=R=>{let z=R.reasoning?{...R.reasoning,chunks:[...R.reasoning.chunks]}:void 0,b=R.toolCall?{...R.toolCall,chunks:R.toolCall.chunks?[...R.toolCall.chunks]:void 0}:void 0,P=R.tools?R.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...R,reasoning:z,toolCall:b,tools:P}},g=R=>{if(R.role!=="assistant"||R.variant)return!0;let z=Array.isArray(R.contentParts)&&R.contentParts.length>0,b=typeof R.rawContent=="string"&&R.rawContent.trim()!=="";return typeof R.content=="string"&&R.content.trim()!==""||z||b||!!R.stopReason},f=R=>{g(R)&&n({type:"message",message:u(R)})},h=null,S=null,L={current:null},E={current:null},M=null,A="",w=new Map,T=new Map,H=new Map,C=new Map,B=new Map,F={lastId:null,byStep:new Map},q={lastId:null,byCall:new Map},D=R=>{if(R==null)return null;try{return String(R)}catch{return null}},U=R=>D(R.stepId??R.step_id??R.step??R.parentId??R.flowStepId??R.flow_step_id),se=R=>D(R.callId??R.call_id??R.requestId??R.request_id??R.toolCallId??R.tool_call_id??R.stepId??R.step_id),le=o,Ce=!1,Ie=()=>{if(h)return h;let R,z="",b=M;return!Ce&&le?(R=le,Ce=!0,z=r??""):le&&b?R=`${le}_${b}`:R=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:R,role:"assistant",content:z,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(h),h},ae=(R,z)=>{F.lastId=z,R&&F.byStep.set(R,z)},me=(R,z)=>{let b=R.reasoningId??R.id,P=U(R);if(b){let N=String(b);return ae(P,N),N}if(P){let N=F.byStep.get(P);if(N)return F.lastId=N,N}if(F.lastId&&!z)return F.lastId;if(!z)return null;let I=`reason-${c()}`;return ae(P,I),I},Z=R=>{let z=C.get(R);if(z)return z;let b={id:`reason-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:R,status:"streaming",chunks:[]}};return C.set(R,b),f(b),b},de=(R,z)=>{q.lastId=z,R&&q.byCall.set(R,z)},Y=new Set,ve=new Map,Ae=new Set,xe=new Map,Be=R=>{if(!R)return!1;let z=R.replace(/_+/g,"_").replace(/^_|_$/g,"");return z==="emit_artifact_markdown"||z==="emit_artifact_component"},Oe=(R,z)=>{let b=R.toolId??R.id,P=se(R);if(b){let N=String(b);return de(P,N),N}if(P){let N=q.byCall.get(P);if(N)return q.lastId=N,N}if(q.lastId&&!z)return q.lastId;if(!z)return null;let I=`tool-${c()}`;return de(P,I),I},ze=R=>{let z=B.get(R);if(z)return z;let b={id:`tool-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:R,status:"pending"}};return B.set(R,b),f(b),b},Ne=R=>{if(typeof R=="number"&&Number.isFinite(R))return R;if(typeof R=="string"){let z=Number(R);if(!Number.isNaN(z)&&Number.isFinite(z))return z;let b=Date.parse(R);if(!Number.isNaN(b))return b}return Date.now()},rt=R=>{if(typeof R=="string")return R;if(R==null)return"";try{return JSON.stringify(R)}catch{return String(R)}},Je=new Map,We=new Map,Me=new Map,Qe=(R,z,b)=>{let P=Me.get(R);P||(P=[],Me.set(R,P));let I=0,N=P.length;for(;I<N;){let _=I+N>>>1;P[_].seq<z?I=_+1:N=_}P[I]?.seq===z?P[I]={seq:z,text:b}:P.splice(I,0,{seq:z,text:b});let G="";for(let _=0;_<P.length;_++)G+=P[_].text;return G},cn=(R,z)=>{let b=rt(z),P=We.get(R.id),I=_x(P,b);R.rawContent=I;let N=Je.get(R.id),G=Te=>{let at=R.content??"";Te.trim()!==""&&(at.trim().length===0||Te.startsWith(at)||Te.trimStart().startsWith(at.trim()))&&(R.content=Te)},_=()=>{if(N){let Te=N.close?.();Te instanceof Promise&&Te.catch(()=>{})}Je.delete(R.id),We.delete(R.id),R.streaming=!1,f(R)};if(!N){G(b),_();return}let j=Ea(I);if(j!==null&&j.trim()!==""){G(j),_();return}let re=Te=>{let at=typeof Te=="string"?Te:Te?.text??null;if(at!==null&&at.trim()!=="")return at;let K=N.getExtractedText();return K!==null&&K.trim()!==""?K:b},je;try{je=N.processChunk(I)}catch{G(b),_();return}if(je instanceof Promise){je.then(Te=>{G(re(Te)),_()}).catch(()=>{G(b),_()});return}G(re(je)),_()},Tt=null,yt=(R,z,b,P)=>{R.rawContent=z,Je.has(R.id)||Je.set(R.id,this.createStreamParser());let I=Je.get(R.id),N=z.trim().startsWith("{")||z.trim().startsWith("[");if(N&&We.set(R.id,z),I.__isPlainTextParser===!0){R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R);return}let _=I.processChunk(z);if(_ instanceof Promise)_.then(j=>{let re=typeof j=="string"?j:j?.text??null;re!==null&&re.trim()!==""?(R.content=re,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}).catch(()=>{R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R)});else{let j=typeof _=="string"?_:_?.text??null;j!==null&&j.trim()!==""?(R.content=j,f(R)):!N&&!z.trim().startsWith("<")&&(R.content=P!==void 0?z:R.content+b,We.delete(R.id),Je.delete(R.id),R.rawContent=void 0,f(R))}},He=(R,z)=>{let b=z??R.content;if(b==null||b===""){R.streaming=!1,f(R);return}let I=We.get(R.id)??rt(b);R.rawContent=I;let N=Je.get(R.id),G=null,_=!1;if(N&&(G=N.getExtractedText(),G===null&&(G=Ea(I)),G===null)){let j=N.processChunk(I);j instanceof Promise?(_=!0,j.then(re=>{let je=typeof re=="string"?re:re?.text??null;je!==null&&(R.content=je,R.streaming=!1,Je.delete(R.id),We.delete(R.id),f(R))}).catch(()=>{})):G=typeof j=="string"?j:j?.text??null}if(!_){G!==null&&G.trim()!==""?R.content=G:We.has(R.id)||(R.content=rt(b));let j=Je.get(R.id);if(j){let re=j.close?.();re instanceof Promise&&re.catch(()=>{}),Je.delete(R.id)}We.delete(R.id),R.streaming=!1,f(R)}},fe=(R,z,b)=>{let P=T.get(R);if(P)return P;let I={id:`nested-${z}-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...b?{variant:b}:{},...b==="reasoning"?{reasoning:{id:R,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:z}};return T.set(R,I),f(I),I},Ke=[],Ee,pe=new Map,ie=0,ge="agent",xt=!1,he=null,ce=null,yn=new Map,Q=this.config.iterationDisplay??"separate";for(Ee=()=>{for(let R=0;R<Ke.length;R++){let z=Ke[R].payloadType,b=Ke[R].payload;if(!xt&&ge!=="flow"&&typeof b.stepType=="string"&&(ge="flow"),z==="reasoning_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I),fe(P,I,"reasoning");continue}let N=me(b,!0)??`reason-${c()}`,G=Z(N);G.reasoning=G.reasoning??{id:N,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Ne(b.startedAt??b.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(z==="reasoning_delta"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let _=T.get(P),j=b.reasoningText??b.text??b.delta??"";j&&b.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String(j)),f(_));continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=Z(I);N.reasoning=N.reasoning??{id:I,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Ne(b.startedAt??b.timestamp);let G=b.reasoningText??b.text??b.delta??"";if(G&&b.hidden!==!0){let _=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(_!==void 0){let j=Qe(I,_,String(G));N.reasoning.chunks=[j]}else N.reasoning.chunks.push(String(G))}if(N.reasoning.status=b.done?"complete":"streaming",b.done){N.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let _=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-_)}N.streaming=N.reasoning.status!=="complete",f(N)}else if(z==="reasoning_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)&&T.has(P)){let j=T.get(P);if(j.reasoning){let re=typeof b.text=="string"?b.text:"";re&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(re),j.reasoning.status="complete",j.streaming=!1,f(j)}w.delete(P),T.delete(P);continue}let I=me(b,!1)??me(b,!0)??`reason-${c()}`,N=typeof b.text=="string"?b.text:"";!C.get(I)&&(N||b.scope==="loop")&&Z(I);let G=C.get(I);if(G?.reasoning){(b.scope==="loop"||b.scope==="turn")&&(G.reasoning.scope=b.scope),N&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(N),G.reasoning.status="complete",G.reasoning.completedAt=Ne(b.completedAt??b.timestamp);let j=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-j),G.streaming=!1,f(G)}let _=U(b);_&&F.byStep.delete(_)}else if(z==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof b.iteration=="number"&&(ie=b.iteration);let P=(typeof b.toolCallId=="string"?b.toolCallId:void 0)??Oe(b,!0)??`tool-${c()}`,I=b.toolName??b.name;if(Be(I)){Y.add(P);continue}de(se(b),P);let N=ze(P),G=N.toolCall??{id:P,status:"pending"};G.name=I??G.name,G.status="running",b.parameters!==void 0?G.args=b.parameters:b.args!==void 0&&(G.args=b.args),G.startedAt=G.startedAt??Ne(b.startedAt??b.timestamp),G.completedAt=void 0,G.durationMs=void 0,N.toolCall=G,N.streaming=!0,b.executionId&&(N.agentMetadata={executionId:b.executionId,iteration:b.iteration}),f(N)}else if(z==="tool_output_delta"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P))continue;let I=ze(P),N=I.toolCall??{id:P,status:"running"};N.startedAt=N.startedAt??Ne(b.startedAt??b.timestamp);let G=b.text??b.delta??b.message??"";G&&(N.chunks=N.chunks??[],N.chunks.push(String(G))),N.status="running",I.toolCall=N,I.streaming=!0;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I)}else if(z==="tool_complete"){let P=Oe(b,!1)??Oe(b,!0)??`tool-${c()}`;if(Y.has(P)){Y.delete(P);continue}let I=ze(P),N=I.toolCall??{id:P,status:"running"};N.status="complete",b.result!==void 0&&(N.result=b.result),typeof b.duration=="number"&&(N.duration=b.duration),N.completedAt=Ne(b.completedAt??b.timestamp);let G=b.duration??b.executionTime;if(typeof G=="number")N.durationMs=G;else{let re=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-re)}I.toolCall=N,I.streaming=!1;let _=b.agentContext;(_||b.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:_?.executionId??b.executionId,iteration:_?.iteration??b.iteration}),f(I);let j=se(b);j&&q.byCall.delete(j)}else if(z==="await"&&b.toolName){let P=typeof b.toolCallId=="string"&&b.toolCallId.length>0?b.toolCallId:void 0,I=P??b.toolId??`local-${c()}`,N=ze(I),G=b.toolName,_=b.origin==="webmcp"&&!uo(G)?`webmcp:${G}`:G,j=uo(_),re=N.toolCall??{id:I,status:"pending"};re.name=_,re.args=b.parameters,re.status=j?"running":"complete",re.chunks=re.chunks??[],re.startedAt=re.startedAt??Ne(b.startedAt??b.timestamp??b.awaitedAt),j?(re.completedAt=void 0,re.duration=void 0,re.durationMs=void 0):re.completedAt=re.completedAt??re.startedAt,N.toolCall=re,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:b.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...P?{webMcpToolCallId:P}:{}},f(N)}else if(z==="text_start"){let P=typeof b.id=="string"?b.id:null,I=typeof b.parentToolCallId=="string"&&b.parentToolCallId?b.parentToolCallId:null;if(P&&I){w.set(P,I);continue}let N=h;N&&(ge==="flow"?(He(N),Tt=N):(N.streaming=!1,f(N)),h=null),M=typeof b.id=="string"?b.id:M,A=""}else if(z==="text_delta"){let P=typeof b.id=="string"?b.id:null,I=P?w.get(P):void 0;if(P&&I){let G=typeof b.delta=="string"?b.delta:"",_=(H.get(P)??"")+G;if(H.set(P,_),_.trim()==="")continue;let j=fe(P,I);j.agentMetadata={...j.agentMetadata,executionId:b.executionId,parentToolId:I},yt(j,_,G,void 0);continue}if(M=typeof b.id=="string"?b.id:M,ge==="flow"){let G=typeof b.delta=="string"?b.delta:"";if(A+=G,A.trim()==="")continue;let _=Ie();_.agentMetadata={executionId:b.executionId,iteration:b.iteration},yt(_,A,G,void 0),S=_;continue}let N=Ie();N.content+=b.delta??"",N.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:he??void 0,agentName:ce?.agentName},S=N,f(N)}else if(z==="text_complete"){let P=typeof b.id=="string"?b.id:null;if(P&&w.has(P)){let N=T.get(P);N&&He(N),w.delete(P),H.delete(P),T.delete(P);continue}let I=h;I&&(ge==="flow"?(He(I),Tt=I):((I.content??"")===""&&typeof b.text=="string"&&(I.content=b.text),I.streaming=!1,f(I)),h=null),M=null,A=""}else if(z==="step_complete"){let P=b.stepType,I=b.executionType;if(P==="tool"||I==="context")continue;if(b.success===!1){let N=b.error,G=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let N=Tt;Tt=null;let G=b.stopReason,_=b.result?.response;if(N)G&&(N.stopReason=G),_!=null?cn(N,_):N.streaming!==!1&&(Je.delete(N.id),We.delete(N.id),N.streaming=!1,f(N));else{let j=_!=null&&_!=="";if(j||G){let re=Ie();G&&(re.stopReason=G),j?He(re,_):(re.streaming=!1,f(re))}}continue}}else if(z==="execution_start")ge=b.kind==="flow"?"flow":"agent",xt=!0,ge==="agent"&&(ce={executionId:b.executionId,agentId:b.agentId??"virtual",agentName:b.agentName??"",status:"running",currentIteration:0,maxTurns:b.maxTurns??1,startedAt:Ne(b.startedAt)});else if(z==="turn_start"){let P=typeof b.iteration=="number"?b.iteration:ie;if(P!==ie){if(ce&&(ce.currentIteration=P),Q==="separate"&&P>1){let I=h;I&&(I.streaming=!1,f(I),yn.set(P-1,I),h=null)}ie=P}he=typeof b.id=="string"?b.id:null,S=null}else if(z==="tool_input_delta"){let P=b.toolCallId??q.lastId;if(P){let I=B.get(P);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(b.delta??""),f(I))}}else{if(z==="tool_input_complete")continue;if(z==="turn_complete"){let P=b.stopReason,I=h??S;if(P&&I!==null){let N=b.id;(!N||I.agentMetadata?.turnId===N)&&(I.stopReason=P,f(I))}he===b.id&&(he=null)}else if(z==="media_start"){let P=String(b.id);pe.set(P,{mediaType:typeof b.mediaType=="string"?b.mediaType:void 0,role:typeof b.role=="string"?b.role:void 0,toolCallId:b.toolCallId,parts:[]})}else if(z==="media_delta"){let P=pe.get(String(b.id));P&&typeof b.delta=="string"&&P.parts.push(b.delta)}else if(z==="media_complete"){let P=String(b.id),I=pe.get(P);pe.delete(P);let N=(typeof b.mediaType=="string"?b.mediaType:void 0)??I?.mediaType??"application/octet-stream",G=typeof b.data=="string"?b.data:void 0,_=typeof b.url=="string"?b.url:I&&I.parts.length>0?I.parts.join(""):void 0,j=null;if(G)j={type:"media",data:G,mediaType:N};else if(_){let at=N.toLowerCase();j={type:at==="image"||at.startsWith("image/")?"image-url":"file-url",url:_,mediaType:N}}let re=b.toolCallId??I?.toolCallId,je=j?[j]:[],Te=[];for(let at of je){if(!at||typeof at!="object")continue;let K=at,qe=typeof K.type=="string"?K.type:void 0,we=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",Re=null,ke="";if(qe==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;ke=we.length>0?we:"application/octet-stream",Re=`data:${ke};base64,${Ye}`}else if(qe==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else if(qe==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;ke=we,Re=Ye}else continue;if(Re)if(qe==="image-url"||ke.startsWith("image/"))Te.push({type:"image",image:Re,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))Te.push({type:"audio",audio:Re,mimeType:ke});else if(ke.startsWith("video/"))Te.push({type:"video",video:Re,mimeType:ke});else{let Ye=ke||"application/octet-stream";Te.push({type:"file",data:Re,mimeType:Ye,filename:Ox(Ye)})}}if(Te.length>0){let at=c(),K=re,we={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${at}`:String(at)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:at,agentMetadata:{executionId:b.executionId,iteration:typeof b.iteration=="number"?b.iteration:ie}};f(we);let Re=h;Re&&(Re.streaming=!1,f(Re)),h=null,L.current=null}}else if(z==="execution_complete"){let P=b.kind??ge;P==="agent"&&ce&&(ce.status=b.success?"complete":"error",ce.completedAt=Ne(b.completedAt),ce.stopReason=b.stopReason);let I=h;I&&(P==="flow"&&I.streaming!==!1?He(I):(I.streaming=!1,f(I)),h=null),M=null,A="",Tt=null,n({type:"status",status:"idle",terminal:!0})}else if(z==="execution_error"){let P=typeof b.error=="string"?b.error:b.error?.message??"Execution error";n({type:"error",error:new Error(P)})}else if(z!=="ping"){if(z==="approval_start"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="step_await"&&b.awaitReason==="approval_required"){let P=b.approvalId??`approval-${c()}`,I={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:"pending",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",toolType:b.toolType,description:b.description??`Execute ${b.toolName??"tool"}`,...typeof b.reason=="string"&&b.reason?{reason:b.reason}:{},parameters:b.parameters}};f(I)}else if(z==="approval_complete"){let P=b.approvalId;if(P){let N={id:`approval-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:P,status:b.decision??"approved",agentId:ce?.agentId??"virtual",executionId:b.executionId??ce?.executionId??"",toolName:b.toolName??"",description:b.description??"",resolvedAt:Date.now()}};f(N)}}else if(z==="artifact_start"||z==="artifact_delta"||z==="artifact_update"||z==="artifact_complete"){if(z==="artifact_start"){let P=b.artifactType,I=String(b.id),N=typeof b.title=="string"?b.title:void 0,G=b.file,_;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(_={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:I,artifactType:P,title:N,component:typeof b.component=="string"?b.component:void 0,..._?{file:_}:{}});let j=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?{...b.props}:void 0;if(xe.set(I,{markdown:"",title:N,file:_,...j?{props:j}:{}}),!Ae.has(I)){Ae.add(I);let re=jo(this.config.features?.artifacts,P),je=typeof b.component=="string"?b.component:void 0,Te={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:Ws(re,{artifactId:I,title:N,artifactType:P,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};ve.set(I,Te),f(Te)}}else if(z==="artifact_delta"){let P=String(b.id),I=typeof b.delta=="string"?b.delta:String(b.delta??"");n({type:"artifact_delta",id:P,artDelta:I});let N=xe.get(P);N&&(N.markdown+=I)}else if(z==="artifact_update"){let P=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:P,component:typeof b.component=="string"?b.component:void 0});let I=xe.get(String(b.id));I&&(I.props={...I.props??{},...P})}else if(z==="artifact_complete"){let P=String(b.id);n({type:"artifact_complete",id:P});let I=ve.get(P);if(I){I.streaming=!1;try{let N=JSON.parse(I.rawContent??"{}");if(N.props){N.props.status="complete";let G=xe.get(P);G?.markdown&&(N.props.markdown=G.markdown),G?.file&&(N.props.file=G.file),N.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(N.props.componentProps=G.props)}I.rawContent=JSON.stringify(N)}catch{}xe.delete(P),f(I),ve.delete(P)}}}else if(z==="transcript_insert"){let P=b.message;if(!P||typeof P!="object")continue;let I=String(P.id??`msg-${c()}`),N=P.role,_={id:I,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof P.content=="string"?P.content:"",rawContent:typeof P.rawContent=="string"?P.rawContent:void 0,createdAt:typeof P.createdAt=="string"?P.createdAt:new Date().toISOString(),streaming:P.streaming===!0,...typeof P.variant=="string"?{variant:P.variant}:{},sequence:c()};if(f(_),_.rawContent)try{let re=JSON.parse(_.rawContent)?.props?.artifactId;typeof re=="string"&&Ae.add(re)}catch{}h=null,L.current=null,Je.delete(I),We.delete(I)}else if(z==="error"){if(b.recoverable===!1&&b.error!=null&&b.error!==""){let P=typeof b.error=="string"?b.error:b.error?.message!=null?String(b.error.message):"Execution error";n({type:"error",error:new Error(P)});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(z==="step_error"||z==="dispatch_error"||z==="flow_error"){let P=null;if(b.error instanceof Error)P=b.error;else if(z==="dispatch_error"){let I=b.message??b.error;I!=null&&I!==""&&(P=new Error(String(I)))}else{let I=b.error;typeof I=="string"&&I!==""?P=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(P=new Error(String(I.message??I)))}if(P){n({type:"error",error:P});let I=h;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}Ke.length=0};;){let{done:R,value:z}=await a.read();if(R)break;l+=s.decode(z,{stream:!0});let b=l.split(`
13
13
 
14
14
  `);l=b.pop()??"";for(let P of b){let I=P.split(`
15
15
  `),N="message",G="",_=null;for(let Te of I)Te.startsWith("event:")?N=Te.replace("event:","").trim():Te.startsWith("data:")?G+=Te.replace("data:","").trim():Te.startsWith("id:")&&(_=Te.slice(3).trim());let j=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!G){j();continue}let re;try{re=JSON.parse(G)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let je=N!=="message"?N:re.type??"message";if(this.onSSEEvent?.(je,re),this.parseSSEEvent){L.current=h;let Te=await this.handleCustomSSEEvent(re,n,L,f,c,E);if(L.current&&L.current!==h&&(h=L.current),Te){j();continue}}Ke.push({payloadType:je,payload:re}),Ee(),j()}}Ee()}};function im(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Qs="[Image]";function lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function dm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ys(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function cm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function bo(e){return{type:"text",text:e}}function pm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function um(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function fm(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 mm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ux=["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"],Kn=[...mm,...Ux];function qx(e){return mm.includes(e)||e.startsWith("image/")}function Zs(e){return qx(e.type)}async function gm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Zs(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function hm(e,t=Kn,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 Vx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ym(e,t){let n=Vx(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var ei=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var xm=16e3,zx=24e3,$x=4096,jx=1380533830;function Gx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===jx?new Uint8Array(e,44):new Uint8Array(e)}function Kx(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ka=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(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:xm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ei(zx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Kx(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}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,o,r){let a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor($x,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Gx(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}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,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Jo=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}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 vo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ka(e.runtype);case"browser":if(!Jo.isSupported())throw new Error("Browser speech recognition not supported");return new Jo(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 ti(e){if(e?.type==="custom"&&e.custom)return vo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return vo({type:"runtype",runtype:e.runtype});if(Jo.isSupported())return vo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function La(e){try{return ti(e),!0}catch{return!1}}function Lr(e){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 n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Co=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Lr(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Qo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!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){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function rd(e){if(!e)return"";let t=Xx(e);return bm(t!==null?t:e)}function Xx(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 o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function bm(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`