@runtypelabs/persona 4.16.0 → 4.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},By=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)}},Dy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Oy=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function ln(e){return e==="card"?"collapsed":e}function rr(e){return e.split(";",1)[0].trim().toLowerCase()}function Ny(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(rr(r)===t)return{mode:ln(s),selector:rr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(rr(r)===o)return{mode:ln(s),selector:o}}function _u(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:ln(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?rr(t.file.mimeType):void 0,p=i?Ny(o.files.byMediaType,i):void 0;if(i&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:i,selector:p.selector}};if(o.files.default)return{mode:ln(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:ln(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:ln(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:ln(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:ln(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function to(e,t){return _u(e,t).mode}function _s(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Fy="agent_",_y="flow_";function $u(e){return e.startsWith(Fy)?{kind:"agentId",agentId:e}:e.startsWith(_y)?{kind:"flowId",flowId:e}:null}function ju(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=$u(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=$u(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as $y,ARR as jy,OBJ as Uy,STR as zy}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Uu=()=>document.createDocumentFragment(),Me=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},In=(...e)=>e.filter(Boolean).join(" ");var ei="ask_user_question",$s=8,$r="data-persona-ask-sheet-for",qy="Other",Vy="Other\u2026",qu="Type your own answer here",Vu="Send",Ky="Next",Gy="Back",Jy="Submit all",Yy="Skip",Xy=3,lc="data-ask-current-index",cc="data-ask-question-count",Ku="data-ask-answers",dc="data-ask-grouped",Gu="data-ask-layout",Qy=e=>e.layout==="pills"?"pills":"rows",Zy=e=>e.getAttribute(Gu)==="pills"?"pills":"rows",zu=!1,Ju=e=>e.replace(/["\\]/g,"\\$&"),vo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ei,ti=e=>e?.features?.askUserQuestion??{},xo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=$y(r,zy|Uy|jy);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},js=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>$s&&!zu&&(zu=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${$s}.`)),t.slice(0,$s)},eb=e=>js(e)[0]??null,tb=(e,t)=>js(e)[t]??null,Yu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Xu=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},nb=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Xu(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ob=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},rb=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Xy;c++)s.appendChild(ob(o));return s}if(p.forEach((c,g)=>{s.appendChild(nb(c,g,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?qy:Vy;if(o==="rows"){let g=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(p.length)),g.setAttribute("data-ask-other-row","true");let b=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??qu,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),g.appendChild(b);let x=Xu(o,a,p.length);x&&g.appendChild(x),s.appendChild(g)}else{let g=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??c,s.appendChild(g)}}return s},Qu=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??qu,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Vu,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},sb=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Vu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ab=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Gy,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Yy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Jy:n.nextLabel??Ky,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},sr=e=>{let t=e.getAttribute(Ku);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zu=(e,t)=>{e.setAttribute(Ku,JSON.stringify(t))},vn=e=>{let t=Number(e.getAttribute(lc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ib=(e,t)=>{e.setAttribute(lc,String(Math.max(0,Math.floor(t))))},jr=e=>{let t=Number(e.getAttribute(cc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Co=e=>e.getAttribute(dc)==="true",lb=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},cb=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ni=(e,t)=>{let{payload:n}=xo(t),o=js(n),r=sr(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},eg=e=>{let t=sr(e),n=vn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},tg=e=>{if(!Co(e))return;let t=sr(e),n=vn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},pc=(e,t,n)=>{let o=ti(n),r=Zy(e),{payload:s,complete:a}=xo(t),i=Co(e),p=vn(e),d=jr(e),c=i?tb(s,p):eb(s),g=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let P=typeof c?.question=="string"?c.question:"";x.textContent=P,x.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let P=rb(c,o,a,r);C.replaceWith(P)}if(r!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Qu(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!S?e.appendChild(sb(o)):(!g||i)&&S&&S.remove(),e.setAttribute("data-multi-select",g?"true":"false");let M=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=ab(p,d,o);M?M.replaceWith(P):e.appendChild(P)}else M&&M.remove();eg(e),tg(e)},db=(e,t,n)=>{let o=ti(t),r=Qy(o),s=e.toolCall.id,a=js(n),i=Math.max(1,a.length),p=i>1,d=lb(e,a),c=p?cb(e,i):0,g=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute($r,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(cc,String(i)),g.setAttribute(lc,String(c)),g.setAttribute(dc,p?"true":"false"),g.setAttribute(Gu,r),Zu(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Yu(g,o);let b=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",b.appendChild(x),g.appendChild(b);let S=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),g.appendChild(S),r!=="rows"&&g.appendChild(Qu(o,r)),pc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},pb=(e,t,n)=>{let{payload:o}=xo(t),r=Math.max(1,js(o).length);r>jr(e)&&(e.setAttribute(cc,String(r)),r>1&&!Co(e)&&e.setAttribute(dc,"true")),pc(e,t,n)},ub=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ti(t);Yu(n,o);let r=y("span","persona-ask-stub-label"),{complete:s}=xo(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Us=(e,t,n)=>{if(!n||!vo(e)||ti(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${$r}]`).forEach(d=>{d.getAttribute($r)!==r&&d.remove()});let a=n.querySelector(`[${$r}="${Ju(r)}"]`);if(a){pb(a,e,t);return}let{payload:i}=xo(e),p=db(e,t,i);n.appendChild(p)},ar=(e,t)=>{if(!e)return;let n=t?`[${$r}="${Ju(t)}"]`:`[${$r}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},uc=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),wo=(e,t)=>{let n=sr(e),o=vn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Zu(e,n),eg(e),tg(e)},oi=(e,t,n,o)=>{let r=jr(e),s=Math.max(0,Math.min(r-1,o));ib(e,s),pc(e,t,n)};var On="suggest_replies";var og={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:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},gc={name:On,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. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts 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:og,origin:"sdk",annotations:{readOnlyHint:!0}},fc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ur=e=>e.variant==="tool"&&e.toolCall?.name===On,rg=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let i=r.trim();return i?[i]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});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},mc=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ur(n))continue;let o=rg(n.toolCall?.args);return o.length>0?o:null}return null},ng=new Set,gb=(e,t,n)=>{let o=`${e}:${t}:${n}`;ng.has(o)||(ng.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Ao=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let i=t?.[a],p=n?.[a];i===void 0||p===void 0||i!==p&&gb(a,p,i)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var sg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:$s,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},ag={name:ei,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:sg,origin:"sdk",annotations:{readOnlyHint:!0}},zs=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(ag),Ao(e).expose&&t.push(gc),t};import{parse as ig,STR as lg,OBJ as cg}from"partial-json";var ri=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),So=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)}},fb=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},dg=e=>e.status==="complete"?fb(e):e.status==="pending"?"Waiting":"",mb=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var pg=e=>e.status==="complete"?mb(e):"Using tool...",si=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Vs=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return si(t)},ai=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return si(t)},hc=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Vs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ii=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&qs(o,n.slice(s,a.index),[]),a[1]!==void 0?qs(o,a[1],["bold"]):a[2]!==void 0?qs(o,a[2],["italic"]):a[3]!==void 0&&qs(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&qs(o,n.slice(s),[]),o},qs=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},hb=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ks=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},yc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},bc=()=>{let e=hb();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},vc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=ig(n,lg|cg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},yb=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?ri(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ri(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=ig(s,lg|cg),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},xc=()=>{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 ug="4.16.0";var To=ug;var vb="https://api.runtype.com/v1/dispatch",li="https://api.runtype.com";function xb(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Cc=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 Cb(e){switch(e){case"json":return vc;case"regex-json":return bc;case"xml":return xc;default:return yc}}var gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function wb(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=gg(n);if(!gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ks(e);return Ks(t)!==null&&a===null?t:e}var zr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??vb,this.headers={"Content-Type":"application/json","X-Persona-Version":To,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Cb(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ns(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=ju(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Cc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Fu(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||li}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Cc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Cc).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=E=>{let I=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,h=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,W=E.tools?E.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...E,reasoning:I,toolCall:h,tools:W}},b=E=>{if(E.role!=="assistant"||E.variant)return!0;let I=Array.isArray(E.contentParts)&&E.contentParts.length>0,h=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||I||h||!!E.stopReason},f=E=>{b(E)&&n({type:"message",message:g(E)})},x=null,C=null,S={current:null},M={current:null},P=null,T="",L=new Map,H=new Map,O=new Map,_=new Map,U=new Map,z={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},A=E=>{if(E==null)return null;try{return String(E)}catch{return null}},G=E=>A(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),Q=E=>A(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),le=o,J=!1,me=()=>{if(x)return x;let E,I="",h=P;return!J&&le?(E=le,J=!0,I=r??""):le&&h?E=`${le}_${h}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:E,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},ee=(E,I)=>{z.lastId=I,E&&z.byStep.set(E,I)},ye=(E,I)=>{let h=E.reasoningId??E.id,W=G(E);if(h){let B=String(h);return ee(W,B),B}if(W){let B=z.byStep.get(W);if(B)return z.lastId=B,B}if(z.lastId&&!I)return z.lastId;if(!I)return null;let R=`reason-${c()}`;return ee(W,R),R},Z=E=>{let I=_.get(E);if(I)return I;let h={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return _.set(E,h),f(h),h},ue=(E,I)=>{Y.lastId=I,E&&Y.byCall.set(E,I)},te=new Set,fe=new Map,be=new Set,he=new Map,Be=E=>{if(!E)return!1;let I=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},rt=(E,I)=>{let h=E.toolId??E.id,W=Q(E);if(h){let B=String(h);return ue(W,B),B}if(W){let B=Y.byCall.get(W);if(B)return Y.lastId=B,B}if(Y.lastId&&!I)return Y.lastId;if(!I)return null;let R=`tool-${c()}`;return ue(W,R),R},$e=E=>{let I=U.get(E);if(I)return I;let h={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,h),f(h),h},Ve=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let I=Number(E);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(E);if(!Number.isNaN(h))return h}return Date.now()},Le=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},_e=new Map,we=new Map,ae=new Map,Re=(E,I,h)=>{let W=ae.get(E);W||(W=[],ae.set(E,W));let R=0,B=W.length;for(;R<B;){let $=R+B>>>1;W[$].seq<I?R=$+1:B=$}W[R]?.seq===I?W[R]={seq:I,text:h}:W.splice(R,0,{seq:I,text:h});let V="";for(let $=0;$<W.length;$++)V+=W[$].text;return V},ct=(E,I)=>{let h=Le(I),W=we.get(E.id),R=wb(W,h);E.rawContent=R;let B=_e.get(E.id),V=pe=>{let Pe=E.content??"";pe.trim()!==""&&(Pe.trim().length===0||pe.startsWith(Pe)||pe.trimStart().startsWith(Pe.trim()))&&(E.content=pe)},$=()=>{if(B){let pe=B.close?.();pe instanceof Promise&&pe.catch(()=>{})}_e.delete(E.id),we.delete(E.id),E.streaming=!1,f(E)};if(!B){V(h),$();return}let K=Ks(R);if(K!==null&&K.trim()!==""){V(K),$();return}let de=pe=>{let Pe=typeof pe=="string"?pe:pe?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=B.getExtractedText();return ze!==null&&ze.trim()!==""?ze:h},Ue;try{Ue=B.processChunk(R)}catch{V(h),$();return}if(Ue instanceof Promise){Ue.then(pe=>{V(de(pe)),$()}).catch(()=>{V(h),$()});return}V(de(Ue)),$()},et=null,vt=(E,I,h,W)=>{E.rawContent=I,_e.has(E.id)||_e.set(E.id,this.createStreamParser());let R=_e.get(E.id),B=I.trim().startsWith("{")||I.trim().startsWith("[");if(B&&we.set(E.id,I),R.__isPlainTextParser===!0){E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E);return}let $=R.processChunk(I);if($ instanceof Promise)$.then(K=>{let de=typeof K=="string"?K:K?.text??null;de!==null&&de.trim()!==""?(E.content=de,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(E.content=K,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}},wn=(E,I)=>{let h=I??E.content;if(h==null||h===""){E.streaming=!1,f(E);return}let R=we.get(E.id)??Le(h);E.rawContent=R;let B=_e.get(E.id),V=null,$=!1;if(B&&(V=B.getExtractedText(),V===null&&(V=Ks(R)),V===null)){let K=B.processChunk(R);K instanceof Promise?($=!0,K.then(de=>{let Ue=typeof de=="string"?de:de?.text??null;Ue!==null&&(E.content=Ue,E.streaming=!1,_e.delete(E.id),we.delete(E.id),f(E))}).catch(()=>{})):V=typeof K=="string"?K:K?.text??null}if(!$){V!==null&&V.trim()!==""?E.content=V:we.has(E.id)||(E.content=Le(h));let K=_e.get(E.id);if(K){let de=K.close?.();de instanceof Promise&&de.catch(()=>{}),_e.delete(E.id)}we.delete(E.id),E.streaming=!1,f(E)}},An=(E,I,h)=>{let W=H.get(E);if(W)return W;let R={id:`nested-${I}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(E,R),f(R),R},Ze=[],ke,ve=new Map,tt=0,Te="agent",Ce=!1,re=null,Ae=null,Sn=new Map,ne=this.config.iterationDisplay??"separate";for(ke=()=>{for(let E=0;E<Ze.length;E++){let I=Ze[E].payloadType,h=Ze[E].payload;if(!Ce&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R),An(W,R,"reasoning");continue}let B=ye(h,!0)??`reason-${c()}`,V=Z(B);V.reasoning=V.reasoning??{id:B,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??Ve(h.startedAt??h.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),V.streaming=!0,V.reasoning.status="streaming",f(V)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),f($));continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=Z(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Ve(h.startedAt??h.timestamp);let V=h.reasoningText??h.text??h.delta??"";if(V&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=Re(R,$,String(V));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(V))}if(B.reasoning.status=h.done?"complete":"streaming",h.done){B.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let $=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-$)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let de=typeof h.text=="string"?h.text:"";de&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(de),K.reasoning.status="complete",K.streaming=!1,f(K)}L.delete(W),H.delete(W);continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=typeof h.text=="string"?h.text:"";!_.get(R)&&(B||h.scope==="loop")&&Z(R);let V=_.get(R);if(V?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),B&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(B),V.reasoning.status="complete",V.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let K=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-K),V.streaming=!1,f(V)}let $=G(h);$&&z.byStep.delete($)}else if(I==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??rt(h,!0)??`tool-${c()}`,R=h.toolName??h.name;if(Be(R)){te.add(W);continue}ue(Q(h),W);let B=$e(W),V=B.toolCall??{id:W,status:"pending"};V.name=R??V.name,V.status="running",h.parameters!==void 0?V.args=h.parameters:h.args!==void 0&&(V.args=h.args),V.startedAt=V.startedAt??Ve(h.startedAt??h.timestamp),V.completedAt=void 0,V.durationMs=void 0,B.toolCall=V,B.streaming=!0,h.executionId&&(B.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(B)}else if(I==="tool_output_delta"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W))continue;let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.startedAt=B.startedAt??Ve(h.startedAt??h.timestamp);let V=h.text??h.delta??h.message??"";V&&(B.chunks=B.chunks??[],B.chunks.push(String(V))),B.status="running",R.toolCall=B,R.streaming=!0;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R)}else if(I==="tool_complete"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W)){te.delete(W);continue}let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.status="complete",h.result!==void 0&&(B.result=h.result),typeof h.duration=="number"&&(B.duration=h.duration),B.completedAt=Ve(h.completedAt??h.timestamp);let V=h.duration??h.executionTime;if(typeof V=="number")B.durationMs=V;else{let de=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-de)}R.toolCall=B,R.streaming=!1;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R);let K=Q(h);K&&Y.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,R=W??h.toolId??`local-${c()}`,B=$e(R),V=h.toolName,$=h.origin==="webmcp"&&!or(V)?`webmcp:${V}`:V,K=or($),de=B.toolCall??{id:R,status:"pending"};de.name=$,de.args=h.parameters,de.status=K?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Ve(h.startedAt??h.timestamp??h.awaitedAt),K?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,B.toolCall=de,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:h.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},f(B)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R);continue}let B=x;B&&(Te==="flow"?(wn(B),et=B):(B.streaming=!1,f(B)),x=null),P=typeof h.id=="string"?h.id:P,T=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,R=W?L.get(W):void 0;if(W&&R){let V=typeof h.delta=="string"?h.delta:"",$=(O.get(W)??"")+V;if(O.set(W,$),$.trim()==="")continue;let K=An(W,R);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:R},vt(K,$,V,void 0);continue}if(P=typeof h.id=="string"?h.id:P,Te==="flow"){let V=typeof h.delta=="string"?h.delta:"";if(T+=V,T.trim()==="")continue;let $=me();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},vt($,T,V,void 0),C=$;continue}let B=me();B.content+=h.delta??"",B.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:Ae?.agentName},C=B,f(B)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)){let B=H.get(W);B&&wn(B),L.delete(W),O.delete(W),H.delete(W);continue}let R=x;R&&(Te==="flow"?(wn(R),et=R):((R.content??"")===""&&typeof h.text=="string"&&(R.content=h.text),R.streaming=!1,f(R)),x=null),P=null,T=""}else if(I==="step_complete"){let W=h.stepType,R=h.executionType;if(W==="tool"||R==="context")continue;if(h.success===!1){let B=h.error,V=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let $=x;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"});continue}{let B=et;et=null;let V=h.stopReason,$=h.result?.response;if(B)V&&(B.stopReason=V),$!=null?ct(B,$):B.streaming!==!1&&(_e.delete(B.id),we.delete(B.id),B.streaming=!1,f(B));else{let K=$!=null&&$!=="";if(K||V){let de=me();V&&(de.stopReason=V),K?wn(de,$):(de.streaming=!1,f(de))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",Ce=!0,Te==="agent"&&(Ae={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ve(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(Ae&&(Ae.currentIteration=W),ne==="separate"&&W>1){let R=x;R&&(R.streaming=!1,f(R),Sn.set(W-1,R),x=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??Y.lastId;if(W){let R=U.get(W);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(h.delta??""),f(R))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,R=x??C;if(W&&R!==null){let B=h.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=W,f(R))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ve.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ve.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),R=ve.get(W);ve.delete(W);let B=(typeof h.mediaType=="string"?h.mediaType:void 0)??R?.mediaType??"application/octet-stream",V=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(V)K={type:"media",data:V,mediaType:B};else if($){let Pe=B.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:B}}let de=h.toolCallId??R?.toolCallId,Ue=K?[K]:[],pe=[];for(let Pe of Ue){if(!Pe||typeof Pe!="object")continue;let ze=Pe,je=typeof ze.type=="string"?ze.type:void 0,He=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",Se=null,nt="";if(je==="media"){let St=typeof ze.data=="string"?ze.data:void 0;if(!St)continue;nt=He.length>0?He:"application/octet-stream",Se=`data:${nt};base64,${St}`}else if(je==="image-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else if(je==="file-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else continue;if(Se)if(je==="image-url"||nt.startsWith("image/"))pe.push({type:"image",image:Se,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))pe.push({type:"audio",audio:Se,mimeType:nt});else if(nt.startsWith("video/"))pe.push({type:"video",video:Se,mimeType:nt});else{let St=nt||"application/octet-stream";pe.push({type:"file",data:Se,mimeType:St,filename:xb(St)})}}if(pe.length>0){let Pe=c(),ze=de,He={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:pe,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};f(He);let Se=x;Se&&(Se.streaming=!1,f(Se)),x=null,S.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&Ae&&(Ae.status=h.success?"complete":"error",Ae.completedAt=Ve(h.completedAt),Ae.stopReason=h.stopReason);let R=x;R&&(W==="flow"&&R.streaming!==!1?wn(R):(R.streaming=!1,f(R)),x=null),P=null,T="",et=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let B={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(B)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,R=String(h.id),B=typeof h.title=="string"?h.title:void 0,V=h.file,$;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&($={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:R,artifactType:W,title:B,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(R,{markdown:"",title:B,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let de=to(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),Ue=typeof h.component=="string"?h.component:void 0,pe={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:_s(de,{artifactId:R,title:B,artifactType:W,status:"streaming",...$?{file:$}:{},...Ue?{component:Ue}:{}})};fe.set(R,pe),f(pe)}}else if(I==="artifact_delta"){let W=String(h.id),R=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:R});let B=he.get(W);B&&(B.markdown+=R)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let R=he.get(String(h.id));R&&(R.props={...R.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let R=fe.get(W);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let V=he.get(W);V?.markdown&&(B.props.markdown=V.markdown),V?.file&&(B.props.file=V.file),B.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(B.props.componentProps=V.props)}R.rawContent=JSON.stringify(B)}catch{}he.delete(W),f(R),fe.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let R=String(W.id??`msg-${c()}`),B=W.role,$={id:R,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(f($),$.rawContent)try{let de=JSON.parse($.rawContent)?.props?.artifactId;typeof de=="string"&&be.add(de)}catch{}x=null,S.current=null,_e.delete(R),we.delete(R)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let R=h.message??h.error;R!=null&&R!==""&&(W=new Error(String(R)))}else{let R=h.error;typeof R=="string"&&R!==""?W=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(W=new Error(String(R.message??R)))}if(W){n({type:"error",error:W});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:E,value:I}=await s.read();if(E)break;i+=a.decode(I,{stream:!0});let h=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ks=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},yc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},bc=()=>{let e=hb();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},vc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=ig(n,lg|cg);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},yb=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?ri(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?ri(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=ig(s,lg|cg),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},xc=()=>{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 ug="4.17.1";var To=ug;var vb="https://api.runtype.com/v1/dispatch",li="https://api.runtype.com";function xb(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Cc=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 Cb(e){switch(e){case"json":return vc;case"regex-json":return bc;case"xml":return xc;default:return yc}}var gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function wb(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=gg(n);if(!gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Ks(e);return Ks(t)!==null&&a===null?t:e}var zr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??vb,this.headers={"Content-Type":"application/json","X-Persona-Version":To,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Cb(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Ns(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=ju(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Cc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":To},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||li}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Fu(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||li}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Cc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Cc).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...zs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=E=>{let I=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,h=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,W=E.tools?E.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...E,reasoning:I,toolCall:h,tools:W}},b=E=>{if(E.role!=="assistant"||E.variant)return!0;let I=Array.isArray(E.contentParts)&&E.contentParts.length>0,h=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||I||h||!!E.stopReason},f=E=>{b(E)&&n({type:"message",message:g(E)})},x=null,C=null,S={current:null},M={current:null},P=null,T="",L=new Map,H=new Map,O=new Map,_=new Map,U=new Map,z={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},A=E=>{if(E==null)return null;try{return String(E)}catch{return null}},G=E=>A(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),Q=E=>A(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),le=o,J=!1,me=()=>{if(x)return x;let E,I="",h=P;return!J&&le?(E=le,J=!0,I=r??""):le&&h?E=`${le}_${h}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:E,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},ee=(E,I)=>{z.lastId=I,E&&z.byStep.set(E,I)},ye=(E,I)=>{let h=E.reasoningId??E.id,W=G(E);if(h){let B=String(h);return ee(W,B),B}if(W){let B=z.byStep.get(W);if(B)return z.lastId=B,B}if(z.lastId&&!I)return z.lastId;if(!I)return null;let R=`reason-${c()}`;return ee(W,R),R},Z=E=>{let I=_.get(E);if(I)return I;let h={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return _.set(E,h),f(h),h},ue=(E,I)=>{Y.lastId=I,E&&Y.byCall.set(E,I)},te=new Set,fe=new Map,be=new Set,he=new Map,Be=E=>{if(!E)return!1;let I=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},rt=(E,I)=>{let h=E.toolId??E.id,W=Q(E);if(h){let B=String(h);return ue(W,B),B}if(W){let B=Y.byCall.get(W);if(B)return Y.lastId=B,B}if(Y.lastId&&!I)return Y.lastId;if(!I)return null;let R=`tool-${c()}`;return ue(W,R),R},$e=E=>{let I=U.get(E);if(I)return I;let h={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,h),f(h),h},Ve=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let I=Number(E);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(E);if(!Number.isNaN(h))return h}return Date.now()},Le=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},_e=new Map,we=new Map,ae=new Map,Re=(E,I,h)=>{let W=ae.get(E);W||(W=[],ae.set(E,W));let R=0,B=W.length;for(;R<B;){let $=R+B>>>1;W[$].seq<I?R=$+1:B=$}W[R]?.seq===I?W[R]={seq:I,text:h}:W.splice(R,0,{seq:I,text:h});let V="";for(let $=0;$<W.length;$++)V+=W[$].text;return V},ct=(E,I)=>{let h=Le(I),W=we.get(E.id),R=wb(W,h);E.rawContent=R;let B=_e.get(E.id),V=pe=>{let Pe=E.content??"";pe.trim()!==""&&(Pe.trim().length===0||pe.startsWith(Pe)||pe.trimStart().startsWith(Pe.trim()))&&(E.content=pe)},$=()=>{if(B){let pe=B.close?.();pe instanceof Promise&&pe.catch(()=>{})}_e.delete(E.id),we.delete(E.id),E.streaming=!1,f(E)};if(!B){V(h),$();return}let K=Ks(R);if(K!==null&&K.trim()!==""){V(K),$();return}let de=pe=>{let Pe=typeof pe=="string"?pe:pe?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=B.getExtractedText();return ze!==null&&ze.trim()!==""?ze:h},Ue;try{Ue=B.processChunk(R)}catch{V(h),$();return}if(Ue instanceof Promise){Ue.then(pe=>{V(de(pe)),$()}).catch(()=>{V(h),$()});return}V(de(Ue)),$()},et=null,vt=(E,I,h,W)=>{E.rawContent=I,_e.has(E.id)||_e.set(E.id,this.createStreamParser());let R=_e.get(E.id),B=I.trim().startsWith("{")||I.trim().startsWith("[");if(B&&we.set(E.id,I),R.__isPlainTextParser===!0){E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E);return}let $=R.processChunk(I);if($ instanceof Promise)$.then(K=>{let de=typeof K=="string"?K:K?.text??null;de!==null&&de.trim()!==""?(E.content=de,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(E.content=K,f(E)):!B&&!I.trim().startsWith("<")&&(E.content=W!==void 0?I:E.content+h,we.delete(E.id),_e.delete(E.id),E.rawContent=void 0,f(E))}},wn=(E,I)=>{let h=I??E.content;if(h==null||h===""){E.streaming=!1,f(E);return}let R=we.get(E.id)??Le(h);E.rawContent=R;let B=_e.get(E.id),V=null,$=!1;if(B&&(V=B.getExtractedText(),V===null&&(V=Ks(R)),V===null)){let K=B.processChunk(R);K instanceof Promise?($=!0,K.then(de=>{let Ue=typeof de=="string"?de:de?.text??null;Ue!==null&&(E.content=Ue,E.streaming=!1,_e.delete(E.id),we.delete(E.id),f(E))}).catch(()=>{})):V=typeof K=="string"?K:K?.text??null}if(!$){V!==null&&V.trim()!==""?E.content=V:we.has(E.id)||(E.content=Le(h));let K=_e.get(E.id);if(K){let de=K.close?.();de instanceof Promise&&de.catch(()=>{}),_e.delete(E.id)}we.delete(E.id),E.streaming=!1,f(E)}},An=(E,I,h)=>{let W=H.get(E);if(W)return W;let R={id:`nested-${I}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(E,R),f(R),R},Ze=[],ke,ve=new Map,tt=0,Te="agent",Ce=!1,re=null,Ae=null,Sn=new Map,ne=this.config.iterationDisplay??"separate";for(ke=()=>{for(let E=0;E<Ze.length;E++){let I=Ze[E].payloadType,h=Ze[E].payload;if(!Ce&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R),An(W,R,"reasoning");continue}let B=ye(h,!0)??`reason-${c()}`,V=Z(B);V.reasoning=V.reasoning??{id:B,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??Ve(h.startedAt??h.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),V.streaming=!0,V.reasoning.status="streaming",f(V)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),f($));continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=Z(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Ve(h.startedAt??h.timestamp);let V=h.reasoningText??h.text??h.delta??"";if(V&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=Re(R,$,String(V));B.reasoning.chunks=[K]}else B.reasoning.chunks.push(String(V))}if(B.reasoning.status=h.done?"complete":"streaming",h.done){B.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let $=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-$)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let de=typeof h.text=="string"?h.text:"";de&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(de),K.reasoning.status="complete",K.streaming=!1,f(K)}L.delete(W),H.delete(W);continue}let R=ye(h,!1)??ye(h,!0)??`reason-${c()}`,B=typeof h.text=="string"?h.text:"";!_.get(R)&&(B||h.scope==="loop")&&Z(R);let V=_.get(R);if(V?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(V.reasoning.scope=h.scope),B&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(B),V.reasoning.status="complete",V.reasoning.completedAt=Ve(h.completedAt??h.timestamp);let K=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-K),V.streaming=!1,f(V)}let $=G(h);$&&z.byStep.delete($)}else if(I==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??rt(h,!0)??`tool-${c()}`,R=h.toolName??h.name;if(Be(R)){te.add(W);continue}ue(Q(h),W);let B=$e(W),V=B.toolCall??{id:W,status:"pending"};V.name=R??V.name,V.status="running",h.parameters!==void 0?V.args=h.parameters:h.args!==void 0&&(V.args=h.args),V.startedAt=V.startedAt??Ve(h.startedAt??h.timestamp),V.completedAt=void 0,V.durationMs=void 0,B.toolCall=V,B.streaming=!0,h.executionId&&(B.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(B)}else if(I==="tool_output_delta"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W))continue;let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.startedAt=B.startedAt??Ve(h.startedAt??h.timestamp);let V=h.text??h.delta??h.message??"";V&&(B.chunks=B.chunks??[],B.chunks.push(String(V))),B.status="running",R.toolCall=B,R.streaming=!0;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R)}else if(I==="tool_complete"){let W=rt(h,!1)??rt(h,!0)??`tool-${c()}`;if(te.has(W)){te.delete(W);continue}let R=$e(W),B=R.toolCall??{id:W,status:"running"};B.status="complete",h.result!==void 0&&(B.result=h.result),typeof h.duration=="number"&&(B.duration=h.duration),B.completedAt=Ve(h.completedAt??h.timestamp);let V=h.duration??h.executionTime;if(typeof V=="number")B.durationMs=V;else{let de=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-de)}R.toolCall=B,R.streaming=!1;let $=h.agentContext;($||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),f(R);let K=Q(h);K&&Y.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,R=W??h.toolId??`local-${c()}`,B=$e(R),V=h.toolName,$=h.origin==="webmcp"&&!or(V)?`webmcp:${V}`:V,K=or($),de=B.toolCall??{id:R,status:"pending"};de.name=$,de.args=h.parameters,de.status=K?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Ve(h.startedAt??h.timestamp??h.awaitedAt),K?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,B.toolCall=de,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:h.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},f(B)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&R){L.set(W,R);continue}let B=x;B&&(Te==="flow"?(wn(B),et=B):(B.streaming=!1,f(B)),x=null),P=typeof h.id=="string"?h.id:P,T=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,R=W?L.get(W):void 0;if(W&&R){let V=typeof h.delta=="string"?h.delta:"",$=(O.get(W)??"")+V;if(O.set(W,$),$.trim()==="")continue;let K=An(W,R);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:R},vt(K,$,V,void 0);continue}if(P=typeof h.id=="string"?h.id:P,Te==="flow"){let V=typeof h.delta=="string"?h.delta:"";if(T+=V,T.trim()==="")continue;let $=me();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},vt($,T,V,void 0),C=$;continue}let B=me();B.content+=h.delta??"",B.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:Ae?.agentName},C=B,f(B)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&L.has(W)){let B=H.get(W);B&&wn(B),L.delete(W),O.delete(W),H.delete(W);continue}let R=x;R&&(Te==="flow"?(wn(R),et=R):((R.content??"")===""&&typeof h.text=="string"&&(R.content=h.text),R.streaming=!1,f(R)),x=null),P=null,T=""}else if(I==="step_complete"){let W=h.stepType,R=h.executionType;if(W==="tool"||R==="context")continue;if(h.success===!1){let B=h.error,V=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let $=x;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"});continue}{let B=et;et=null;let V=h.stopReason,$=h.result?.response;if(B)V&&(B.stopReason=V),$!=null?ct(B,$):B.streaming!==!1&&(_e.delete(B.id),we.delete(B.id),B.streaming=!1,f(B));else{let K=$!=null&&$!=="";if(K||V){let de=me();V&&(de.stopReason=V),K?wn(de,$):(de.streaming=!1,f(de))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",Ce=!0,Te==="agent"&&(Ae={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ve(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(Ae&&(Ae.currentIteration=W),ne==="separate"&&W>1){let R=x;R&&(R.streaming=!1,f(R),Sn.set(W-1,R),x=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??Y.lastId;if(W){let R=U.get(W);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(h.delta??""),f(R))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,R=x??C;if(W&&R!==null){let B=h.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=W,f(R))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ve.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ve.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),R=ve.get(W);ve.delete(W);let B=(typeof h.mediaType=="string"?h.mediaType:void 0)??R?.mediaType??"application/octet-stream",V=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(V)K={type:"media",data:V,mediaType:B};else if($){let Pe=B.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:B}}let de=h.toolCallId??R?.toolCallId,Ue=K?[K]:[],pe=[];for(let Pe of Ue){if(!Pe||typeof Pe!="object")continue;let ze=Pe,je=typeof ze.type=="string"?ze.type:void 0,He=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",Se=null,nt="";if(je==="media"){let St=typeof ze.data=="string"?ze.data:void 0;if(!St)continue;nt=He.length>0?He:"application/octet-stream",Se=`data:${nt};base64,${St}`}else if(je==="image-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else if(je==="file-url"){let St=typeof ze.url=="string"?ze.url:void 0;if(!St)continue;nt=He,Se=St}else continue;if(Se)if(je==="image-url"||nt.startsWith("image/"))pe.push({type:"image",image:Se,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))pe.push({type:"audio",audio:Se,mimeType:nt});else if(nt.startsWith("video/"))pe.push({type:"video",video:Se,mimeType:nt});else{let St=nt||"application/octet-stream";pe.push({type:"file",data:Se,mimeType:St,filename:xb(St)})}}if(pe.length>0){let Pe=c(),ze=de,He={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:pe,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};f(He);let Se=x;Se&&(Se.streaming=!1,f(Se)),x=null,S.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&Ae&&(Ae.status=h.success?"complete":"error",Ae.completedAt=Ve(h.completedAt),Ae.stopReason=h.stopReason);let R=x;R&&(W==="flow"&&R.streaming!==!1?wn(R):(R.streaming=!1,f(R)),x=null),P=null,T="",et=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let B={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(B)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,R=String(h.id),B=typeof h.title=="string"?h.title:void 0,V=h.file,$;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&($={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:R,artifactType:W,title:B,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(R,{markdown:"",title:B,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let de=to(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),Ue=typeof h.component=="string"?h.component:void 0,pe={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:_s(de,{artifactId:R,title:B,artifactType:W,status:"streaming",...$?{file:$}:{},...Ue?{component:Ue}:{}})};fe.set(R,pe),f(pe)}}else if(I==="artifact_delta"){let W=String(h.id),R=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:R});let B=he.get(W);B&&(B.markdown+=R)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let R=he.get(String(h.id));R&&(R.props={...R.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let R=fe.get(W);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let V=he.get(W);V?.markdown&&(B.props.markdown=V.markdown),V?.file&&(B.props.file=V.file),B.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(B.props.componentProps=V.props)}R.rawContent=JSON.stringify(B)}catch{}he.delete(W),f(R),fe.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let R=String(W.id??`msg-${c()}`),B=W.role,$={id:R,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(f($),$.rawContent)try{let de=JSON.parse($.rawContent)?.props?.artifactId;typeof de=="string"&&be.add(de)}catch{}x=null,S.current=null,_e.delete(R),we.delete(R)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let R=h.message??h.error;R!=null&&R!==""&&(W=new Error(String(R)))}else{let R=h.error;typeof R=="string"&&R!==""?W=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(W=new Error(String(R.message??R)))}if(W){n({type:"error",error:W});let R=x;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}Ze.length=0};;){let{done:E,value:I}=await s.read();if(E)break;i+=a.decode(I,{stream:!0});let h=i.split(`
12
12
 
13
13
  `);i=h.pop()??"";for(let W of h){let R=W.split(`
14
14
  `),B="message",V="",$=null;for(let pe of R)pe.startsWith("event:")?B=pe.replace("event:","").trim():pe.startsWith("data:")?V+=pe.replace("data:","").trim():pe.startsWith("id:")&&($=pe.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!V){K();continue}let de;try{de=JSON.parse(V)}catch(pe){n({type:"error",error:pe instanceof Error?pe:new Error("Failed to parse chat stream payload")});continue}let Ue=B!=="message"?B:de.type??"message";if(this.onSSEEvent?.(Ue,de),this.parseSSEEvent){S.current=x;let pe=await this.handleCustomSSEEvent(de,n,S,f,c,M);if(S.current&&S.current!==x&&(x=S.current),pe){K();continue}}Ze.push({payloadType:Ue,payload:de}),ke(),K()}}ke()}};function Ab(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Gs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function ir(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ci="[Image]";function Sb(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Tb(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function wc(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Eb(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function lr(e){return{type:"text",text:e}}function Mb(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function kb(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Lb(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var fg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pb=["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"],no=[...fg,...Pb];function Rb(e){return fg.includes(e)||e.startsWith("image/")}function di(e){return Rb(e.type)}async function mg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;di(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function hg(e,t=no,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Ib(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function yg(e,t){let n=Ib(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Ac();var bg=16e3,Wb=24e3,Hb=4096,Bb=1380533830;function Db(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Bb?new Uint8Array(e,44):new Uint8Array(e)}function Ob(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Js=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:bg,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:bg});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new qr(Wb);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(g=>g.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Ob(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=g=>this.handleMessage(g,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Hb,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let g=Math.max(-1,Math.min(1,p[c]));d[c]=g<0?g*32768:g*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Db(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var cr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Js(e.runtype);case"browser":if(!cr.isSupported())throw new Error("Browser speech recognition not supported");return new cr(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Sc(e){if(e?.type==="custom"&&e.custom)return dr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return dr({type:"runtype",runtype:e.runtype});if(cr.isSupported())return dr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function pi(e){try{return Sc(e),!0}catch{return!1}}function Ys(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var pr=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ys(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Vr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Tc(e){if(!e)return"";let t=Nb(e);return vg(t!==null?t:e)}function Nb(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function vg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`