@runtypelabs/persona 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -116,7 +116,7 @@ The full reference lives in [`docs/`](./docs/) and the theming guide:
116
116
 
117
117
  - [Extending Persona](./docs/EXTENDING.md): the map of every extension point: plugins, components, postprocessors, themes, stream parsers, animations, voice, sanitization, actions, context/WebMCP, layout slots, storage, and UI builders, each linked to its deep dive
118
118
  - [Authoring Plugins](./docs/PLUGINS.md): the `AgentWidgetPlugin` contract, all 14 render hooks, global vs per-instance registration, lifecycle, and the `@runtypelabs/persona/plugin-kit` helpers
119
- - [Publishing Plugins](./docs/PUBLISHING-PLUGINS.md): naming + npm-keyword convention, peer/external setup, and a package skeleton for shipping plugins, themes, and adapters
119
+ - [Contributing](../../CONTRIBUTING.md): current guidance for contributing plugins, themes, adapters, examples, and other customizations back to this monorepo
120
120
  - [Programmatic Control & Events](./docs/PROGRAMMATIC-CONTROL.md): controller API, message hooks and injection, enriched DOM context, WebMCP page tools, DOM and controller events, state loading
121
121
  - [UI Features & Components](./docs/UI-COMPONENTS.md): message actions and feedback, loading/idle indicators, approvals, built-in `ask_user_question` and `suggest_replies` tools, dropdown menus, button utilities, dynamic forms
122
122
  - [Script Tag Installation & Framework Integration](./docs/INSTALLATION-FRAMEWORKS.md): automatic installer, deferred launcher lifecycle hooks, manual script tag setup, React, Next.js, Remix, Gatsby, and Astro guides
