@runtypelabs/persona 4.16.0 → 4.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},eh=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)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function yn(e){return e==="card"?"collapsed":e}function Ar(e){return e.split(";",1)[0].trim().toLowerCase()}function oh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ar(r)===t)return{mode:yn(s),selector:Ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ar(r)===o)return{mode:yn(s),selector:o}}function rh(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:yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ar(t.file.mimeType):void 0,u=l?oh(o.files.byMediaType,l):void 0;if(l&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:l,selector:u.selector}};if(o.files.default)return{mode:yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:yn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ho(e,t){return rh(e,t).mode}function xs(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 sh="agent_",ah="flow_";function Vp(e){return e.startsWith(sh)?{kind:"agentId",agentId:e}:e.startsWith(ah)?{kind:"flowId",flowId:e}:null}function qp(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),l=n.slice(o+1);if(a==="runtype"){let d=Vp(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[a];if(!u)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:u(l).payload}}let r=Vp(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 ih,ARR as lh,OBJ as ch,STR as dh}from"partial-json";var Rl="ask_user_question",Cs=8,Sr="data-persona-ask-sheet-for",ph="Other",uh="Other\u2026",Gp="Type your own answer here",Yp="Send",fh="Next",gh="Back",mh="Submit all",hh="Skip",yh=3,Hl="data-ask-current-index",Bl="data-ask-question-count",Xp="data-ask-answers",Dl="data-ask-grouped",Qp="data-ask-layout",bh=e=>e.layout==="pills"?"pills":"rows",vh=e=>e.getAttribute(Qp)==="pills"?"pills":"rows",Kp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Rl,Fl=e=>e?.features?.askUserQuestion??{},Tr=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=ih(r,dh|ch|lh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},As=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Cs&&!Kp&&(Kp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},wh=e=>As(e)[0]??null,xh=(e,t)=>As(e)[t]??null,Ch=(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))},Zp=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=b("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=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=b("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let u=Zp(n,o,t);u&&s.appendChild(u)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=b("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},Th=(e,t,n,o)=>{let s=b("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,u=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(u.length===0&&!n){for(let c=0;c<yh;c++)s.appendChild(Sh(o));return s}if(u.forEach((c,f)=>{s.appendChild(Ah(c,f,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ph:uh;if(o==="rows"){let f=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(u.length)),f.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Gp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),f.appendChild(w);let v=Zp(o,a,u.length);v&&f.appendChild(v),s.appendChild(f)}else{let f=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,s.appendChild(f)}}return s},eu=(e,t)=>{let o=b("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??Gp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=b("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Yp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Yp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Eh=(e,t,n)=>{let o=b("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=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??hh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let u=e===t-1;return l.textContent=u?n.submitAllLabel??mh:n.nextLabel??fh,l.setAttribute("data-ask-user-action",u?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(Xp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(e,t)=>{e.setAttribute(Xp,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(Hl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Bl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Dl)==="true",Lh=(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 l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ph=(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)))},Na=(e,t)=>{let{payload:n}=Tr(t),o=As(n),r=Ko(e),s={},a=new Set;return o.forEach((l,u)=>{let d=typeof l?.question=="string"?l.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,u)&&(s[d]=r[u]))}),s},nu=e=>{let t=Ko(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(u=>r.add(u));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(u=>{let d=u.getAttribute("data-option-label")??"",c=r.has(d);u.setAttribute("aria-pressed",c?"true":"false"),u.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(u=>u.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ou=e=>{if(!yo(e))return;let t=Ko(e),n=bn(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 l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ol=(e,t,n)=>{let o=Fl(n),r=vh(e),{payload:s,complete:a}=Tr(t),l=yo(e),u=bn(e),d=Mr(e),c=l?xh(s,u):wh(s),f=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${u+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let S=typeof c?.question=="string"?c.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=Th(c,o,a,r);C.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(eu(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(Mh(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=Eh(u,d,o);B?B.replaceWith(S):e.appendChild(S)}else B&&B.remove();nu(e),ou(e)},Ih=(e,t,n)=>{let o=Fl(t),r=bh(o),s=e.toolCall.id,a=As(n),l=Math.max(1,a.length),u=l>1,d=Lh(e,a),c=u?Ph(e,l):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sr,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(Bl,String(l)),f.setAttribute(Hl,String(c)),f.setAttribute(Dl,u?"true":"false"),f.setAttribute(Qp,r),tu(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(f,o);let w=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),f.appendChild(w);let T=b("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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(eu(o,r)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wh=(e,t,n)=>{let{payload:o}=Tr(t),r=Math.max(1,As(o).length);r>Mr(e)&&(e.setAttribute(Bl,String(r)),r>1&&!yo(e)&&e.setAttribute(Dl,"true")),Ol(e,t,n)};var _a=(e,t,n)=>{if(!n||!qo(e)||Fl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Wh(a,e,t);return}let{payload:l}=Tr(e),u=Ih(e,t,l);n.appendChild(u)},Er=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;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)})},Nl=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),bo=(e,t)=>{let n=Ko(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tu(e,n),nu(e),ou(e)},$a=(e,t,n,o)=>{let r=Mr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Ol(e,t,n)};var Xn="suggest_replies";var Rh={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},su={name:Xn,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:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>e.variant==="tool"&&e.toolCall?.name===Xn,Hh=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 l=r.trim();return l?[l]:[]}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},au=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ss(n))continue;let o=Hh(n.toolCall?.args);return o.length>0?o:null}return null},ru=new Set,Bh=(e,t,n)=>{let o=`${e}:${t}:${n}`;ru.has(o)||(ru.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},vo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],u=n?.[a];l===void 0||u===void 0||l!==u&&Bh(a,u,l)};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 Dh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,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},Fh={name:Rl,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:Dh,origin:"sdk",annotations:{readOnlyHint:!0}},Ua=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fh),vo(e).expose&&t.push(su),t};import{parse as Oh,STR as Nh,OBJ as _h}from"partial-json";var iu=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=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)}},$h=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`},lu=e=>e.status==="complete"?$h(e):e.status==="pending"?"Waiting":"",Uh=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 cu=e=>e.status==="complete"?Uh(e):"Using tool...",za=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Ms=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 za(t)},ja=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return za(t)},$l=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Ms(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Va=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Ts(o,n.slice(s,a.index),[]),a[1]!==void 0?Ts(o,a[1],["bold"]):a[2]!==void 0?Ts(o,a[2],["italic"]):a[3]!==void 0&&Ts(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ts(o,n.slice(s),[]),o},Ts=(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})},zh=()=>{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*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();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)}},uu=()=>{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=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{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 gu="4.16.0";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(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 Ul=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 Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(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=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=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??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(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 Oa(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=qp(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$/,"")||qa}/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":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.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$/,"")||qa}/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":ks},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(Ul).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:l,commit:u}=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":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let 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 l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}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 l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}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$/,"")||qa}/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?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,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(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),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(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(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(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(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 l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={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=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.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)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.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=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=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()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.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}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.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}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,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(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}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 L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="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(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}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 L=v;L&&L.streaming&&(L.streaming=!1,g(L)),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 L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();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)}},uu=()=>{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=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{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 gu="4.17.0";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(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 Ul=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 Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(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=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=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??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(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 Oa(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=qp(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$/,"")||qa}/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":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.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$/,"")||qa}/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":ks},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(Ul).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:l,commit:u}=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":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let 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 l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}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 l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}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$/,"")||qa}/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?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,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(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),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(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(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(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(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 l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={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=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.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)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.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=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=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()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.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}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.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}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,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(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}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 L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="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(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}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 L=v;L&&L.streaming&&(L.streaming=!1,g(L)),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 L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
12
12
 
13
13
  `);l=h.pop()??"";for(let W of h){let L=W.split(`
14
14
  `),R="message",q="",$=null;for(let de of L)de.startsWith("event:")?R=de.replace("event:","").trim():de.startsWith("data:")?q+=de.replace("data:","").trim():de.startsWith("id:")&&($=de.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!q){K();continue}let ce;try{ce=JSON.parse(q)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let je=R!=="message"?R:ce.type??"message";if(this.onSSEEvent?.(je,ce),this.parseSSEEvent){T.current=v;let de=await this.handleCustomSSEEvent(ce,n,T,g,c,B);if(T.current&&T.current!==v&&(v=T.current),de){K();continue}}et.push({payloadType:je,payload:ce}),Le(),K()}}Le()}};function Ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Lr(e){return{type:"text",text:e}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yh=["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"],Qn=[...yu,...Yh];function Xh(e){return yu.includes(e)||e.startsWith("image/")}function Ya(e){return Xh(e.type)}async function bu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(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 vu(e,t=Qn,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 Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wu(e,t){let n=Qh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var xu=16e3,Jh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(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 Ps=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:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:xu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mp(Jh);if(r!==this.callGeneration){u.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ny(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let w=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),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(Zh,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let u=l.inputBuffer.getChannelData(0),d=new Int16Array(u.length);for(let c=0;c<u.length;c++){let f=Math.max(-1,Math.min(1,u[c]));d[c]=f<0?f*32768:f*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=ty(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 Go=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 Pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!Go.isSupported())throw new Error("Browser speech recognition not supported");return new Go(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 Cu(e){if(e?.type==="custom"&&e.custom)return Pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Pr({type:"runtype",runtype:e.runtype});if(Go.isSupported())return Pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zl(e){try{return Cu(e),!0}catch{return!1}}function Xa(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 Ir=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(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xa(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 l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Is=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 jl(e){if(!e)return"";let t=oy(e);return Au(t!==null?t:e)}function oy(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 Au(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,`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/persona",
3
- "version": "4.16.0",
3
+ "version": "4.17.0",
4
4
  "description": "Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -80,7 +80,7 @@
80
80
  ],
81
81
  "dependencies": {
82
82
  "@mcp-b/webmcp-polyfill": "^3.0.0",
83
- "dompurify": "^3.4.10",
83
+ "dompurify": "^3.4.13",
84
84
  "idiomorph": "^0.7.4",
85
85
  "lucide": "^1.18.0",
86
86
  "marked": "^12.0.2",
@@ -404,12 +404,46 @@ describe("install.ts: CDN base derivation", () => {
404
404
  expect(cssHref).toBe("https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/widget.css");
405
405
  });
406
406
 
407
- it("an explicit `version` opts back into npm-CDN URLs even when the src is derivable", async () => {
407
+ it("an explicit `version` on the first-party CDN stays first-party (versioned path)", async () => {
408
408
  setCurrentScript("https://cdn.runtype.com/persona/latest/install.global.js");
409
+ const { cssHref, scripts } = await installedUrls({ version: "1.2.3" });
410
+ expect(cssHref).toBe("https://cdn.runtype.com/persona/1.2.3/widget.css");
411
+ expect(scripts).toContain("https://cdn.runtype.com/persona/1.2.3/launcher.global.js");
412
+ });
413
+
414
+ it("an explicit `version` on a non-first-party src opts into npm-CDN URLs", async () => {
415
+ setCurrentScript("https://assets.example.com/vendor/persona/install.global.js");
409
416
  const { cssHref } = await installedUrls({ version: "1.2.3" });
410
417
  expect(cssHref).toBe("https://cdn.jsdelivr.net/npm/@runtypelabs/persona@1.2.3/dist/widget.css");
411
418
  });
412
419
 
420
+ it("warns when resolved assets leave the installer's origin (silent-CSP guard)", async () => {
421
+ setCurrentScript("https://cdn.runtype.com/persona/latest/install.global.js");
422
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
423
+ await installedUrls({ cdn: "jsdelivr" });
424
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("strict CSP may silently block"));
425
+ warn.mockRestore();
426
+ });
427
+
428
+ it("does not warn when assets resolve to the installer's own origin", async () => {
429
+ setCurrentScript("https://cdn.runtype.com/persona/latest/install.global.js");
430
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
431
+ await installedUrls({ version: "1.2.3" });
432
+ expect(warn).not.toHaveBeenCalled();
433
+ warn.mockRestore();
434
+ });
435
+
436
+ it("does not warn for explicit cssUrl + jsUrl overrides on another origin", async () => {
437
+ setCurrentScript("https://cdn.runtype.com/persona/latest/install.global.js");
438
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
439
+ await installedUrls({
440
+ cssUrl: "https://assets.example.com/persona/widget.css",
441
+ jsUrl: "https://assets.example.com/persona/index.global.js",
442
+ });
443
+ expect(warn).not.toHaveBeenCalled();
444
+ warn.mockRestore();
445
+ });
446
+
413
447
  it("an explicit `cdn` opts back into npm-CDN URLs even when the src is derivable", async () => {
414
448
  setCurrentScript("https://cdn.runtype.com/persona/latest/install.global.js");
415
449
  const { cssHref } = await installedUrls({ cdn: "unpkg" });
package/src/install.ts CHANGED
@@ -7,9 +7,12 @@
7
7
  export {};
8
8
 
9
9
  interface SiteAgentInstallConfig {
10
- // Setting `version` or `cdn` explicitly opts into npm-CDN asset URLs
11
- // (jsDelivr/unpkg). When neither is set, assets load from the directory the
12
- // installer script itself was served from — see getCdnBase().
10
+ // Setting `cdn` explicitly opts into npm-CDN asset URLs (jsDelivr/unpkg),
11
+ // and `version` pins the asset version. When neither is set, assets load
12
+ // from the directory the installer script itself was served from. On the
13
+ // first-party CDN (cdn.runtype.com) a `version` stays first-party
14
+ // (…/persona/<version>/); elsewhere it opts into npm-CDN URLs. Prefer
15
+ // pinning via the installer script URL itself — see getCdnBase().
13
16
  version?: string;
14
17
  cdn?: "unpkg" | "jsdelivr";
15
18
  cssUrl?: string;
@@ -239,16 +242,30 @@ declare global {
239
242
 
240
243
  // Default: load assets from wherever the installer was served, so a page
241
244
  // whose CSP allows only its own CDN (e.g. cdn.runtype.com) never has
242
- // sibling requests fan out to a third-party host. An explicit `cdn` or
243
- // `version` keeps the documented npm-CDN behavior.
244
- if (!config.cdn && !config.version) {
245
+ // sibling requests fan out to a third-party host. An explicit `cdn`
246
+ // keeps the documented npm-CDN behavior.
247
+ if (!config.cdn) {
245
248
  const selfBase = getInstallerBase();
246
249
  if (selfBase) {
247
- return {
248
- cssUrl: `${selfBase}/widget.css`,
249
- jsUrl: `${selfBase}/index.global.js`,
250
- launcherUrl: `${selfBase}/launcher.global.js` as string | null,
251
- };
250
+ if (!config.version) {
251
+ return {
252
+ cssUrl: `${selfBase}/widget.css`,
253
+ jsUrl: `${selfBase}/index.global.js`,
254
+ launcherUrl: `${selfBase}/launcher.global.js` as string | null,
255
+ };
256
+ }
257
+ // A `version` on the first-party CDN stays first-party: the bucket
258
+ // mirrors every release at /persona/<version>/, and rerouting to a
259
+ // npm CDN would be blocked by the CSP that allowed the installer.
260
+ const selfOrigin = new URL(selfBase).origin;
261
+ if (selfOrigin === "https://cdn.runtype.com") {
262
+ const base = `${selfOrigin}/persona/${config.version}`;
263
+ return {
264
+ cssUrl: `${base}/widget.css`,
265
+ jsUrl: `${base}/index.global.js`,
266
+ launcherUrl: `${base}/launcher.global.js` as string | null,
267
+ };
268
+ }
252
269
  }
253
270
  }
254
271
 
@@ -268,6 +285,25 @@ declare global {
268
285
 
269
286
  const { cssUrl, jsUrl, launcherUrl } = getCdnBase();
270
287
 
288
+ // Surface silent CSP breakage: when `cdn`/`version` reroutes assets to a
289
+ // different origin than the one that served the installer, a strict CSP
290
+ // (e.g. Runtype-hosted apps) blocks them with no visible error. Explicit
291
+ // cssUrl/jsUrl overrides are a deliberate choice, so they don't warn.
292
+ if (!(config.cssUrl && config.jsUrl)) {
293
+ const selfBase = getInstallerBase();
294
+ try {
295
+ if (selfBase && new URL(selfBase).origin !== new URL(jsUrl, document.baseURI).origin) {
296
+ console.warn(
297
+ `[persona] Widget assets resolve to ${new URL(jsUrl, document.baseURI).origin}, but the installer loaded from ${new URL(selfBase).origin}. ` +
298
+ "A strict CSP may silently block them. To pin a version, put it in the installer script URL " +
299
+ "(e.g. https://cdn.runtype.com/persona/<version>/install.global.js) instead of the `version`/`cdn` config keys.",
300
+ );
301
+ }
302
+ } catch {
303
+ // URL parsing is best-effort; never let diagnostics break installation.
304
+ }
305
+ }
306
+
271
307
  // Check if CSS is already loaded
272
308
  const isCssLoaded = () => {
273
309
  return !!document.head.querySelector('link[data-persona]') ||