@runtypelabs/persona 4.3.0 → 4.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/theme-editor-preview.cjs +1 -1
- package/dist/theme-editor-preview.js +1 -1
- package/dist/widget.css +3 -0
- package/package.json +1 -1
- package/src/styles/widget.css +3 -0
package/dist/index.global.js
CHANGED
|
@@ -9,7 +9,7 @@ ${t}`:"")+(e.description?`
|
|
|
9
9
|
${e.description}`:"");return window.confirm(r)},Ly=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)}},Py=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ry=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Iy="agent_",Wy="flow_";function yg(e){return e.startsWith(Iy)?{kind:"agentId",agentId:e}:e.startsWith(Wy)?{kind:"flowId",flowId:e}:null}function bg(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let l=yg(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)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:c(i).payload}}let n=yg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var bn=Sa(Ys(),1);var w=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Mt=(e,t={},...r)=>{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 i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},ss=(...e)=>e.filter(Boolean).join(" ");var ls="ask_user_question",is=8,Ea="data-persona-ask-sheet-for",Ny="Other",Oy="Other\u2026",Cg="Type your own answer here",Sg="Send",_y="Next",Uy="Back",qy="Submit all",Vy="Skip",zy=3,Ll="data-ask-current-index",Pl="data-ask-question-count",Ag="data-ask-answers",Rl="data-ask-grouped",Mg="data-ask-layout",$y=e=>e.layout==="pills"?"pills":"rows",jy=e=>e.getAttribute(Mg)==="pills"?"pills":"rows",wg=!1,Tg=e=>e.replace(/["\\]/g,"\\$&"),Qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ls,Zs=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Yo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,bn.parse)(n,bn.STR|bn.OBJ|bn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ds=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>is&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${is}.`)),t.slice(0,is)},Gy=e=>{var t;return(t=ds(e)[0])!=null?t:null},Ky=(e,t)=>{var r;return(r=ds(e)[t])!=null?r:null},Eg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},kg=(e,t,r)=>{if(e!=="rows")return null;let o=w("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=w("span","persona-ask-row-check");o.appendChild(n)}else{let n=w("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Xy=(e,t,r,o)=>{let a=w("button",r==="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),r==="rows"){let s=w("span","persona-ask-row-content"),i=w("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=w("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let c=kg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Jy=e=>{let r=w("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 r.setAttribute("aria-hidden","true"),r},Qy=(e,t,r,o)=>{var p,f,u;let a=w("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!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<zy;m++)a.appendChild(Jy(o));return a}if(c.forEach((m,x)=>{a.appendChild(Xy(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Ny:Oy;if(o==="rows"){let x=w("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let b=w("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(p=t.freeTextPlaceholder)!=null?p:Cg,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),b.appendChild(L),x.appendChild(b);let E=kg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=w("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=t.freeTextLabel)!=null?u:m,a.appendChild(x)}}return a},Lg=(e,t)=>{var a,s;let o=w("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 n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Cg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=w("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Sg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Yy=e=>{var o;let t=w("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=w("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Sg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Zy=(e,t,r)=>{var l,p,f,u;let o=w("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=w("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=r.backLabel)!=null?l:Uy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=w("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=w("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:Vy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=w("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(f=r.submitAllLabel)!=null?f:qy:(u=r.nextLabel)!=null?u:_y,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},Kn=e=>{let t=e.getAttribute(Ag);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Pg=(e,t)=>{e.setAttribute(Ag,JSON.stringify(t))},co=e=>{var r;let t=Number((r=e.getAttribute(Ll))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},eb=(e,t)=>{e.setAttribute(Ll,String(Math.max(0,Math.floor(t))))},ka=e=>{var r;let t=Number((r=e.getAttribute(Pl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vn=e=>e.getAttribute(Rl)==="true",tb=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},rb=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},ei=(e,t)=>{let{payload:r}=Yo(t),o=ds(r),n=Kn(e),a={},s=new Set;return o.forEach((i,c)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,c)&&(a[l]=n[c]))}),a},Rg=e=>{let t=Kn(e),r=co(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var f;let l=(f=c.getAttribute("data-option-label"))!=null?f:"",p=n.has(l);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var l;return(l=c.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Ig=e=>{if(!vn(e))return;let t=Kn(e),r=co(e),o=t[r],n=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=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Il=(e,t,r)=>{let o=Zs(r),n=jy(e),{payload:a,complete:s}=Yo(t),i=vn(e),c=co(e),l=ka(e),p=i?Ky(a,c):Gy(a),f=!!(p!=null&&p.multiSelect),u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${c+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=Qy(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Lg(o,n))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!L?e.appendChild(Yy(o)):(!f||i)&&L&&L.remove(),e.setAttribute("data-multi-select",f?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Zy(c,l,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();Rg(e),Ig(e)},ob=(e,t,r)=>{let o=Zs(t),n=$y(o),a=e.toolCall.id,s=ds(r),i=Math.max(1,s.length),c=i>1,l=tb(e,s),p=c?rb(e,i):0,f=w("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Ea,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Pl,String(i)),f.setAttribute(Ll,String(p)),f.setAttribute(Rl,c?"true":"false"),f.setAttribute(Mg,n),Pg(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Eg(f,o);let u=w("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=w("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let x=w("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),f.appendChild(u);let L=w("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),f.appendChild(L),n!=="rows"&&f.appendChild(Lg(o,n)),Il(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nb=(e,t,r)=>{let{payload:o}=Yo(t),n=Math.max(1,ds(o).length);n>ka(e)&&(e.setAttribute(Pl,String(n)),n>1&&!vn(e)&&e.setAttribute(Rl,"true")),Il(e,t,r)},Wg=(e,t)=>{let r=w("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=Zs(t);Eg(r,o);let n=w("span","persona-ask-stub-label"),{complete:a}=Yo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},La=(e,t,r)=>{if(!r||!Qo(e)||Zs(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ea}]`).forEach(l=>{l.getAttribute(Ea)!==n&&l.remove()});let s=r.querySelector(`[${Ea}="${Tg(n)}"]`);if(s){nb(s,e,t);return}let{payload:i}=Yo(e),c=ob(e,t,i);r.appendChild(c)},wn=(e,t)=>{if(!e)return;let r=t?`[${Ea}="${Tg(t)}"]`:`[${Ea}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Wl=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),Cn=(e,t)=>{let r=Kn(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Pg(e,r),Rg(e),Ig(e)},ti=(e,t,r,o)=>{let n=ka(e),a=Math.max(0,Math.min(n-1,o));eb(e,a),Il(e,t,r)};var wo="suggest_replies";var Hl={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},ri={name:wo,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:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},Bl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),cs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===wo},Dl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},oi=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!cs(o))continue;let n=Dl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Hg=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Fl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:is,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},Nl={name:ls,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:Fl,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(Nl),Hg(e)&&t.push(ri),t};var Zo=Sa(Ys(),1),ni=e=>e.replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Sn=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)}},ab=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Bg=e=>e.status==="complete"?ab(e):e.status==="pending"?"Waiting":"",sb=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Dg=e=>e.status==="complete"?sb(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},fs=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ai(t)},si=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ai(t)},Ol=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ii=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&us(o,r.slice(a,s.index),[]),s[1]!==void 0?us(o,s[1],["bold"]):s[2]!==void 0?us(o,s[2],["italic"]):s[3]!==void 0&&us(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&us(o,r.slice(a),[]),o},us=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ib=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);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*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
12
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ib();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ci=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ni(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ni(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Fg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ni(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<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{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 Ng="4.3.0";var Xn=Ng;var db="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function cb(e){var a,s;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 n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _l=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 pb(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ub(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Og(r);if(!Og(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;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=(r=t.apiUrl)!=null?r:db,this.headers={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:pb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ta(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=bg(o,n);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){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={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":Xn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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 n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){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:r})}async submitCSATFeedback(t,r){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:r})}async submitNPSFeedback(t,r){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:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(_l).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,m=!!(u&&u.length>0),x=m?xg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(_l).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...ps(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(_l).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...ps(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Ht,Qt,_o,So;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Ae=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Ie=P.tools?P.tools.map(Ee=>({...Ee,chunks:Ee.chunks?[...Ee.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Ae,tools:Ie}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Ae=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Ae||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},D=P=>{var ee,Ae,Ie,Ee,He;return I((He=(Ee=(Ie=(Ae=(ee=P.stepId)!=null?ee:P.step_id)!=null?Ae:P.step)!=null?Ie:P.parentId)!=null?Ee:P.flowStepId)!=null?He:P.flow_step_id)},O=P=>{var ee,Ae,Ie,Ee,He,Ge,st;return I((st=(Ge=(He=(Ee=(Ie=(Ae=(ee=P.callId)!=null?ee:P.call_id)!=null?Ae:P.requestId)!=null?Ie:P.request_id)!=null?Ee:P.toolCallId)!=null?He:P.tool_call_id)!=null?Ge:P.stepId)!=null?st:P.step_id)},J=o,me=!1,ce=()=>{if(m)return m;let P,ee=E;return!me&&J?(P=J,me=!0):J&&ee?P=`${J}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Se=(P,ee)=>{var He;let Ae=(He=P.reasoningId)!=null?He:P.id,Ie=D(P);if(Ae){let Ge=String(Ae);return te(Ie,Ge),Ge}if(Ie){let Ge=W.byStep.get(Ie);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let Ee=`reason-${l()}`;return te(Ie,Ee),Ee},We=P=>{let ee=v.get(P);if(ee)return ee;let Ae={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Ae),u(Ae),Ae},de=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},ve=new Set,se=new Map,ie=new Set,pe=new Map,Ve=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},_e=(P,ee)=>{var He;let Ae=(He=P.toolId)!=null?He:P.id,Ie=O(P);if(Ae){let Ge=String(Ae);return de(Ie,Ge),Ge}if(Ie){let Ge=H.byCall.get(Ie);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let Ee=`tool-${l()}`;return de(Ie,Ee),Ee},G=P=>{let ee=M.get(P);if(ee)return ee;let Ae={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Ae),u(Ae),Ae},K=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Ae=Date.parse(P);if(!Number.isNaN(Ae))return Ae}return Date.now()},Me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Q=new Map,le=new Map,Re=new Map,rt=(P,ee,Ae)=>{var st;let Ie=Re.get(P);Ie||(Ie=[],Re.set(P,Ie));let Ee=0,He=Ie.length;for(;Ee<He;){let Lt=Ee+He>>>1;Ie[Lt].seq<ee?Ee=Lt+1:He=Lt}((st=Ie[Ee])==null?void 0:st.seq)===ee?Ie[Ee]={seq:ee,text:Ae}:Ie.splice(Ee,0,{seq:ee,text:Ae});let Ge="";for(let Lt=0;Lt<Ie.length;Lt++)Ge+=Ie[Lt].text;return Ge},vt=(P,ee)=>{let Ae=Me(ee),Ie=le.get(P.id),Ee=ub(Ie,Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=Y=>{var it;let Ce=(it=P.content)!=null?it:"";Y.trim()!==""&&(Ce.trim().length===0||Y.startsWith(Ce)||Y.trimStart().startsWith(Ce.trim()))&&(P.content=Y)},st=()=>{var Y;if(He){let Ce=(Y=He.close)==null?void 0:Y.call(He);Ce instanceof Promise&&Ce.catch(()=>{})}Q.delete(P.id),le.delete(P.id),P.streaming=!1,u(P)};if(!He){Ge(Ae),st();return}let Lt=ms(Ee);if(Lt!==null&&Lt.trim()!==""){Ge(Lt),st();return}let xt=Y=>{var Je;let Ce=typeof Y=="string"?Y:(Je=Y==null?void 0:Y.text)!=null?Je:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let it=He.getExtractedText();return it!==null&&it.trim()!==""?it:Ae},F;try{F=He.processChunk(Ee)}catch{Ge(Ae),st();return}if(F instanceof Promise){F.then(Y=>{Ge(xt(Y)),st()}).catch(()=>{Ge(Ae),st()});return}Ge(xt(F)),st()},Ut=null,jt=(P,ee,Ae,Ie)=>{var Lt;P.rawContent=ee,Q.has(P.id)||Q.set(P.id,this.createStreamParser());let Ee=Q.get(P.id),He=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(He&&le.set(P.id,ee),Ee.__isPlainTextParser===!0){P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P);return}let st=Ee.processChunk(ee);if(st instanceof Promise)st.then(xt=>{var Y;let F=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;F!==null&&F.trim()!==""?(P.content=F,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P)});else{let xt=typeof st=="string"?st:(Lt=st==null?void 0:st.text)!=null?Lt:null;xt!==null&&xt.trim()!==""?(P.content=xt,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}},at=(P,ee)=>{var Lt,xt;let Ae=ee!=null?ee:P.content;if(Ae==null||Ae===""){P.streaming=!1,u(P);return}let Ie=le.get(P.id),Ee=Ie!=null?Ie:Me(Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=null,st=!1;if(He&&(Ge=He.getExtractedText(),Ge===null&&(Ge=ms(Ee)),Ge===null)){let F=He.processChunk(Ee);F instanceof Promise?(st=!0,F.then(Y=>{var it;let Ce=typeof Y=="string"?Y:(it=Y==null?void 0:Y.text)!=null?it:null;Ce!==null&&(P.content=Ce,P.streaming=!1,Q.delete(P.id),le.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof F=="string"?F:(Lt=F==null?void 0:F.text)!=null?Lt:null}if(!st){Ge!==null&&Ge.trim()!==""?P.content=Ge:le.has(P.id)||(P.content=Me(Ae));let F=Q.get(P.id);if(F){let Y=(xt=F.close)==null?void 0:xt.call(F);Y instanceof Promise&&Y.catch(()=>{}),Q.delete(P.id)}le.delete(P.id),P.streaming=!1,u(P)}},Ne=(P,ee,Ae)=>{let Ie=y.get(P);if(Ie)return Ie;let Ee={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ae?{variant:Ae}:{},...Ae==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,Ee),u(Ee),Ee},j=[],$e,ze=new Map,ye=0,we="agent",Ze=!1,Nt=null,re=null,Oe=new Map,xr=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for($e=()=>{var P,ee,Ae,Ie,Ee,He,Ge,st,Lt,xt,F,Y,Ce,it,Je,qt,yr,yt,bt,Pt,wt,pr,Ot,_r,Tr,Er,wr,kr,uo,Ct,Ao,Mo,Uo,fo,pt,Rn,To,In,Br,da,nn,qo,an,sn,Wn,Hn,ln,ht,Ur,qr,Lr,St,to,ro,Vr,dn,Vo,cn,zr,Rt,Pr,oo,pn,zo,un,he,Dr,Eo,ut,ar,sr,ko,$a,$o,Bn,Lo,q,ca,Po,Ro,jo,Io,mo,pa,Fs,$r,jr,go,ho,Dn,Go,Cr,Wo,ua,Fn,fa,Ns,ma,Os,ga,ct,ja,no,Fr,_s;for(let ha=0;ha<j.length;ha++){let Ye=j[ha].payloadType,k=j[ha].payload;if(!Ze&&we!=="flow"&&typeof k.stepType=="string"&&(we="flow"),Ye==="reasoning_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V),Ne($,V,"reasoning");continue}let X=(P=Se(k,!0))!=null?P:`reason-${l()}`,ge=We(X);ge.reasoning=(ee=ge.reasoning)!=null?ee:{id:X,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Ie=ge.reasoning.startedAt)!=null?Ie:K((Ae=k.startedAt)!=null?Ae:k.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),ge.streaming=!0,ge.reasoning.status="streaming",u(ge)}else if(Ye==="reasoning_delta"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let De=y.get($),ft=(Ge=(He=(Ee=k.reasoningText)!=null?Ee:k.text)!=null?He:k.delta)!=null?Ge:"";ft&&k.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(ft)),u(De));continue}let V=(Lt=(st=Se(k,!1))!=null?st:Se(k,!0))!=null?Lt:`reason-${l()}`,X=We(V);X.reasoning=(xt=X.reasoning)!=null?xt:{id:V,status:"streaming",chunks:[]},X.reasoning.startedAt=(Y=X.reasoning.startedAt)!=null?Y:K((F=k.startedAt)!=null?F:k.timestamp);let ge=(Je=(it=(Ce=k.reasoningText)!=null?Ce:k.text)!=null?it:k.delta)!=null?Je:"";if(ge&&k.hidden!==!0){let De=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(De!==void 0){let ft=rt(V,De,String(ge));X.reasoning.chunks=[ft]}else X.reasoning.chunks.push(String(ge))}if(X.reasoning.status=k.done?"complete":"streaming",k.done){X.reasoning.completedAt=K((qt=k.completedAt)!=null?qt:k.timestamp);let De=(yr=X.reasoning.startedAt)!=null?yr:Date.now();X.reasoning.durationMs=Math.max(0,((yt=X.reasoning.completedAt)!=null?yt:Date.now())-De)}X.streaming=X.reasoning.status!=="complete",u(X)}else if(Ye==="reasoning_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let ft=y.get($);if(ft.reasoning){let ot=typeof k.text=="string"?k.text:"";ot&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(ot),ft.reasoning.status="complete",ft.streaming=!1,u(ft)}T.delete($),y.delete($);continue}let V=(Pt=(bt=Se(k,!1))!=null?bt:Se(k,!0))!=null?Pt:`reason-${l()}`,X=typeof k.text=="string"?k.text:"";!v.get(V)&&(X||k.scope==="loop")&&We(V);let ge=v.get(V);if(ge!=null&&ge.reasoning){(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),X&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(X),ge.reasoning.status="complete",ge.reasoning.completedAt=K((wt=k.completedAt)!=null?wt:k.timestamp);let ft=(pr=ge.reasoning.startedAt)!=null?pr:Date.now();ge.reasoning.durationMs=Math.max(0,((Ot=ge.reasoning.completedAt)!=null?Ot:Date.now())-ft),ge.streaming=!1,u(ge)}let De=D(k);De&&W.byStep.delete(De)}else if(Ye==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ye=k.iteration);let $=(Tr=(_r=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?_r:_e(k,!0))!=null?Tr:`tool-${l()}`,V=(Er=k.toolName)!=null?Er:k.name;if(Ve(V)){ve.add($);continue}de(O(k),$);let X=G($),ge=(wr=X.toolCall)!=null?wr:{id:$,status:"pending"};ge.name=V!=null?V:ge.name,ge.status="running",k.parameters!==void 0?ge.args=k.parameters:k.args!==void 0&&(ge.args=k.args),ge.startedAt=(uo=ge.startedAt)!=null?uo:K((kr=k.startedAt)!=null?kr:k.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,X.toolCall=ge,X.streaming=!0,k.executionId&&(X.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(X)}else if(Ye==="tool_output_delta"){let $=(Ao=(Ct=_e(k,!1))!=null?Ct:_e(k,!0))!=null?Ao:`tool-${l()}`;if(ve.has($))continue;let V=G($),X=(Mo=V.toolCall)!=null?Mo:{id:$,status:"running"};X.startedAt=(fo=X.startedAt)!=null?fo:K((Uo=k.startedAt)!=null?Uo:k.timestamp);let ge=(To=(Rn=(pt=k.text)!=null?pt:k.delta)!=null?Rn:k.message)!=null?To:"";ge&&(X.chunks=(In=X.chunks)!=null?In:[],X.chunks.push(String(ge))),X.status="running",V.toolCall=X,V.streaming=!0;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(nn=V.agentMetadata)!=null?nn:{executionId:(Br=De==null?void 0:De.executionId)!=null?Br:k.executionId,iteration:(da=De==null?void 0:De.iteration)!=null?da:k.iteration}),u(V)}else if(Ye==="tool_complete"){let $=(an=(qo=_e(k,!1))!=null?qo:_e(k,!0))!=null?an:`tool-${l()}`;if(ve.has($)){ve.delete($);continue}let V=G($),X=(sn=V.toolCall)!=null?sn:{id:$,status:"running"};X.status="complete",k.result!==void 0&&(X.result=k.result),typeof k.duration=="number"&&(X.duration=k.duration),X.completedAt=K((Wn=k.completedAt)!=null?Wn:k.timestamp);let ge=(Hn=k.duration)!=null?Hn:k.executionTime;if(typeof ge=="number")X.durationMs=ge;else{let ot=(ln=X.startedAt)!=null?ln:Date.now();X.durationMs=Math.max(0,((ht=X.completedAt)!=null?ht:Date.now())-ot)}V.toolCall=X,V.streaming=!1;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(Lr=V.agentMetadata)!=null?Lr:{executionId:(Ur=De==null?void 0:De.executionId)!=null?Ur:k.executionId,iteration:(qr=De==null?void 0:De.iteration)!=null?qr:k.iteration}),u(V);let ft=O(k);ft&&H.byCall.delete(ft)}else if(Ye==="await"&&k.toolName){let $=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(St=$!=null?$:k.toolId)!=null?St:`local-${l()}`,X=G(V),ge=k.toolName,De=k.origin==="webmcp"&&!yn(ge)?`webmcp:${ge}`:ge,ft=yn(De),ot=(to=X.toolCall)!=null?to:{id:V,status:"pending"};ot.name=De,ot.args=k.parameters,ot.status=ft?"running":"complete",ot.chunks=(ro=ot.chunks)!=null?ro:[],ot.startedAt=(Vo=ot.startedAt)!=null?Vo:K((dn=(Vr=k.startedAt)!=null?Vr:k.timestamp)!=null?dn:k.awaitedAt),ft?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(cn=ot.completedAt)!=null?cn:ot.startedAt,X.toolCall=ot,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=k.executionId)!=null?Rt:(zr=X.agentMetadata)==null?void 0:zr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(X)}else if(Ye==="text_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V);continue}let X=m;X&&(we==="flow"?(at(X),Ut=X):(X.streaming=!1,u(X)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ye==="text_delta"){let $=typeof k.id=="string"?k.id:null,V=$?T.get($):void 0;if($&&V){let ge=typeof k.delta=="string"?k.delta:"",De=((Pr=S.get($))!=null?Pr:"")+ge;if(S.set($,De),De.trim()==="")continue;let ft=Ne($,V);ft.agentMetadata={...ft.agentMetadata,executionId:k.executionId,parentToolId:V},jt(ft,De,ge,void 0);continue}if(E=typeof k.id=="string"?k.id:E,we==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(A+=ge,A.trim()==="")continue;let De=ce();De.agentMetadata={executionId:k.executionId,iteration:k.iteration},jt(De,A,ge,void 0),x=De;continue}let X=ce();X.content+=(oo=k.delta)!=null?oo:"",X.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Nt!=null?Nt:void 0,agentName:re==null?void 0:re.agentName},x=X,u(X)}else if(Ye==="text_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)){let X=y.get($);X&&at(X),T.delete($),S.delete($),y.delete($);continue}let V=m;V&&(we==="flow"?(at(V),Ut=V):(((pn=V.content)!=null?pn:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(Ye==="step_complete"){let $=k.stepType,V=k.executionType;if($==="tool"||V==="context")continue;if(k.success===!1){let X=k.error,ge=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((zo=X.message)!=null?zo:"Step failed"):"Step failed";r({type:"error",error:new Error(ge)});let De=m;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let X=Ut;Ut=null;let ge=k.stopReason,De=(un=k.result)==null?void 0:un.response;if(X)ge&&(X.stopReason=ge),De!=null?vt(X,De):X.streaming!==!1&&(Q.delete(X.id),le.delete(X.id),X.streaming=!1,u(X));else{let ft=De!=null&&De!=="";if(ft||ge){let ot=ce();ge&&(ot.stopReason=ge),ft?at(ot,De):(ot.streaming=!1,u(ot))}}continue}}else if(Ye==="execution_start")we=k.kind==="flow"?"flow":"agent",Ze=!0,we==="agent"&&(re={executionId:k.executionId,agentId:(he=k.agentId)!=null?he:"virtual",agentName:(Dr=k.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(Eo=k.maxTurns)!=null?Eo:1,startedAt:K(k.startedAt)});else if(Ye==="turn_start"){let $=typeof k.iteration=="number"?k.iteration:ye;if($!==ye){if(re&&(re.currentIteration=$),xr==="separate"&&$>1){let V=m;V&&(V.streaming=!1,u(V),Oe.set($-1,V),m=null)}ye=$}Nt=typeof k.id=="string"?k.id:null,x=null}else if(Ye==="tool_input_delta"){let $=(ut=k.toolCallId)!=null?ut:H.lastId;if($){let V=M.get($);V!=null&&V.toolCall&&(V.toolCall.chunks=(ar=V.toolCall.chunks)!=null?ar:[],V.toolCall.chunks.push((sr=k.delta)!=null?sr:""),u(V))}}else{if(Ye==="tool_input_complete")continue;if(Ye==="turn_complete"){let $=k.stopReason,V=m!=null?m:x;if($&&V!==null){let X=k.id;(!X||((ko=V.agentMetadata)==null?void 0:ko.turnId)===X)&&(V.stopReason=$,u(V))}Nt===k.id&&(Nt=null)}else if(Ye==="media_start"){let $=String(k.id);ze.set($,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ye==="media_delta"){let $=ze.get(String(k.id));$&&typeof k.delta=="string"&&$.parts.push(k.delta)}else if(Ye==="media_complete"){let $=String(k.id),V=ze.get($);ze.delete($);let X=($o=($a=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?$a:V==null?void 0:V.mediaType)!=null?$o:"application/octet-stream",ge=typeof k.data=="string"?k.data:void 0,De=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ft=null;if(ge)ft={type:"media",data:ge,mediaType:X};else if(De){let ur=X.toLowerCase();ft={type:ur==="image"||ur.startsWith("image/")?"image-url":"file-url",url:De,mediaType:X}}let ot=(Bn=k.toolCallId)!=null?Bn:V==null?void 0:V.toolCallId,Ga=ft?[ft]:[],Nr=[];for(let ur of Ga){if(!ur||typeof ur!="object")continue;let fr=ur,Nn=typeof fr.type=="string"?fr.type:void 0,Ko=typeof fr.mediaType=="string"?fr.mediaType.toLowerCase():"",Rr=null,br="";if(Nn==="media"){let Gr=typeof fr.data=="string"?fr.data:void 0;if(!Gr)continue;br=Ko.length>0?Ko:"application/octet-stream",Rr=`data:${br};base64,${Gr}`}else if(Nn==="image-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else if(Nn==="file-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else continue;if(Rr)if(Nn==="image-url"||br.startsWith("image/"))Nr.push({type:"image",image:Rr,...br.includes("/")?{mimeType:br}:{}});else if(br.startsWith("audio/"))Nr.push({type:"audio",audio:Rr,mimeType:br});else if(br.startsWith("video/"))Nr.push({type:"video",video:Rr,mimeType:br});else{let Gr=br||"application/octet-stream";Nr.push({type:"file",data:Rr,mimeType:Gr,filename:cb(Gr)})}}if(Nr.length>0){let ur=l(),fr=ot,Ko={id:`agent-media-${typeof fr=="string"&&fr.length>0?`${fr}-${ur}`:String(ur)}`,role:"assistant",content:"",contentParts:Nr,createdAt:new Date().toISOString(),streaming:!1,sequence:ur,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ye}};u(Ko);let Rr=m;Rr&&(Rr.streaming=!1,u(Rr)),m=null,b.current=null}}else if(Ye==="execution_complete"){let $=(Lo=k.kind)!=null?Lo:we;$==="agent"&&re&&(re.status=k.success?"complete":"error",re.completedAt=K(k.completedAt),re.stopReason=k.stopReason);let V=m;V&&($==="flow"&&V.streaming!==!1?at(V):(V.streaming=!1,u(V)),m=null),E=null,A="",Ut=null,r({type:"status",status:"idle"})}else if(Ye==="execution_error"){let $=typeof k.error=="string"?k.error:(ca=(q=k.error)==null?void 0:q.message)!=null?ca:"Execution error";r({type:"error",error:new Error($)})}else if(Ye!=="ping"){if(Ye==="approval_start"){let $=(Po=k.approvalId)!=null?Po:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ro=re==null?void 0:re.agentId)!=null?Ro:"virtual",executionId:(Io=(jo=k.executionId)!=null?jo:re==null?void 0:re.executionId)!=null?Io:"",toolName:(mo=k.toolName)!=null?mo:"",toolType:k.toolType,description:(Fs=k.description)!=null?Fs:`Execute ${(pa=k.toolName)!=null?pa:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let $=($r=k.approvalId)!=null?$r:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(jr=re==null?void 0:re.agentId)!=null?jr:"virtual",executionId:(ho=(go=k.executionId)!=null?go:re==null?void 0:re.executionId)!=null?ho:"",toolName:(Dn=k.toolName)!=null?Dn:"",toolType:k.toolType,description:(Cr=k.description)!=null?Cr:`Execute ${(Go=k.toolName)!=null?Go:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="approval_complete"){let $=k.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Wo=k.decision)!=null?Wo:"approved",agentId:(ua=re==null?void 0:re.agentId)!=null?ua:"virtual",executionId:(fa=(Fn=k.executionId)!=null?Fn:re==null?void 0:re.executionId)!=null?fa:"",toolName:(Ns=k.toolName)!=null?Ns:"",description:(ma=k.description)!=null?ma:"",resolvedAt:Date.now()}};u(X)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let $=k.artifactType,V=String(k.id),X=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:$,title:X,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:X}),!ie.has(V)){ie.add(V);let ge={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:X,artifactType:$,status:"streaming"}})};se.set(V,ge),u(ge)}}else if(Ye==="artifact_delta"){let $=String(k.id),V=typeof k.delta=="string"?k.delta:String((Os=k.delta)!=null?Os:"");r({type:"artifact_delta",id:$,artDelta:V});let X=pe.get($);X&&(X.markdown+=V)}else if(Ye==="artifact_update"){let $=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:$,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let $=String(k.id);r({type:"artifact_complete",id:$});let V=se.get($);if(V){V.streaming=!1;try{let X=JSON.parse((ga=V.rawContent)!=null?ga:"{}");if(X.props){X.props.status="complete";let ge=pe.get($);ge!=null&&ge.markdown&&(X.props.markdown=ge.markdown)}V.rawContent=JSON.stringify(X)}catch{}pe.delete($),u(V),se.delete($)}}}else if(Ye==="transcript_insert"){let $=k.message;if(!$||typeof $!="object")continue;let V=String((ct=$.id)!=null?ct:`msg-${l()}`),X=$.role,De={id:V,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(u(De),De.rawContent)try{let ft=JSON.parse(De.rawContent),ot=(ja=ft==null?void 0:ft.props)==null?void 0:ja.artifactId;typeof ot=="string"&&ie.add(ot)}catch{}m=null,b.current=null,Q.delete(V),le.delete(V)}else if(Ye==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let $=typeof k.error=="string"?k.error:((no=k.error)==null?void 0:no.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error($)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let $=null;if(k.error instanceof Error)$=k.error;else if(Ye==="dispatch_error"){let V=(Fr=k.message)!=null?Fr:k.error;V!=null&&V!==""&&($=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?$=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&($=new Error(String((_s=V.message)!=null?_s:V)))}if($){r({type:"error",error:$});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}j.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Ae=s.split(`
|
|
12
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ib();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ci=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ni(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ni(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Fg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ni(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<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{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 Ng="4.3.1";var Xn=Ng;var db="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function cb(e){var a,s;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 n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _l=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 pb(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ub(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Og(r);if(!Og(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;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=(r=t.apiUrl)!=null?r:db,this.headers={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:pb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ta(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=bg(o,n);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){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={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":Xn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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 n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){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:r})}async submitCSATFeedback(t,r){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:r})}async submitNPSFeedback(t,r){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:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(_l).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,m=!!(u&&u.length>0),x=m?xg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(_l).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...ps(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(_l).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...ps(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Ht,Qt,_o,So;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Ae=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Ie=P.tools?P.tools.map(Ee=>({...Ee,chunks:Ee.chunks?[...Ee.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Ae,tools:Ie}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Ae=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Ae||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},D=P=>{var ee,Ae,Ie,Ee,He;return I((He=(Ee=(Ie=(Ae=(ee=P.stepId)!=null?ee:P.step_id)!=null?Ae:P.step)!=null?Ie:P.parentId)!=null?Ee:P.flowStepId)!=null?He:P.flow_step_id)},O=P=>{var ee,Ae,Ie,Ee,He,Ge,st;return I((st=(Ge=(He=(Ee=(Ie=(Ae=(ee=P.callId)!=null?ee:P.call_id)!=null?Ae:P.requestId)!=null?Ie:P.request_id)!=null?Ee:P.toolCallId)!=null?He:P.tool_call_id)!=null?Ge:P.stepId)!=null?st:P.step_id)},J=o,me=!1,ce=()=>{if(m)return m;let P,ee=E;return!me&&J?(P=J,me=!0):J&&ee?P=`${J}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Se=(P,ee)=>{var He;let Ae=(He=P.reasoningId)!=null?He:P.id,Ie=D(P);if(Ae){let Ge=String(Ae);return te(Ie,Ge),Ge}if(Ie){let Ge=W.byStep.get(Ie);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let Ee=`reason-${l()}`;return te(Ie,Ee),Ee},We=P=>{let ee=v.get(P);if(ee)return ee;let Ae={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Ae),u(Ae),Ae},de=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},ve=new Set,se=new Map,ie=new Set,pe=new Map,Ve=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},_e=(P,ee)=>{var He;let Ae=(He=P.toolId)!=null?He:P.id,Ie=O(P);if(Ae){let Ge=String(Ae);return de(Ie,Ge),Ge}if(Ie){let Ge=H.byCall.get(Ie);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let Ee=`tool-${l()}`;return de(Ie,Ee),Ee},G=P=>{let ee=M.get(P);if(ee)return ee;let Ae={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Ae),u(Ae),Ae},K=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Ae=Date.parse(P);if(!Number.isNaN(Ae))return Ae}return Date.now()},Me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Q=new Map,le=new Map,Re=new Map,rt=(P,ee,Ae)=>{var st;let Ie=Re.get(P);Ie||(Ie=[],Re.set(P,Ie));let Ee=0,He=Ie.length;for(;Ee<He;){let Lt=Ee+He>>>1;Ie[Lt].seq<ee?Ee=Lt+1:He=Lt}((st=Ie[Ee])==null?void 0:st.seq)===ee?Ie[Ee]={seq:ee,text:Ae}:Ie.splice(Ee,0,{seq:ee,text:Ae});let Ge="";for(let Lt=0;Lt<Ie.length;Lt++)Ge+=Ie[Lt].text;return Ge},vt=(P,ee)=>{let Ae=Me(ee),Ie=le.get(P.id),Ee=ub(Ie,Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=Y=>{var it;let Ce=(it=P.content)!=null?it:"";Y.trim()!==""&&(Ce.trim().length===0||Y.startsWith(Ce)||Y.trimStart().startsWith(Ce.trim()))&&(P.content=Y)},st=()=>{var Y;if(He){let Ce=(Y=He.close)==null?void 0:Y.call(He);Ce instanceof Promise&&Ce.catch(()=>{})}Q.delete(P.id),le.delete(P.id),P.streaming=!1,u(P)};if(!He){Ge(Ae),st();return}let Lt=ms(Ee);if(Lt!==null&&Lt.trim()!==""){Ge(Lt),st();return}let xt=Y=>{var Je;let Ce=typeof Y=="string"?Y:(Je=Y==null?void 0:Y.text)!=null?Je:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let it=He.getExtractedText();return it!==null&&it.trim()!==""?it:Ae},F;try{F=He.processChunk(Ee)}catch{Ge(Ae),st();return}if(F instanceof Promise){F.then(Y=>{Ge(xt(Y)),st()}).catch(()=>{Ge(Ae),st()});return}Ge(xt(F)),st()},Ut=null,jt=(P,ee,Ae,Ie)=>{var Lt;P.rawContent=ee,Q.has(P.id)||Q.set(P.id,this.createStreamParser());let Ee=Q.get(P.id),He=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(He&&le.set(P.id,ee),Ee.__isPlainTextParser===!0){P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P);return}let st=Ee.processChunk(ee);if(st instanceof Promise)st.then(xt=>{var Y;let F=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;F!==null&&F.trim()!==""?(P.content=F,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P)});else{let xt=typeof st=="string"?st:(Lt=st==null?void 0:st.text)!=null?Lt:null;xt!==null&&xt.trim()!==""?(P.content=xt,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}},at=(P,ee)=>{var Lt,xt;let Ae=ee!=null?ee:P.content;if(Ae==null||Ae===""){P.streaming=!1,u(P);return}let Ie=le.get(P.id),Ee=Ie!=null?Ie:Me(Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=null,st=!1;if(He&&(Ge=He.getExtractedText(),Ge===null&&(Ge=ms(Ee)),Ge===null)){let F=He.processChunk(Ee);F instanceof Promise?(st=!0,F.then(Y=>{var it;let Ce=typeof Y=="string"?Y:(it=Y==null?void 0:Y.text)!=null?it:null;Ce!==null&&(P.content=Ce,P.streaming=!1,Q.delete(P.id),le.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof F=="string"?F:(Lt=F==null?void 0:F.text)!=null?Lt:null}if(!st){Ge!==null&&Ge.trim()!==""?P.content=Ge:le.has(P.id)||(P.content=Me(Ae));let F=Q.get(P.id);if(F){let Y=(xt=F.close)==null?void 0:xt.call(F);Y instanceof Promise&&Y.catch(()=>{}),Q.delete(P.id)}le.delete(P.id),P.streaming=!1,u(P)}},Ne=(P,ee,Ae)=>{let Ie=y.get(P);if(Ie)return Ie;let Ee={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ae?{variant:Ae}:{},...Ae==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,Ee),u(Ee),Ee},j=[],$e,ze=new Map,ye=0,we="agent",Ze=!1,Nt=null,re=null,Oe=new Map,xr=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for($e=()=>{var P,ee,Ae,Ie,Ee,He,Ge,st,Lt,xt,F,Y,Ce,it,Je,qt,yr,yt,bt,Pt,wt,pr,Ot,_r,Tr,Er,wr,kr,uo,Ct,Ao,Mo,Uo,fo,pt,Rn,To,In,Br,da,nn,qo,an,sn,Wn,Hn,ln,ht,Ur,qr,Lr,St,to,ro,Vr,dn,Vo,cn,zr,Rt,Pr,oo,pn,zo,un,he,Dr,Eo,ut,ar,sr,ko,$a,$o,Bn,Lo,q,ca,Po,Ro,jo,Io,mo,pa,Fs,$r,jr,go,ho,Dn,Go,Cr,Wo,ua,Fn,fa,Ns,ma,Os,ga,ct,ja,no,Fr,_s;for(let ha=0;ha<j.length;ha++){let Ye=j[ha].payloadType,k=j[ha].payload;if(!Ze&&we!=="flow"&&typeof k.stepType=="string"&&(we="flow"),Ye==="reasoning_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V),Ne($,V,"reasoning");continue}let X=(P=Se(k,!0))!=null?P:`reason-${l()}`,ge=We(X);ge.reasoning=(ee=ge.reasoning)!=null?ee:{id:X,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Ie=ge.reasoning.startedAt)!=null?Ie:K((Ae=k.startedAt)!=null?Ae:k.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),ge.streaming=!0,ge.reasoning.status="streaming",u(ge)}else if(Ye==="reasoning_delta"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let De=y.get($),ft=(Ge=(He=(Ee=k.reasoningText)!=null?Ee:k.text)!=null?He:k.delta)!=null?Ge:"";ft&&k.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(ft)),u(De));continue}let V=(Lt=(st=Se(k,!1))!=null?st:Se(k,!0))!=null?Lt:`reason-${l()}`,X=We(V);X.reasoning=(xt=X.reasoning)!=null?xt:{id:V,status:"streaming",chunks:[]},X.reasoning.startedAt=(Y=X.reasoning.startedAt)!=null?Y:K((F=k.startedAt)!=null?F:k.timestamp);let ge=(Je=(it=(Ce=k.reasoningText)!=null?Ce:k.text)!=null?it:k.delta)!=null?Je:"";if(ge&&k.hidden!==!0){let De=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(De!==void 0){let ft=rt(V,De,String(ge));X.reasoning.chunks=[ft]}else X.reasoning.chunks.push(String(ge))}if(X.reasoning.status=k.done?"complete":"streaming",k.done){X.reasoning.completedAt=K((qt=k.completedAt)!=null?qt:k.timestamp);let De=(yr=X.reasoning.startedAt)!=null?yr:Date.now();X.reasoning.durationMs=Math.max(0,((yt=X.reasoning.completedAt)!=null?yt:Date.now())-De)}X.streaming=X.reasoning.status!=="complete",u(X)}else if(Ye==="reasoning_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let ft=y.get($);if(ft.reasoning){let ot=typeof k.text=="string"?k.text:"";ot&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(ot),ft.reasoning.status="complete",ft.streaming=!1,u(ft)}T.delete($),y.delete($);continue}let V=(Pt=(bt=Se(k,!1))!=null?bt:Se(k,!0))!=null?Pt:`reason-${l()}`,X=typeof k.text=="string"?k.text:"";!v.get(V)&&(X||k.scope==="loop")&&We(V);let ge=v.get(V);if(ge!=null&&ge.reasoning){(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),X&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(X),ge.reasoning.status="complete",ge.reasoning.completedAt=K((wt=k.completedAt)!=null?wt:k.timestamp);let ft=(pr=ge.reasoning.startedAt)!=null?pr:Date.now();ge.reasoning.durationMs=Math.max(0,((Ot=ge.reasoning.completedAt)!=null?Ot:Date.now())-ft),ge.streaming=!1,u(ge)}let De=D(k);De&&W.byStep.delete(De)}else if(Ye==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ye=k.iteration);let $=(Tr=(_r=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?_r:_e(k,!0))!=null?Tr:`tool-${l()}`,V=(Er=k.toolName)!=null?Er:k.name;if(Ve(V)){ve.add($);continue}de(O(k),$);let X=G($),ge=(wr=X.toolCall)!=null?wr:{id:$,status:"pending"};ge.name=V!=null?V:ge.name,ge.status="running",k.parameters!==void 0?ge.args=k.parameters:k.args!==void 0&&(ge.args=k.args),ge.startedAt=(uo=ge.startedAt)!=null?uo:K((kr=k.startedAt)!=null?kr:k.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,X.toolCall=ge,X.streaming=!0,k.executionId&&(X.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(X)}else if(Ye==="tool_output_delta"){let $=(Ao=(Ct=_e(k,!1))!=null?Ct:_e(k,!0))!=null?Ao:`tool-${l()}`;if(ve.has($))continue;let V=G($),X=(Mo=V.toolCall)!=null?Mo:{id:$,status:"running"};X.startedAt=(fo=X.startedAt)!=null?fo:K((Uo=k.startedAt)!=null?Uo:k.timestamp);let ge=(To=(Rn=(pt=k.text)!=null?pt:k.delta)!=null?Rn:k.message)!=null?To:"";ge&&(X.chunks=(In=X.chunks)!=null?In:[],X.chunks.push(String(ge))),X.status="running",V.toolCall=X,V.streaming=!0;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(nn=V.agentMetadata)!=null?nn:{executionId:(Br=De==null?void 0:De.executionId)!=null?Br:k.executionId,iteration:(da=De==null?void 0:De.iteration)!=null?da:k.iteration}),u(V)}else if(Ye==="tool_complete"){let $=(an=(qo=_e(k,!1))!=null?qo:_e(k,!0))!=null?an:`tool-${l()}`;if(ve.has($)){ve.delete($);continue}let V=G($),X=(sn=V.toolCall)!=null?sn:{id:$,status:"running"};X.status="complete",k.result!==void 0&&(X.result=k.result),typeof k.duration=="number"&&(X.duration=k.duration),X.completedAt=K((Wn=k.completedAt)!=null?Wn:k.timestamp);let ge=(Hn=k.duration)!=null?Hn:k.executionTime;if(typeof ge=="number")X.durationMs=ge;else{let ot=(ln=X.startedAt)!=null?ln:Date.now();X.durationMs=Math.max(0,((ht=X.completedAt)!=null?ht:Date.now())-ot)}V.toolCall=X,V.streaming=!1;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(Lr=V.agentMetadata)!=null?Lr:{executionId:(Ur=De==null?void 0:De.executionId)!=null?Ur:k.executionId,iteration:(qr=De==null?void 0:De.iteration)!=null?qr:k.iteration}),u(V);let ft=O(k);ft&&H.byCall.delete(ft)}else if(Ye==="await"&&k.toolName){let $=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(St=$!=null?$:k.toolId)!=null?St:`local-${l()}`,X=G(V),ge=k.toolName,De=k.origin==="webmcp"&&!yn(ge)?`webmcp:${ge}`:ge,ft=yn(De),ot=(to=X.toolCall)!=null?to:{id:V,status:"pending"};ot.name=De,ot.args=k.parameters,ot.status=ft?"running":"complete",ot.chunks=(ro=ot.chunks)!=null?ro:[],ot.startedAt=(Vo=ot.startedAt)!=null?Vo:K((dn=(Vr=k.startedAt)!=null?Vr:k.timestamp)!=null?dn:k.awaitedAt),ft?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(cn=ot.completedAt)!=null?cn:ot.startedAt,X.toolCall=ot,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=k.executionId)!=null?Rt:(zr=X.agentMetadata)==null?void 0:zr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(X)}else if(Ye==="text_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V);continue}let X=m;X&&(we==="flow"?(at(X),Ut=X):(X.streaming=!1,u(X)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ye==="text_delta"){let $=typeof k.id=="string"?k.id:null,V=$?T.get($):void 0;if($&&V){let ge=typeof k.delta=="string"?k.delta:"",De=((Pr=S.get($))!=null?Pr:"")+ge;if(S.set($,De),De.trim()==="")continue;let ft=Ne($,V);ft.agentMetadata={...ft.agentMetadata,executionId:k.executionId,parentToolId:V},jt(ft,De,ge,void 0);continue}if(E=typeof k.id=="string"?k.id:E,we==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(A+=ge,A.trim()==="")continue;let De=ce();De.agentMetadata={executionId:k.executionId,iteration:k.iteration},jt(De,A,ge,void 0),x=De;continue}let X=ce();X.content+=(oo=k.delta)!=null?oo:"",X.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Nt!=null?Nt:void 0,agentName:re==null?void 0:re.agentName},x=X,u(X)}else if(Ye==="text_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)){let X=y.get($);X&&at(X),T.delete($),S.delete($),y.delete($);continue}let V=m;V&&(we==="flow"?(at(V),Ut=V):(((pn=V.content)!=null?pn:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(Ye==="step_complete"){let $=k.stepType,V=k.executionType;if($==="tool"||V==="context")continue;if(k.success===!1){let X=k.error,ge=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((zo=X.message)!=null?zo:"Step failed"):"Step failed";r({type:"error",error:new Error(ge)});let De=m;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let X=Ut;Ut=null;let ge=k.stopReason,De=(un=k.result)==null?void 0:un.response;if(X)ge&&(X.stopReason=ge),De!=null?vt(X,De):X.streaming!==!1&&(Q.delete(X.id),le.delete(X.id),X.streaming=!1,u(X));else{let ft=De!=null&&De!=="";if(ft||ge){let ot=ce();ge&&(ot.stopReason=ge),ft?at(ot,De):(ot.streaming=!1,u(ot))}}continue}}else if(Ye==="execution_start")we=k.kind==="flow"?"flow":"agent",Ze=!0,we==="agent"&&(re={executionId:k.executionId,agentId:(he=k.agentId)!=null?he:"virtual",agentName:(Dr=k.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(Eo=k.maxTurns)!=null?Eo:1,startedAt:K(k.startedAt)});else if(Ye==="turn_start"){let $=typeof k.iteration=="number"?k.iteration:ye;if($!==ye){if(re&&(re.currentIteration=$),xr==="separate"&&$>1){let V=m;V&&(V.streaming=!1,u(V),Oe.set($-1,V),m=null)}ye=$}Nt=typeof k.id=="string"?k.id:null,x=null}else if(Ye==="tool_input_delta"){let $=(ut=k.toolCallId)!=null?ut:H.lastId;if($){let V=M.get($);V!=null&&V.toolCall&&(V.toolCall.chunks=(ar=V.toolCall.chunks)!=null?ar:[],V.toolCall.chunks.push((sr=k.delta)!=null?sr:""),u(V))}}else{if(Ye==="tool_input_complete")continue;if(Ye==="turn_complete"){let $=k.stopReason,V=m!=null?m:x;if($&&V!==null){let X=k.id;(!X||((ko=V.agentMetadata)==null?void 0:ko.turnId)===X)&&(V.stopReason=$,u(V))}Nt===k.id&&(Nt=null)}else if(Ye==="media_start"){let $=String(k.id);ze.set($,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ye==="media_delta"){let $=ze.get(String(k.id));$&&typeof k.delta=="string"&&$.parts.push(k.delta)}else if(Ye==="media_complete"){let $=String(k.id),V=ze.get($);ze.delete($);let X=($o=($a=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?$a:V==null?void 0:V.mediaType)!=null?$o:"application/octet-stream",ge=typeof k.data=="string"?k.data:void 0,De=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ft=null;if(ge)ft={type:"media",data:ge,mediaType:X};else if(De){let ur=X.toLowerCase();ft={type:ur==="image"||ur.startsWith("image/")?"image-url":"file-url",url:De,mediaType:X}}let ot=(Bn=k.toolCallId)!=null?Bn:V==null?void 0:V.toolCallId,Ga=ft?[ft]:[],Nr=[];for(let ur of Ga){if(!ur||typeof ur!="object")continue;let fr=ur,Nn=typeof fr.type=="string"?fr.type:void 0,Ko=typeof fr.mediaType=="string"?fr.mediaType.toLowerCase():"",Rr=null,br="";if(Nn==="media"){let Gr=typeof fr.data=="string"?fr.data:void 0;if(!Gr)continue;br=Ko.length>0?Ko:"application/octet-stream",Rr=`data:${br};base64,${Gr}`}else if(Nn==="image-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else if(Nn==="file-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else continue;if(Rr)if(Nn==="image-url"||br.startsWith("image/"))Nr.push({type:"image",image:Rr,...br.includes("/")?{mimeType:br}:{}});else if(br.startsWith("audio/"))Nr.push({type:"audio",audio:Rr,mimeType:br});else if(br.startsWith("video/"))Nr.push({type:"video",video:Rr,mimeType:br});else{let Gr=br||"application/octet-stream";Nr.push({type:"file",data:Rr,mimeType:Gr,filename:cb(Gr)})}}if(Nr.length>0){let ur=l(),fr=ot,Ko={id:`agent-media-${typeof fr=="string"&&fr.length>0?`${fr}-${ur}`:String(ur)}`,role:"assistant",content:"",contentParts:Nr,createdAt:new Date().toISOString(),streaming:!1,sequence:ur,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ye}};u(Ko);let Rr=m;Rr&&(Rr.streaming=!1,u(Rr)),m=null,b.current=null}}else if(Ye==="execution_complete"){let $=(Lo=k.kind)!=null?Lo:we;$==="agent"&&re&&(re.status=k.success?"complete":"error",re.completedAt=K(k.completedAt),re.stopReason=k.stopReason);let V=m;V&&($==="flow"&&V.streaming!==!1?at(V):(V.streaming=!1,u(V)),m=null),E=null,A="",Ut=null,r({type:"status",status:"idle"})}else if(Ye==="execution_error"){let $=typeof k.error=="string"?k.error:(ca=(q=k.error)==null?void 0:q.message)!=null?ca:"Execution error";r({type:"error",error:new Error($)})}else if(Ye!=="ping"){if(Ye==="approval_start"){let $=(Po=k.approvalId)!=null?Po:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ro=re==null?void 0:re.agentId)!=null?Ro:"virtual",executionId:(Io=(jo=k.executionId)!=null?jo:re==null?void 0:re.executionId)!=null?Io:"",toolName:(mo=k.toolName)!=null?mo:"",toolType:k.toolType,description:(Fs=k.description)!=null?Fs:`Execute ${(pa=k.toolName)!=null?pa:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let $=($r=k.approvalId)!=null?$r:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(jr=re==null?void 0:re.agentId)!=null?jr:"virtual",executionId:(ho=(go=k.executionId)!=null?go:re==null?void 0:re.executionId)!=null?ho:"",toolName:(Dn=k.toolName)!=null?Dn:"",toolType:k.toolType,description:(Cr=k.description)!=null?Cr:`Execute ${(Go=k.toolName)!=null?Go:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="approval_complete"){let $=k.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Wo=k.decision)!=null?Wo:"approved",agentId:(ua=re==null?void 0:re.agentId)!=null?ua:"virtual",executionId:(fa=(Fn=k.executionId)!=null?Fn:re==null?void 0:re.executionId)!=null?fa:"",toolName:(Ns=k.toolName)!=null?Ns:"",description:(ma=k.description)!=null?ma:"",resolvedAt:Date.now()}};u(X)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let $=k.artifactType,V=String(k.id),X=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:$,title:X,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:X}),!ie.has(V)){ie.add(V);let ge={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:X,artifactType:$,status:"streaming"}})};se.set(V,ge),u(ge)}}else if(Ye==="artifact_delta"){let $=String(k.id),V=typeof k.delta=="string"?k.delta:String((Os=k.delta)!=null?Os:"");r({type:"artifact_delta",id:$,artDelta:V});let X=pe.get($);X&&(X.markdown+=V)}else if(Ye==="artifact_update"){let $=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:$,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let $=String(k.id);r({type:"artifact_complete",id:$});let V=se.get($);if(V){V.streaming=!1;try{let X=JSON.parse((ga=V.rawContent)!=null?ga:"{}");if(X.props){X.props.status="complete";let ge=pe.get($);ge!=null&&ge.markdown&&(X.props.markdown=ge.markdown)}V.rawContent=JSON.stringify(X)}catch{}pe.delete($),u(V),se.delete($)}}}else if(Ye==="transcript_insert"){let $=k.message;if(!$||typeof $!="object")continue;let V=String((ct=$.id)!=null?ct:`msg-${l()}`),X=$.role,De={id:V,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(u(De),De.rawContent)try{let ft=JSON.parse(De.rawContent),ot=(ja=ft==null?void 0:ft.props)==null?void 0:ja.artifactId;typeof ot=="string"&&ie.add(ot)}catch{}m=null,b.current=null,Q.delete(V),le.delete(V)}else if(Ye==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let $=typeof k.error=="string"?k.error:((no=k.error)==null?void 0:no.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error($)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let $=null;if(k.error instanceof Error)$=k.error;else if(Ye==="dispatch_error"){let V=(Fr=k.message)!=null?Fr:k.error;V!=null&&V!==""&&($=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?$=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&($=new Error(String((_s=V.message)!=null?_s:V)))}if($){r({type:"error",error:$});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}j.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Ae=s.split(`
|
|
13
13
|
|
|
14
14
|
`);s=(Qt=Ae.pop())!=null?Qt:"";for(let Ie of Ae){let Ee=Ie.split(`
|
|
15
15
|
`),He="message",Ge="";for(let xt of Ee)xt.startsWith("event:")?He=xt.replace("event:","").trim():xt.startsWith("data:")&&(Ge+=xt.replace("data:","").trim());if(!Ge)continue;let st;try{st=JSON.parse(Ge)}catch(xt){r({type:"error",error:xt instanceof Error?xt:new Error("Failed to parse chat stream payload")});continue}let Lt=He!=="message"?He:(_o=st.type)!=null?_o:"message";if((So=this.onSSEEvent)==null||So.call(this,Lt,st),this.parseSSEEvent){b.current=m;let xt=await this.handleCustomSSEEvent(st,r,b,u,l,L);if(b.current&&b.current!==m&&(m=b.current),xt)continue}j.push({payloadType:Lt,payload:st}),$e()}}$e()}};function _g(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Pa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Qn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Ug(e){return typeof e=="string"?[{type:"text",text:e}]:e}function qg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Vg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function gs(e){return{type:"text",text:e}}function $g(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function jg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Gg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Kg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fb=["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"],en=[...Kg,...fb];function mb(e){return Kg.includes(e)||e.startsWith("image/")}function mi(e){return mb(e.type)}async function Xg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;mi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Jg(e,t=en,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function gb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qg(e,t){let r=gb(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]||r||"FILE"}var gi=class{constructor(t=24e3,r={}){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;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.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 r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);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 r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);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 r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Yg=16e3,hb=24e3,xb=4096,yb=1380533830;function bb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===yb?new Uint8Array(e,44):new Uint8Array(e)}function vb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Yg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){l.getTracks().forEach(b=>b.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,f=new p({sampleRate:Yg});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new gi(hb);if(n!==this.callGeneration){u.destroy(),l.getTracks().forEach(b=>b.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,l,x,n))},x.onmessage=b=>this.handleMessage(b,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let L=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${L}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(xb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),l=new Int16Array(c.length);for(let p=0;p<c.length;p++){let f=Math.max(-1,Math.min(1,c[p]));l[p]=f<0?f*32768:f*32767}o.send(l.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!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,r){if(r!==this.callGeneration||!this.playback)return;let o=bb(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(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var Yn=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 An(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Yn.isSupported())throw new Error("Browser speech recognition not supported");return new Yn(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function hi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return An({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return An({type:"runtype",runtype:e.runtype});if(Yn.isSupported())return An({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return hi(e),!0}catch{return!1}}function Ra(e){var r;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 o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var Mn=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Ra(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var l,p;let c=i.error;c==="canceled"||c==="interrupted"?(l=r.onEnd)==null||l.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Zn=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!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,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{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(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function Ul(e){if(!e)return"";let t=wb(e);return Zg(t!==null?t:e)}function wb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[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 Zg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|