package/dist/codegen.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},W=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of T(r))!M.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=_(r,o))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var B={};R(B,{generateCodeSnippet:()=>v});module.exports=H(B);var x="4.3.0";var c=x;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function k(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,r)=>{for(var n in r)$(e,n,{get:r[n],enumerable:!0})},W=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of T(r))!M.call(e,o)&&o!==n&&$(e,o,{get:()=>r[o],enumerable:!(s=_(r,o))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var B={};R(B,{generateCodeSnippet:()=>v});module.exports=H(B);var x="4.3.1";var c=x;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function k(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
package/dist/codegen.js CHANGED
@@ -1,4 +1,4 @@
1
- var S="4.3.0";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function I(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
1
+ var S="4.3.1";var c=S;function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function I(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var x=`({ text, message }: any) => {
2
2
  const jsonSource = (message as any).rawContent || text || message.content;
3
3
  if (!jsonSource || typeof jsonSource !== 'string') return null;
4
4
  let cleanJson = jsonSource
package/dist/index.cjs CHANGED
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},Bh=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)}},Dh=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)}};var Oh="agent_",Fh="flow_";function ym(e){return e.startsWith(Oh)?{kind:"agentId",agentId:e}:e.startsWith(Fh)?{kind:"flowId",flowId:e}:null}function bm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=ym(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=ym(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var bo=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},oa=(...e)=>e.filter(Boolean).join(" ");var aa="ask_user_question",sa=8,Ts="data-persona-ask-sheet-for",_h="Other",$h="Other\u2026",vm="Type your own answer here",wm="Send",jh="Next",Uh="Back",qh="Submit all",zh="Skip",Vh=3,bl="data-ask-current-index",xl="data-ask-question-count",Cm="data-ask-answers",vl="data-ask-grouped",Am="data-ask-layout",Kh=e=>e.layout==="pills"?"pills":"rows",Gh=e=>e.getAttribute(Am)==="pills"?"pills":"rows",xm=!1,Sm=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===aa,Ga=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,bo.parse)(o,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ia=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>sa&&!xm&&(xm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${sa}.`)),t.slice(0,sa)},Jh=e=>{var t;return(t=ia(e)[0])!=null?t:null},Xh=(e,t)=>{var n;return(n=ia(e)[t])!=null?n:null},Tm=(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))},Em=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Qh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Em(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Yh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Zh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Vh;f++)s.appendChild(Yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(Qh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?_h:$h;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(p=t.freeTextPlaceholder)!=null?p:vm,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(M),v.appendChild(x);let E=Em(r,a,d.length);E&&v.appendChild(E),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Mm=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:vm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:wm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},ey=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:wm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ty=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Uh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:zh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:qh:(g=n.nextLabel)!=null?g:jh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(Cm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},km=(e,t)=>{e.setAttribute(Cm,JSON.stringify(t))},ir=e=>{var n;let t=Number((n=e.getAttribute(bl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ny=(e,t)=>{e.setAttribute(bl,String(Math.max(0,Math.floor(t))))},Es=e=>{var n;let t=Number((n=e.getAttribute(xl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(vl)==="true",ry=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},oy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ja=(e,t)=>{let{payload:n}=Xr(t),r=ia(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Lm=e=>{let t=Go(e),n=ir(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Pm=e=>{if(!xo(e))return;let t=Go(e),n=ir(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},wl=(e,t,n)=>{let r=Ga(n),o=Gh(e),{payload:s,complete:a}=Xr(t),i=xo(e),d=ir(e),l=Es(e),p=i?Xh(s,d):Jh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=P,v.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let P=Zh(p,r,a,o);x.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Mm(r,o))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(ey(r)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=ty(d,l,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();Lm(e),Pm(e)},sy=(e,t,n)=>{let r=Ga(t),o=Kh(r),s=e.toolCall.id,a=ia(n),i=Math.max(1,a.length),d=i>1,l=ry(e,a),p=d?oy(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ts,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(xl,String(i)),u.setAttribute(bl,String(p)),u.setAttribute(vl,d?"true":"false"),u.setAttribute(Am,o),km(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Tm(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let M=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),o!=="rows"&&u.appendChild(Mm(r,o)),wl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ay=(e,t,n)=>{let{payload:r}=Xr(t),o=Math.max(1,ia(r).length);o>Es(e)&&(e.setAttribute(xl,String(o)),o>1&&!xo(e)&&e.setAttribute(vl,"true")),wl(e,t,n)},Im=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ga(t);Tm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=Xr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ms=(e,t,n)=>{if(!n||!Jr(e)||Ga(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ts}]`).forEach(l=>{l.getAttribute(Ts)!==o&&l.remove()});let a=n.querySelector(`[${Ts}="${Sm(o)}"]`);if(a){ay(a,e,t);return}let{payload:i}=Xr(e),d=sy(e,t,i);n.appendChild(d)},vo=(e,t)=>{if(!e)return;let n=t?`[${Ts}="${Sm(t)}"]`:`[${Ts}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Cl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),wo=(e,t)=>{let n=Go(e),r=ir(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,km(e,n),Lm(e),Pm(e)},Xa=(e,t,n,r)=>{let o=Es(e),s=Math.max(0,Math.min(o-1,r));ny(e,s),wl(e,t,n)};var xr="suggest_replies";var Al={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Qa={name:xr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Al,origin:"sdk",annotations:{readOnlyHint:!0}},Sl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),la=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===xr},Tl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Ya=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!la(r))continue;let o=Tl((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Rm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var El={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:sa,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},Ml={name:aa,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:El,origin:"sdk",annotations:{readOnlyHint:!0}},ca=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Ml),Rm(e)&&t.push(Qa),t};var Qr=require("partial-json"),Za=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Co=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)}},iy=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Wm=e=>e.status==="complete"?iy(e):e.status==="pending"?"Waiting":"",ly=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Hm=e=>e.status==="complete"?ly(e):"Using tool...",ei=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},pa=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ei(t)},ti=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ei(t)},kl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=pa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},ni=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&da(r,n.slice(s,a.index),[]),a[1]!==void 0?da(r,a[1],["bold"]):a[2]!==void 0?da(r,a[2],["italic"]):a[3]!==void 0&&da(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&da(r,n.slice(s),[]),r},da=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},cy=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ua=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ri=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},oi=()=>{var t;let e=cy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},si=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Qr.parse)(n,Qr.STR|Qr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Za(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Za(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Bm=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Za(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Qr.parse)(s,Qr.STR|Qr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ai=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Dm="4.3.0";var lr=Dm;var py="https://api.runtype.com/v1/dispatch",ii="https://api.runtype.com";function uy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ll=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 my(e){switch(e){case"json":return si;case"regex-json":return oi;case"xml":return ai;default:return ri}}var Nm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function gy(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Nm(n);if(!Nm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=ua(e);return ua(t)!==null&&a===null?t:e}var Jo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:py,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:my(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ss(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=bm(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Ll).map(k=>{var I,C,W;return{id:k.id,role:k.role,content:(W=(C=(I=k.contentParts)!=null?I:k.llmContent)!=null?C:k.rawContent)!=null?W:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?hm(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&x&&this.lastSentClientToolsFingerprint===v,E=!1,P=null,L;for(let k=0;;k++){let C={...u,...f&&(E||!M)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(C),signal:r.signal}),L.status===409&&k===0&&f){let W=await L.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=W!=null?W:{error:"Chat request failed"}}break}if(!L.ok){let k=P!=null?P:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(L.status===429){let C=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!L.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ii}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Ll).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ca(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Ll).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...ca(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Dt,Yt,Or,wr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=S=>{let ne=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,Me=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,De=S.tools?S.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...S,reasoning:ne,toolCall:Me,tools:De}},u=S=>{if(S.role!=="assistant"||S.variant)return!0;let ne=Array.isArray(S.contentParts)&&S.contentParts.length>0,Me=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||ne||Me||!!S.stopReason},g=S=>{u(S)&&n({type:"message",message:p(S)})},f=null,v=null,x={current:null},M={current:null},E=null,P="",L=new Map,k=new Map,I=new Map,C=new Map,W=new Map,_={lastId:null,byStep:new Map},U={lastId:null,byCall:new Map},H=S=>{if(S==null)return null;try{return String(S)}catch{return null}},F=S=>{var ne,Me,De,Pe,Ne;return H((Ne=(Pe=(De=(Me=(ne=S.stepId)!=null?ne:S.step_id)!=null?Me:S.step)!=null?De:S.parentId)!=null?Pe:S.flowStepId)!=null?Ne:S.flow_step_id)},O=S=>{var ne,Me,De,Pe,Ne,Je,lt;return H((lt=(Je=(Ne=(Pe=(De=(Me=(ne=S.callId)!=null?ne:S.call_id)!=null?Me:S.requestId)!=null?De:S.request_id)!=null?Pe:S.toolCallId)!=null?Ne:S.tool_call_id)!=null?Je:S.stepId)!=null?lt:S.step_id)},ee=r,Ee=!1,ue=()=>{if(f)return f;let S,ne=E;return!Ee&&ee?(S=ee,Ee=!0):ee&&ne?S=`${ee}_${ne}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},te=(S,ne)=>{_.lastId=ne,S&&_.byStep.set(S,ne)},ve=(S,ne)=>{var Ne;let Me=(Ne=S.reasoningId)!=null?Ne:S.id,De=F(S);if(Me){let Je=String(Me);return te(De,Je),Je}if(De){let Je=_.byStep.get(De);if(Je)return _.lastId=Je,Je}if(_.lastId&&!ne)return _.lastId;if(!ne)return null;let Pe=`reason-${l()}`;return te(De,Pe),Pe},ke=S=>{let ne=C.get(S);if(ne)return ne;let Me={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:S,status:"streaming",chunks:[]}};return C.set(S,Me),g(Me),Me},se=(S,ne)=>{U.lastId=ne,S&&U.byCall.set(S,ne)},xe=new Set,pe=new Map,ie=new Set,ae=new Map,He=S=>{if(!S)return!1;let ne=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return ne==="emit_artifact_markdown"||ne==="emit_artifact_component"},Fe=(S,ne)=>{var Ne;let Me=(Ne=S.toolId)!=null?Ne:S.id,De=O(S);if(Me){let Je=String(Me);return se(De,Je),Je}if(De){let Je=U.byCall.get(De);if(Je)return U.lastId=Je,Je}if(U.lastId&&!ne)return U.lastId;if(!ne)return null;let Pe=`tool-${l()}`;return se(De,Pe),Pe},K=S=>{let ne=W.get(S);if(ne)return ne;let Me={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:S,status:"pending"}};return W.set(S,Me),g(Me),Me},G=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let ne=Number(S);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let Me=Date.parse(S);if(!Number.isNaN(Me))return Me}return Date.now()},we=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},X=new Map,de=new Map,We=new Map,fe=(S,ne,Me)=>{var lt;let De=We.get(S);De||(De=[],We.set(S,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<ne?Pe=It+1:Ne=It}((lt=De[Pe])==null?void 0:lt.seq)===ne?De[Pe]={seq:ne,text:Me}:De.splice(Pe,0,{seq:ne,text:Me});let Je="";for(let It=0;It<De.length;It++)Je+=De[It].text;return Je},Ge=(S,ne)=>{let Me=we(ne),De=de.get(S.id),Pe=gy(De,Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=Y=>{var ct;let Te=(ct=S.content)!=null?ct:"";Y.trim()!==""&&(Te.trim().length===0||Y.startsWith(Te)||Y.trimStart().startsWith(Te.trim()))&&(S.content=Y)},lt=()=>{var Y;if(Ne){let Te=(Y=Ne.close)==null?void 0:Y.call(Ne);Te instanceof Promise&&Te.catch(()=>{})}X.delete(S.id),de.delete(S.id),S.streaming=!1,g(S)};if(!Ne){Je(Me),lt();return}let It=ua(Pe);if(It!==null&&It.trim()!==""){Je(It),lt();return}let xt=Y=>{var Ye;let Te=typeof Y=="string"?Y:(Ye=Y==null?void 0:Y.text)!=null?Ye:null;if(Te!==null&&Te.trim()!=="")return Te;let ct=Ne.getExtractedText();return ct!==null&&ct.trim()!==""?ct:Me},B;try{B=Ne.processChunk(Pe)}catch{Je(Me),lt();return}if(B instanceof Promise){B.then(Y=>{Je(xt(Y)),lt()}).catch(()=>{Je(Me),lt()});return}Je(xt(B)),lt()},nt=null,Pt=(S,ne,Me,De)=>{var It;S.rawContent=ne,X.has(S.id)||X.set(S.id,this.createStreamParser());let Pe=X.get(S.id),Ne=ne.trim().startsWith("{")||ne.trim().startsWith("[");if(Ne&&de.set(S.id,ne),Pe.__isPlainTextParser===!0){S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S);return}let lt=Pe.processChunk(ne);if(lt instanceof Promise)lt.then(xt=>{var Y;let B=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;B!==null&&B.trim()!==""?(S.content=B,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S)});else{let xt=typeof lt=="string"?lt:(It=lt==null?void 0:lt.text)!=null?It:null;xt!==null&&xt.trim()!==""?(S.content=xt,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}},Ze=(S,ne)=>{var It,xt;let Me=ne!=null?ne:S.content;if(Me==null||Me===""){S.streaming=!1,g(S);return}let De=de.get(S.id),Pe=De!=null?De:we(Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=null,lt=!1;if(Ne&&(Je=Ne.getExtractedText(),Je===null&&(Je=ua(Pe)),Je===null)){let B=Ne.processChunk(Pe);B instanceof Promise?(lt=!0,B.then(Y=>{var ct;let Te=typeof Y=="string"?Y:(ct=Y==null?void 0:Y.text)!=null?ct:null;Te!==null&&(S.content=Te,S.streaming=!1,X.delete(S.id),de.delete(S.id),g(S))}).catch(()=>{})):Je=typeof B=="string"?B:(It=B==null?void 0:B.text)!=null?It:null}if(!lt){Je!==null&&Je.trim()!==""?S.content=Je:de.has(S.id)||(S.content=we(Me));let B=X.get(S.id);if(B){let Y=(xt=B.close)==null?void 0:xt.call(B);Y instanceof Promise&&Y.catch(()=>{}),X.delete(S.id)}de.delete(S.id),S.streaming=!1,g(S)}},$e=(S,ne,Me)=>{let De=k.get(S);if(De)return De;let Pe={id:`nested-${ne}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ne}};return k.set(S,Pe),g(Pe),Pe},J=[],Ve,ze=new Map,Ce=0,Se="agent",rt=!1,_t=null,re=null,je=new Map,yn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(Ve=()=>{var S,ne,Me,De,Pe,Ne,Je,lt,It,xt,B,Y,Te,ct,Ye,Ut,bn,vt,wt,Rt,Ct,pn,$t,On,Tn,En,vn,Mn,dr,At,Cr,Ar,Fr,pr,mt,Io,Sr,Ro,Wn,is,ro,_r,oo,so,Wo,Ho,ao,bt,Fn,_n,kn,St,Zn,er,$n,io,$r,lo,jn,Wt,Ln,tr,co,jr,po,ye,Hn,Tr,gt,sn,an,Er,Us,Ur,Bo,Mr,j,ls,kr,Lr,qr,Pr,ur,cs,Da,Un,qn,mr,gr,Do,zr,wn,Ir,ds,No,ps,Na,us,Oa,ms,ut,qs,nr,Bn,Fa;for(let gs=0;gs<J.length;gs++){let tt=J[gs].payloadType,w=J[gs].payload;if(!rt&&Se!=="flow"&&typeof w.stepType=="string"&&(Se="flow"),tt==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q),$e(V,q,"reasoning");continue}let Q=(S=ve(w,!0))!=null?S:`reason-${l()}`,he=ke(Q);he.reasoning=(ne=he.reasoning)!=null?ne:{id:Q,status:"streaming",chunks:[]},he.reasoning.startedAt=(De=he.reasoning.startedAt)!=null?De:G((Me=w.startedAt)!=null?Me:w.timestamp),he.reasoning.completedAt=void 0,he.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),he.streaming=!0,he.reasoning.status="streaming",g(he)}else if(tt==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let _e=k.get(V),ft=(Je=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Je:"";ft&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(ft)),g(_e));continue}let q=(It=(lt=ve(w,!1))!=null?lt:ve(w,!0))!=null?It:`reason-${l()}`,Q=ke(q);Q.reasoning=(xt=Q.reasoning)!=null?xt:{id:q,status:"streaming",chunks:[]},Q.reasoning.startedAt=(Y=Q.reasoning.startedAt)!=null?Y:G((B=w.startedAt)!=null?B:w.timestamp);let he=(Ye=(ct=(Te=w.reasoningText)!=null?Te:w.text)!=null?ct:w.delta)!=null?Ye:"";if(he&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let ft=fe(q,_e,String(he));Q.reasoning.chunks=[ft]}else Q.reasoning.chunks.push(String(he))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=G((Ut=w.completedAt)!=null?Ut:w.timestamp);let _e=(bn=Q.reasoning.startedAt)!=null?bn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-_e)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let ft=k.get(V);if(ft.reasoning){let at=typeof w.text=="string"?w.text:"";at&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(at),ft.reasoning.status="complete",ft.streaming=!1,g(ft)}L.delete(V),k.delete(V);continue}let q=(Rt=(wt=ve(w,!1))!=null?wt:ve(w,!0))!=null?Rt:`reason-${l()}`,Q=typeof w.text=="string"?w.text:"";!C.get(q)&&(Q||w.scope==="loop")&&ke(q);let he=C.get(q);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),Q&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(Q),he.reasoning.status="complete",he.reasoning.completedAt=G((Ct=w.completedAt)!=null?Ct:w.timestamp);let ft=(pn=he.reasoning.startedAt)!=null?pn:Date.now();he.reasoning.durationMs=Math.max(0,(($t=he.reasoning.completedAt)!=null?$t:Date.now())-ft),he.streaming=!1,g(he)}let _e=F(w);_e&&_.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(Tn=(On=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?On:Fe(w,!0))!=null?Tn:`tool-${l()}`,q=(En=w.toolName)!=null?En:w.name;if(He(q)){xe.add(V);continue}se(O(w),V);let Q=K(V),he=(vn=Q.toolCall)!=null?vn:{id:V,status:"pending"};he.name=q!=null?q:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(dr=he.startedAt)!=null?dr:G((Mn=w.startedAt)!=null?Mn:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,Q.toolCall=he,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let V=(Cr=(At=Fe(w,!1))!=null?At:Fe(w,!0))!=null?Cr:`tool-${l()}`;if(xe.has(V))continue;let q=K(V),Q=(Ar=q.toolCall)!=null?Ar:{id:V,status:"running"};Q.startedAt=(pr=Q.startedAt)!=null?pr:G((Fr=w.startedAt)!=null?Fr:w.timestamp);let he=(Sr=(Io=(mt=w.text)!=null?mt:w.delta)!=null?Io:w.message)!=null?Sr:"";he&&(Q.chunks=(Ro=Q.chunks)!=null?Ro:[],Q.chunks.push(String(he))),Q.status="running",q.toolCall=Q,q.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(ro=q.agentMetadata)!=null?ro:{executionId:(Wn=_e==null?void 0:_e.executionId)!=null?Wn:w.executionId,iteration:(is=_e==null?void 0:_e.iteration)!=null?is:w.iteration}),g(q)}else if(tt==="tool_complete"){let V=(oo=(_r=Fe(w,!1))!=null?_r:Fe(w,!0))!=null?oo:`tool-${l()}`;if(xe.has(V)){xe.delete(V);continue}let q=K(V),Q=(so=q.toolCall)!=null?so:{id:V,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=G((Wo=w.completedAt)!=null?Wo:w.timestamp);let he=(Ho=w.duration)!=null?Ho:w.executionTime;if(typeof he=="number")Q.durationMs=he;else{let at=(ao=Q.startedAt)!=null?ao:Date.now();Q.durationMs=Math.max(0,((bt=Q.completedAt)!=null?bt:Date.now())-at)}q.toolCall=Q,q.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(kn=q.agentMetadata)!=null?kn:{executionId:(Fn=_e==null?void 0:_e.executionId)!=null?Fn:w.executionId,iteration:(_n=_e==null?void 0:_e.iteration)!=null?_n:w.iteration}),g(q);let ft=O(w);ft&&U.byCall.delete(ft)}else if(tt==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(St=V!=null?V:w.toolId)!=null?St:`local-${l()}`,Q=K(q),he=w.toolName,_e=w.origin==="webmcp"&&!yo(he)?`webmcp:${he}`:he,ft=yo(_e),at=(Zn=Q.toolCall)!=null?Zn:{id:q,status:"pending"};at.name=_e,at.args=w.parameters,at.status=ft?"running":"complete",at.chunks=(er=at.chunks)!=null?er:[],at.startedAt=($r=at.startedAt)!=null?$r:G((io=($n=w.startedAt)!=null?$n:w.timestamp)!=null?io:w.awaitedAt),ft?(at.completedAt=void 0,at.duration=void 0,at.durationMs=void 0):at.completedAt=(lo=at.completedAt)!=null?lo:at.startedAt,Q.toolCall=at,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=w.executionId)!=null?Wt:(jn=Q.agentMetadata)==null?void 0:jn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(Q)}else if(tt==="text_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let Q=f;Q&&(Se==="flow"?(Ze(Q),nt=Q):(Q.streaming=!1,g(Q)),f=null),E=typeof w.id=="string"?w.id:E,P=""}else if(tt==="text_delta"){let V=typeof w.id=="string"?w.id:null,q=V?L.get(V):void 0;if(V&&q){let he=typeof w.delta=="string"?w.delta:"",_e=((Ln=I.get(V))!=null?Ln:"")+he;if(I.set(V,_e),_e.trim()==="")continue;let ft=$e(V,q);ft.agentMetadata={...ft.agentMetadata,executionId:w.executionId,parentToolId:q},Pt(ft,_e,he,void 0);continue}if(E=typeof w.id=="string"?w.id:E,Se==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(P+=he,P.trim()==="")continue;let _e=ue();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Pt(_e,P,he,void 0),v=_e;continue}let Q=ue();Q.content+=(tr=w.delta)!=null?tr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:_t!=null?_t:void 0,agentName:re==null?void 0:re.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)){let Q=k.get(V);Q&&Ze(Q),L.delete(V),I.delete(V),k.delete(V);continue}let q=f;q&&(Se==="flow"?(Ze(q),nt=q):(((co=q.content)!=null?co:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),f=null),E=null,P=""}else if(tt==="step_complete"){let V=w.stepType,q=w.executionType;if(V==="tool"||q==="context")continue;if(w.success===!1){let Q=w.error,he=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((jr=Q.message)!=null?jr:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let Q=nt;nt=null;let he=w.stopReason,_e=(po=w.result)==null?void 0:po.response;if(Q)he&&(Q.stopReason=he),_e!=null?Ge(Q,_e):Q.streaming!==!1&&(X.delete(Q.id),de.delete(Q.id),Q.streaming=!1,g(Q));else{let ft=_e!=null&&_e!=="";if(ft||he){let at=ue();he&&(at.stopReason=he),ft?Ze(at,_e):(at.streaming=!1,g(at))}}continue}}else if(tt==="execution_start")Se=w.kind==="flow"?"flow":"agent",rt=!0,Se==="agent"&&(re={executionId:w.executionId,agentId:(ye=w.agentId)!=null?ye:"virtual",agentName:(Hn=w.agentName)!=null?Hn:"",status:"running",currentIteration:0,maxTurns:(Tr=w.maxTurns)!=null?Tr:1,startedAt:G(w.startedAt)});else if(tt==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(re&&(re.currentIteration=V),yn==="separate"&&V>1){let q=f;q&&(q.streaming=!1,g(q),je.set(V-1,q),f=null)}Ce=V}_t=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let V=(gt=w.toolCallId)!=null?gt:U.lastId;if(V){let q=W.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(sn=q.toolCall.chunks)!=null?sn:[],q.toolCall.chunks.push((an=w.delta)!=null?an:""),g(q))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let V=w.stopReason,q=f!=null?f:v;if(V&&q!==null){let Q=w.id;(!Q||((Er=q.agentMetadata)==null?void 0:Er.turnId)===Q)&&(q.stopReason=V,g(q))}_t===w.id&&(_t=null)}else if(tt==="media_start"){let V=String(w.id);ze.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let V=ze.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(tt==="media_complete"){let V=String(w.id),q=ze.get(V);ze.delete(V);let Q=(Ur=(Us=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Us:q==null?void 0:q.mediaType)!=null?Ur:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,ft=null;if(he)ft={type:"media",data:he,mediaType:Q};else if(_e){let un=Q.toLowerCase();ft={type:un==="image"||un.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:Q}}let at=(Bo=w.toolCallId)!=null?Bo:q==null?void 0:q.toolCallId,zs=ft?[ft]:[],Dn=[];for(let un of zs){if(!un||typeof un!="object")continue;let mn=un,Oo=typeof mn.type=="string"?mn.type:void 0,Vr=typeof mn.mediaType=="string"?mn.mediaType.toLowerCase():"",Pn=null,xn="";if(Oo==="media"){let zn=typeof mn.data=="string"?mn.data:void 0;if(!zn)continue;xn=Vr.length>0?Vr:"application/octet-stream",Pn=`data:${xn};base64,${zn}`}else if(Oo==="image-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else if(Oo==="file-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else continue;if(Pn)if(Oo==="image-url"||xn.startsWith("image/"))Dn.push({type:"image",image:Pn,...xn.includes("/")?{mimeType:xn}:{}});else if(xn.startsWith("audio/"))Dn.push({type:"audio",audio:Pn,mimeType:xn});else if(xn.startsWith("video/"))Dn.push({type:"video",video:Pn,mimeType:xn});else{let zn=xn||"application/octet-stream";Dn.push({type:"file",data:Pn,mimeType:zn,filename:uy(zn)})}}if(Dn.length>0){let un=l(),mn=at,Vr={id:`agent-media-${typeof mn=="string"&&mn.length>0?`${mn}-${un}`:String(un)}`,role:"assistant",content:"",contentParts:Dn,createdAt:new Date().toISOString(),streaming:!1,sequence:un,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Vr);let Pn=f;Pn&&(Pn.streaming=!1,g(Pn)),f=null,x.current=null}}else if(tt==="execution_complete"){let V=(Mr=w.kind)!=null?Mr:Se;V==="agent"&&re&&(re.status=w.success?"complete":"error",re.completedAt=G(w.completedAt),re.stopReason=w.stopReason);let q=f;q&&(V==="flow"&&q.streaming!==!1?Ze(q):(q.streaming=!1,g(q)),f=null),E=null,P="",nt=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let V=typeof w.error=="string"?w.error:(ls=(j=w.error)==null?void 0:j.message)!=null?ls:"Execution error";n({type:"error",error:new Error(V)})}else if(tt!=="ping"){if(tt==="approval_start"){let V=(kr=w.approvalId)!=null?kr:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Lr=re==null?void 0:re.agentId)!=null?Lr:"virtual",executionId:(Pr=(qr=w.executionId)!=null?qr:re==null?void 0:re.executionId)!=null?Pr:"",toolName:(ur=w.toolName)!=null?ur:"",toolType:w.toolType,description:(Da=w.description)!=null?Da:`Execute ${(cs=w.toolName)!=null?cs:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let V=(Un=w.approvalId)!=null?Un:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(qn=re==null?void 0:re.agentId)!=null?qn:"virtual",executionId:(gr=(mr=w.executionId)!=null?mr:re==null?void 0:re.executionId)!=null?gr:"",toolName:(Do=w.toolName)!=null?Do:"",toolType:w.toolType,description:(wn=w.description)!=null?wn:`Execute ${(zr=w.toolName)!=null?zr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="approval_complete"){let V=w.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(Ir=w.decision)!=null?Ir:"approved",agentId:(ds=re==null?void 0:re.agentId)!=null?ds:"virtual",executionId:(ps=(No=w.executionId)!=null?No:re==null?void 0:re.executionId)!=null?ps:"",toolName:(Na=w.toolName)!=null?Na:"",description:(us=w.description)!=null?us:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let V=w.artifactType,q=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:V,title:Q,component:typeof w.component=="string"?w.component:void 0}),ae.set(q,{markdown:"",title:Q}),!ie.has(q)){ie.add(q);let he={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:Q,artifactType:V,status:"streaming"}})};pe.set(q,he),g(he)}}else if(tt==="artifact_delta"){let V=String(w.id),q=typeof w.delta=="string"?w.delta:String((Oa=w.delta)!=null?Oa:"");n({type:"artifact_delta",id:V,artDelta:q});let Q=ae.get(V);Q&&(Q.markdown+=q)}else if(tt==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let q=pe.get(V);if(q){q.streaming=!1;try{let Q=JSON.parse((ms=q.rawContent)!=null?ms:"{}");if(Q.props){Q.props.status="complete";let he=ae.get(V);he!=null&&he.markdown&&(Q.props.markdown=he.markdown)}q.rawContent=JSON.stringify(Q)}catch{}ae.delete(V),g(q),pe.delete(V)}}}else if(tt==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let q=String((ut=V.id)!=null?ut:`msg-${l()}`),Q=V.role,_e={id:q,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:l()};if(g(_e),_e.rawContent)try{let ft=JSON.parse(_e.rawContent),at=(qs=ft==null?void 0:ft.props)==null?void 0:qs.artifactId;typeof at=="string"&&ie.add(at)}catch{}f=null,x.current=null,X.delete(q),de.delete(q)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((nr=w.error)==null?void 0:nr.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(tt==="dispatch_error"){let q=(Bn=w.message)!=null?Bn:w.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((Fa=q.message)!=null?Fa:q)))}if(V){n({type:"error",error:V});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:S,value:ne}=await o.read();if(S)break;a+=s.decode(ne,{stream:!0});let Me=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ua=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ri=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},oi=()=>{var t;let e=cy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},si=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Qr.parse)(n,Qr.STR|Qr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Za(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Za(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Bm=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Za(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Qr.parse)(s,Qr.STR|Qr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ai=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Dm="4.3.1";var lr=Dm;var py="https://api.runtype.com/v1/dispatch",ii="https://api.runtype.com";function uy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ll=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 my(e){switch(e){case"json":return si;case"regex-json":return oi;case"xml":return ai;default:return ri}}var Nm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function gy(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Nm(n);if(!Nm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=ua(e);return ua(t)!==null&&a===null?t:e}var Jo=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:py,this.headers={"Content-Type":"application/json","X-Persona-Version":lr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:my(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ss(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=bm(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let k=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:k}),k}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([k])=>k!=="sessionId"&&k!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Ll).map(k=>{var I,C,W;return{id:k.id,role:k.role,content:(W=(C=(I=k.contentParts)!=null?I:k.llmContent)!=null?C:k.rawContent)!=null?W:k.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?hm(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,M=f&&x&&this.lastSentClientToolsFingerprint===v,E=!1,P=null,L;for(let k=0;;k++){let C={...u,...f&&(E||!M)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":lr},body:JSON.stringify(C),signal:r.signal}),L.status===409&&k===0&&f){let W=await L.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=W!=null?W:{error:"Chat request failed"}}break}if(!L.ok){let k=P!=null?P:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(L.status===429){let C=new Error(k.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let I=new Error(k.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!L.body){let k=new Error("No response body received");throw n({type:"error",error:k}),k}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ii}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ii}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Ll).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ca(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Ll).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...ca(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Dt,Yt,Or,wr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=S=>{let ne=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,Me=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,De=S.tools?S.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...S,reasoning:ne,toolCall:Me,tools:De}},u=S=>{if(S.role!=="assistant"||S.variant)return!0;let ne=Array.isArray(S.contentParts)&&S.contentParts.length>0,Me=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||ne||Me||!!S.stopReason},g=S=>{u(S)&&n({type:"message",message:p(S)})},f=null,v=null,x={current:null},M={current:null},E=null,P="",L=new Map,k=new Map,I=new Map,C=new Map,W=new Map,_={lastId:null,byStep:new Map},U={lastId:null,byCall:new Map},H=S=>{if(S==null)return null;try{return String(S)}catch{return null}},F=S=>{var ne,Me,De,Pe,Ne;return H((Ne=(Pe=(De=(Me=(ne=S.stepId)!=null?ne:S.step_id)!=null?Me:S.step)!=null?De:S.parentId)!=null?Pe:S.flowStepId)!=null?Ne:S.flow_step_id)},O=S=>{var ne,Me,De,Pe,Ne,Je,lt;return H((lt=(Je=(Ne=(Pe=(De=(Me=(ne=S.callId)!=null?ne:S.call_id)!=null?Me:S.requestId)!=null?De:S.request_id)!=null?Pe:S.toolCallId)!=null?Ne:S.tool_call_id)!=null?Je:S.stepId)!=null?lt:S.step_id)},ee=r,Ee=!1,ue=()=>{if(f)return f;let S,ne=E;return!Ee&&ee?(S=ee,Ee=!0):ee&&ne?S=`${ee}_${ne}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},te=(S,ne)=>{_.lastId=ne,S&&_.byStep.set(S,ne)},ve=(S,ne)=>{var Ne;let Me=(Ne=S.reasoningId)!=null?Ne:S.id,De=F(S);if(Me){let Je=String(Me);return te(De,Je),Je}if(De){let Je=_.byStep.get(De);if(Je)return _.lastId=Je,Je}if(_.lastId&&!ne)return _.lastId;if(!ne)return null;let Pe=`reason-${l()}`;return te(De,Pe),Pe},ke=S=>{let ne=C.get(S);if(ne)return ne;let Me={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:S,status:"streaming",chunks:[]}};return C.set(S,Me),g(Me),Me},se=(S,ne)=>{U.lastId=ne,S&&U.byCall.set(S,ne)},xe=new Set,pe=new Map,ie=new Set,ae=new Map,He=S=>{if(!S)return!1;let ne=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return ne==="emit_artifact_markdown"||ne==="emit_artifact_component"},Fe=(S,ne)=>{var Ne;let Me=(Ne=S.toolId)!=null?Ne:S.id,De=O(S);if(Me){let Je=String(Me);return se(De,Je),Je}if(De){let Je=U.byCall.get(De);if(Je)return U.lastId=Je,Je}if(U.lastId&&!ne)return U.lastId;if(!ne)return null;let Pe=`tool-${l()}`;return se(De,Pe),Pe},K=S=>{let ne=W.get(S);if(ne)return ne;let Me={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:S,status:"pending"}};return W.set(S,Me),g(Me),Me},G=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let ne=Number(S);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let Me=Date.parse(S);if(!Number.isNaN(Me))return Me}return Date.now()},we=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},X=new Map,de=new Map,We=new Map,fe=(S,ne,Me)=>{var lt;let De=We.get(S);De||(De=[],We.set(S,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<ne?Pe=It+1:Ne=It}((lt=De[Pe])==null?void 0:lt.seq)===ne?De[Pe]={seq:ne,text:Me}:De.splice(Pe,0,{seq:ne,text:Me});let Je="";for(let It=0;It<De.length;It++)Je+=De[It].text;return Je},Ge=(S,ne)=>{let Me=we(ne),De=de.get(S.id),Pe=gy(De,Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=Y=>{var ct;let Te=(ct=S.content)!=null?ct:"";Y.trim()!==""&&(Te.trim().length===0||Y.startsWith(Te)||Y.trimStart().startsWith(Te.trim()))&&(S.content=Y)},lt=()=>{var Y;if(Ne){let Te=(Y=Ne.close)==null?void 0:Y.call(Ne);Te instanceof Promise&&Te.catch(()=>{})}X.delete(S.id),de.delete(S.id),S.streaming=!1,g(S)};if(!Ne){Je(Me),lt();return}let It=ua(Pe);if(It!==null&&It.trim()!==""){Je(It),lt();return}let xt=Y=>{var Ye;let Te=typeof Y=="string"?Y:(Ye=Y==null?void 0:Y.text)!=null?Ye:null;if(Te!==null&&Te.trim()!=="")return Te;let ct=Ne.getExtractedText();return ct!==null&&ct.trim()!==""?ct:Me},B;try{B=Ne.processChunk(Pe)}catch{Je(Me),lt();return}if(B instanceof Promise){B.then(Y=>{Je(xt(Y)),lt()}).catch(()=>{Je(Me),lt()});return}Je(xt(B)),lt()},nt=null,Pt=(S,ne,Me,De)=>{var It;S.rawContent=ne,X.has(S.id)||X.set(S.id,this.createStreamParser());let Pe=X.get(S.id),Ne=ne.trim().startsWith("{")||ne.trim().startsWith("[");if(Ne&&de.set(S.id,ne),Pe.__isPlainTextParser===!0){S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S);return}let lt=Pe.processChunk(ne);if(lt instanceof Promise)lt.then(xt=>{var Y;let B=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;B!==null&&B.trim()!==""?(S.content=B,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S)});else{let xt=typeof lt=="string"?lt:(It=lt==null?void 0:lt.text)!=null?It:null;xt!==null&&xt.trim()!==""?(S.content=xt,g(S)):!Ne&&!ne.trim().startsWith("<")&&(S.content=De!==void 0?ne:S.content+Me,de.delete(S.id),X.delete(S.id),S.rawContent=void 0,g(S))}},Ze=(S,ne)=>{var It,xt;let Me=ne!=null?ne:S.content;if(Me==null||Me===""){S.streaming=!1,g(S);return}let De=de.get(S.id),Pe=De!=null?De:we(Me);S.rawContent=Pe;let Ne=X.get(S.id),Je=null,lt=!1;if(Ne&&(Je=Ne.getExtractedText(),Je===null&&(Je=ua(Pe)),Je===null)){let B=Ne.processChunk(Pe);B instanceof Promise?(lt=!0,B.then(Y=>{var ct;let Te=typeof Y=="string"?Y:(ct=Y==null?void 0:Y.text)!=null?ct:null;Te!==null&&(S.content=Te,S.streaming=!1,X.delete(S.id),de.delete(S.id),g(S))}).catch(()=>{})):Je=typeof B=="string"?B:(It=B==null?void 0:B.text)!=null?It:null}if(!lt){Je!==null&&Je.trim()!==""?S.content=Je:de.has(S.id)||(S.content=we(Me));let B=X.get(S.id);if(B){let Y=(xt=B.close)==null?void 0:xt.call(B);Y instanceof Promise&&Y.catch(()=>{}),X.delete(S.id)}de.delete(S.id),S.streaming=!1,g(S)}},$e=(S,ne,Me)=>{let De=k.get(S);if(De)return De;let Pe={id:`nested-${ne}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ne}};return k.set(S,Pe),g(Pe),Pe},J=[],Ve,ze=new Map,Ce=0,Se="agent",rt=!1,_t=null,re=null,je=new Map,yn=(Dt=this.config.iterationDisplay)!=null?Dt:"separate";for(Ve=()=>{var S,ne,Me,De,Pe,Ne,Je,lt,It,xt,B,Y,Te,ct,Ye,Ut,bn,vt,wt,Rt,Ct,pn,$t,On,Tn,En,vn,Mn,dr,At,Cr,Ar,Fr,pr,mt,Io,Sr,Ro,Wn,is,ro,_r,oo,so,Wo,Ho,ao,bt,Fn,_n,kn,St,Zn,er,$n,io,$r,lo,jn,Wt,Ln,tr,co,jr,po,ye,Hn,Tr,gt,sn,an,Er,Us,Ur,Bo,Mr,j,ls,kr,Lr,qr,Pr,ur,cs,Da,Un,qn,mr,gr,Do,zr,wn,Ir,ds,No,ps,Na,us,Oa,ms,ut,qs,nr,Bn,Fa;for(let gs=0;gs<J.length;gs++){let tt=J[gs].payloadType,w=J[gs].payload;if(!rt&&Se!=="flow"&&typeof w.stepType=="string"&&(Se="flow"),tt==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q),$e(V,q,"reasoning");continue}let Q=(S=ve(w,!0))!=null?S:`reason-${l()}`,he=ke(Q);he.reasoning=(ne=he.reasoning)!=null?ne:{id:Q,status:"streaming",chunks:[]},he.reasoning.startedAt=(De=he.reasoning.startedAt)!=null?De:G((Me=w.startedAt)!=null?Me:w.timestamp),he.reasoning.completedAt=void 0,he.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),he.streaming=!0,he.reasoning.status="streaming",g(he)}else if(tt==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let _e=k.get(V),ft=(Je=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Je:"";ft&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(ft)),g(_e));continue}let q=(It=(lt=ve(w,!1))!=null?lt:ve(w,!0))!=null?It:`reason-${l()}`,Q=ke(q);Q.reasoning=(xt=Q.reasoning)!=null?xt:{id:q,status:"streaming",chunks:[]},Q.reasoning.startedAt=(Y=Q.reasoning.startedAt)!=null?Y:G((B=w.startedAt)!=null?B:w.timestamp);let he=(Ye=(ct=(Te=w.reasoningText)!=null?Te:w.text)!=null?ct:w.delta)!=null?Ye:"";if(he&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let ft=fe(q,_e,String(he));Q.reasoning.chunks=[ft]}else Q.reasoning.chunks.push(String(he))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=G((Ut=w.completedAt)!=null?Ut:w.timestamp);let _e=(bn=Q.reasoning.startedAt)!=null?bn:Date.now();Q.reasoning.durationMs=Math.max(0,((vt=Q.reasoning.completedAt)!=null?vt:Date.now())-_e)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)&&k.has(V)){let ft=k.get(V);if(ft.reasoning){let at=typeof w.text=="string"?w.text:"";at&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(at),ft.reasoning.status="complete",ft.streaming=!1,g(ft)}L.delete(V),k.delete(V);continue}let q=(Rt=(wt=ve(w,!1))!=null?wt:ve(w,!0))!=null?Rt:`reason-${l()}`,Q=typeof w.text=="string"?w.text:"";!C.get(q)&&(Q||w.scope==="loop")&&ke(q);let he=C.get(q);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),Q&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(Q),he.reasoning.status="complete",he.reasoning.completedAt=G((Ct=w.completedAt)!=null?Ct:w.timestamp);let ft=(pn=he.reasoning.startedAt)!=null?pn:Date.now();he.reasoning.durationMs=Math.max(0,(($t=he.reasoning.completedAt)!=null?$t:Date.now())-ft),he.streaming=!1,g(he)}let _e=F(w);_e&&_.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(Tn=(On=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?On:Fe(w,!0))!=null?Tn:`tool-${l()}`,q=(En=w.toolName)!=null?En:w.name;if(He(q)){xe.add(V);continue}se(O(w),V);let Q=K(V),he=(vn=Q.toolCall)!=null?vn:{id:V,status:"pending"};he.name=q!=null?q:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(dr=he.startedAt)!=null?dr:G((Mn=w.startedAt)!=null?Mn:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,Q.toolCall=he,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let V=(Cr=(At=Fe(w,!1))!=null?At:Fe(w,!0))!=null?Cr:`tool-${l()}`;if(xe.has(V))continue;let q=K(V),Q=(Ar=q.toolCall)!=null?Ar:{id:V,status:"running"};Q.startedAt=(pr=Q.startedAt)!=null?pr:G((Fr=w.startedAt)!=null?Fr:w.timestamp);let he=(Sr=(Io=(mt=w.text)!=null?mt:w.delta)!=null?Io:w.message)!=null?Sr:"";he&&(Q.chunks=(Ro=Q.chunks)!=null?Ro:[],Q.chunks.push(String(he))),Q.status="running",q.toolCall=Q,q.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(ro=q.agentMetadata)!=null?ro:{executionId:(Wn=_e==null?void 0:_e.executionId)!=null?Wn:w.executionId,iteration:(is=_e==null?void 0:_e.iteration)!=null?is:w.iteration}),g(q)}else if(tt==="tool_complete"){let V=(oo=(_r=Fe(w,!1))!=null?_r:Fe(w,!0))!=null?oo:`tool-${l()}`;if(xe.has(V)){xe.delete(V);continue}let q=K(V),Q=(so=q.toolCall)!=null?so:{id:V,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=G((Wo=w.completedAt)!=null?Wo:w.timestamp);let he=(Ho=w.duration)!=null?Ho:w.executionTime;if(typeof he=="number")Q.durationMs=he;else{let at=(ao=Q.startedAt)!=null?ao:Date.now();Q.durationMs=Math.max(0,((bt=Q.completedAt)!=null?bt:Date.now())-at)}q.toolCall=Q,q.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(q.agentMetadata=(kn=q.agentMetadata)!=null?kn:{executionId:(Fn=_e==null?void 0:_e.executionId)!=null?Fn:w.executionId,iteration:(_n=_e==null?void 0:_e.iteration)!=null?_n:w.iteration}),g(q);let ft=O(w);ft&&U.byCall.delete(ft)}else if(tt==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(St=V!=null?V:w.toolId)!=null?St:`local-${l()}`,Q=K(q),he=w.toolName,_e=w.origin==="webmcp"&&!yo(he)?`webmcp:${he}`:he,ft=yo(_e),at=(Zn=Q.toolCall)!=null?Zn:{id:q,status:"pending"};at.name=_e,at.args=w.parameters,at.status=ft?"running":"complete",at.chunks=(er=at.chunks)!=null?er:[],at.startedAt=($r=at.startedAt)!=null?$r:G((io=($n=w.startedAt)!=null?$n:w.timestamp)!=null?io:w.awaitedAt),ft?(at.completedAt=void 0,at.duration=void 0,at.durationMs=void 0):at.completedAt=(lo=at.completedAt)!=null?lo:at.startedAt,Q.toolCall=at,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Wt=w.executionId)!=null?Wt:(jn=Q.agentMetadata)==null?void 0:jn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(Q)}else if(tt==="text_start"){let V=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let Q=f;Q&&(Se==="flow"?(Ze(Q),nt=Q):(Q.streaming=!1,g(Q)),f=null),E=typeof w.id=="string"?w.id:E,P=""}else if(tt==="text_delta"){let V=typeof w.id=="string"?w.id:null,q=V?L.get(V):void 0;if(V&&q){let he=typeof w.delta=="string"?w.delta:"",_e=((Ln=I.get(V))!=null?Ln:"")+he;if(I.set(V,_e),_e.trim()==="")continue;let ft=$e(V,q);ft.agentMetadata={...ft.agentMetadata,executionId:w.executionId,parentToolId:q},Pt(ft,_e,he,void 0);continue}if(E=typeof w.id=="string"?w.id:E,Se==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(P+=he,P.trim()==="")continue;let _e=ue();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},Pt(_e,P,he,void 0),v=_e;continue}let Q=ue();Q.content+=(tr=w.delta)!=null?tr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:_t!=null?_t:void 0,agentName:re==null?void 0:re.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&L.has(V)){let Q=k.get(V);Q&&Ze(Q),L.delete(V),I.delete(V),k.delete(V);continue}let q=f;q&&(Se==="flow"?(Ze(q),nt=q):(((co=q.content)!=null?co:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),f=null),E=null,P=""}else if(tt==="step_complete"){let V=w.stepType,q=w.executionType;if(V==="tool"||q==="context")continue;if(w.success===!1){let Q=w.error,he=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((jr=Q.message)!=null?jr:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let Q=nt;nt=null;let he=w.stopReason,_e=(po=w.result)==null?void 0:po.response;if(Q)he&&(Q.stopReason=he),_e!=null?Ge(Q,_e):Q.streaming!==!1&&(X.delete(Q.id),de.delete(Q.id),Q.streaming=!1,g(Q));else{let ft=_e!=null&&_e!=="";if(ft||he){let at=ue();he&&(at.stopReason=he),ft?Ze(at,_e):(at.streaming=!1,g(at))}}continue}}else if(tt==="execution_start")Se=w.kind==="flow"?"flow":"agent",rt=!0,Se==="agent"&&(re={executionId:w.executionId,agentId:(ye=w.agentId)!=null?ye:"virtual",agentName:(Hn=w.agentName)!=null?Hn:"",status:"running",currentIteration:0,maxTurns:(Tr=w.maxTurns)!=null?Tr:1,startedAt:G(w.startedAt)});else if(tt==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(re&&(re.currentIteration=V),yn==="separate"&&V>1){let q=f;q&&(q.streaming=!1,g(q),je.set(V-1,q),f=null)}Ce=V}_t=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let V=(gt=w.toolCallId)!=null?gt:U.lastId;if(V){let q=W.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(sn=q.toolCall.chunks)!=null?sn:[],q.toolCall.chunks.push((an=w.delta)!=null?an:""),g(q))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let V=w.stopReason,q=f!=null?f:v;if(V&&q!==null){let Q=w.id;(!Q||((Er=q.agentMetadata)==null?void 0:Er.turnId)===Q)&&(q.stopReason=V,g(q))}_t===w.id&&(_t=null)}else if(tt==="media_start"){let V=String(w.id);ze.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let V=ze.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(tt==="media_complete"){let V=String(w.id),q=ze.get(V);ze.delete(V);let Q=(Ur=(Us=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Us:q==null?void 0:q.mediaType)!=null?Ur:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,ft=null;if(he)ft={type:"media",data:he,mediaType:Q};else if(_e){let un=Q.toLowerCase();ft={type:un==="image"||un.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:Q}}let at=(Bo=w.toolCallId)!=null?Bo:q==null?void 0:q.toolCallId,zs=ft?[ft]:[],Dn=[];for(let un of zs){if(!un||typeof un!="object")continue;let mn=un,Oo=typeof mn.type=="string"?mn.type:void 0,Vr=typeof mn.mediaType=="string"?mn.mediaType.toLowerCase():"",Pn=null,xn="";if(Oo==="media"){let zn=typeof mn.data=="string"?mn.data:void 0;if(!zn)continue;xn=Vr.length>0?Vr:"application/octet-stream",Pn=`data:${xn};base64,${zn}`}else if(Oo==="image-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else if(Oo==="file-url"){let zn=typeof mn.url=="string"?mn.url:void 0;if(!zn)continue;xn=Vr,Pn=zn}else continue;if(Pn)if(Oo==="image-url"||xn.startsWith("image/"))Dn.push({type:"image",image:Pn,...xn.includes("/")?{mimeType:xn}:{}});else if(xn.startsWith("audio/"))Dn.push({type:"audio",audio:Pn,mimeType:xn});else if(xn.startsWith("video/"))Dn.push({type:"video",video:Pn,mimeType:xn});else{let zn=xn||"application/octet-stream";Dn.push({type:"file",data:Pn,mimeType:zn,filename:uy(zn)})}}if(Dn.length>0){let un=l(),mn=at,Vr={id:`agent-media-${typeof mn=="string"&&mn.length>0?`${mn}-${un}`:String(un)}`,role:"assistant",content:"",contentParts:Dn,createdAt:new Date().toISOString(),streaming:!1,sequence:un,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Vr);let Pn=f;Pn&&(Pn.streaming=!1,g(Pn)),f=null,x.current=null}}else if(tt==="execution_complete"){let V=(Mr=w.kind)!=null?Mr:Se;V==="agent"&&re&&(re.status=w.success?"complete":"error",re.completedAt=G(w.completedAt),re.stopReason=w.stopReason);let q=f;q&&(V==="flow"&&q.streaming!==!1?Ze(q):(q.streaming=!1,g(q)),f=null),E=null,P="",nt=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let V=typeof w.error=="string"?w.error:(ls=(j=w.error)==null?void 0:j.message)!=null?ls:"Execution error";n({type:"error",error:new Error(V)})}else if(tt!=="ping"){if(tt==="approval_start"){let V=(kr=w.approvalId)!=null?kr:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(Lr=re==null?void 0:re.agentId)!=null?Lr:"virtual",executionId:(Pr=(qr=w.executionId)!=null?qr:re==null?void 0:re.executionId)!=null?Pr:"",toolName:(ur=w.toolName)!=null?ur:"",toolType:w.toolType,description:(Da=w.description)!=null?Da:`Execute ${(cs=w.toolName)!=null?cs:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let V=(Un=w.approvalId)!=null?Un:`approval-${l()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:"pending",agentId:(qn=re==null?void 0:re.agentId)!=null?qn:"virtual",executionId:(gr=(mr=w.executionId)!=null?mr:re==null?void 0:re.executionId)!=null?gr:"",toolName:(Do=w.toolName)!=null?Do:"",toolType:w.toolType,description:(wn=w.description)!=null?wn:`Execute ${(zr=w.toolName)!=null?zr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(tt==="approval_complete"){let V=w.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:V,status:(Ir=w.decision)!=null?Ir:"approved",agentId:(ds=re==null?void 0:re.agentId)!=null?ds:"virtual",executionId:(ps=(No=w.executionId)!=null?No:re==null?void 0:re.executionId)!=null?ps:"",toolName:(Na=w.toolName)!=null?Na:"",description:(us=w.description)!=null?us:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let V=w.artifactType,q=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:V,title:Q,component:typeof w.component=="string"?w.component:void 0}),ae.set(q,{markdown:"",title:Q}),!ie.has(q)){ie.add(q);let he={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:Q,artifactType:V,status:"streaming"}})};pe.set(q,he),g(he)}}else if(tt==="artifact_delta"){let V=String(w.id),q=typeof w.delta=="string"?w.delta:String((Oa=w.delta)!=null?Oa:"");n({type:"artifact_delta",id:V,artDelta:q});let Q=ae.get(V);Q&&(Q.markdown+=q)}else if(tt==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let q=pe.get(V);if(q){q.streaming=!1;try{let Q=JSON.parse((ms=q.rawContent)!=null?ms:"{}");if(Q.props){Q.props.status="complete";let he=ae.get(V);he!=null&&he.markdown&&(Q.props.markdown=he.markdown)}q.rawContent=JSON.stringify(Q)}catch{}ae.delete(V),g(q),pe.delete(V)}}}else if(tt==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let q=String((ut=V.id)!=null?ut:`msg-${l()}`),Q=V.role,_e={id:q,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:l()};if(g(_e),_e.rawContent)try{let ft=JSON.parse(_e.rawContent),at=(qs=ft==null?void 0:ft.props)==null?void 0:qs.artifactId;typeof at=="string"&&ie.add(at)}catch{}f=null,x.current=null,X.delete(q),de.delete(q)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((nr=w.error)==null?void 0:nr.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(tt==="dispatch_error"){let q=(Bn=w.message)!=null?Bn:w.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((Fa=q.message)!=null?Fa:q)))}if(V){n({type:"error",error:V});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:S,value:ne}=await o.read();if(S)break;a+=s.decode(ne,{stream:!0});let Me=a.split(`
12
12
 
13
13
  `);a=(Yt=Me.pop())!=null?Yt:"";for(let De of Me){let Pe=De.split(`
14
14
  `),Ne="message",Je="";for(let xt of Pe)xt.startsWith("event:")?Ne=xt.replace("event:","").trim():xt.startsWith("data:")&&(Je+=xt.replace("data:","").trim());if(!Je)continue;let lt;try{lt=JSON.parse(Je)}catch(xt){n({type:"error",error:xt instanceof Error?xt:new Error("Failed to parse chat stream payload")});continue}let It=Ne!=="message"?Ne:(Or=lt.type)!=null?Or:"message";if((wr=this.onSSEEvent)==null||wr.call(this,It,lt),this.parseSSEEvent){x.current=f;let xt=await this.handleCustomSSEEvent(lt,n,x,g,l,M);if(x.current&&x.current!==f&&(f=x.current),xt)continue}J.push({payloadType:It,payload:lt}),Ve()}}Ve()}};function Om(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ks(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var li="[Image]";function Fm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function _m(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function $m(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function jm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ma(e){return{type:"text",text:e}}function Um(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function qm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function zm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Vm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fy=["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"],Yr=[...Vm,...fy];function hy(e){return Vm.includes(e)||e.startsWith("image/")}function ci(e){return hy(e.type)}async function Km(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ci(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gm(e,t=Yr,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 yy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jm(e,t){let n=yy(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"}Pl();var Xm=16e3,by=24e3,xy=4096,vy=1380533830;function wy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vy?new Uint8Array(e,44):new Uint8Array(e)}function Cy(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ga=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Xm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ls(by);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Cy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let M=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(xy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=wy(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Ao(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ga(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(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 di(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Ao({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ao({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Ao({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function fa(e){try{return di(e),!0}catch{return!1}}function Ps(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var So=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ps(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Yo=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Il(e){if(!e)return"";let t=Ay(e);return Qm(t!==null?t:e)}function Ay(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Qm(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,`