@runtypelabs/persona 4.17.0 → 4.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BpWGm7_6.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-DsmTD8TO.cjs';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BpWGm7_6.js';
1
+ import { S as StreamAnimationPlugin } from './types-DsmTD8TO.js';
2
2
 
3
3
  declare const glyphCycle: StreamAnimationPlugin;
4
4
 
@@ -26,6 +26,7 @@ type RuntypeExecutionStreamEvent = ({
26
26
  iterations?: number;
27
27
  kind: "agent" | "flow";
28
28
  seq: number;
29
+ stepErrorCount?: number;
29
30
  stopReason?: string;
30
31
  success: boolean;
31
32
  successfulSteps?: number;
@@ -355,10 +356,21 @@ type RuntypeExecutionStreamEvent = ({
355
356
  mode: "form" | "url";
356
357
  pauseCount?: number;
357
358
  requestedSchema?: Record<string, unknown>;
359
+ requests?: Array<{
360
+ message: string;
361
+ mode: "form" | "url";
362
+ name: string;
363
+ requestedSchema?: Record<string, unknown>;
364
+ url?: string;
365
+ }>;
358
366
  serverName?: string;
359
367
  url?: string;
360
368
  };
361
369
  executionId: string;
370
+ externalAgent?: {
371
+ contextId?: string;
372
+ taskId?: string;
373
+ };
362
374
  origin?: "webmcp" | "sdk";
363
375
  pageOrigin?: string;
364
376
  parameters?: Record<string, unknown>;
@@ -26,6 +26,7 @@ type RuntypeExecutionStreamEvent = ({
26
26
  iterations?: number;
27
27
  kind: "agent" | "flow";
28
28
  seq: number;
29
+ stepErrorCount?: number;
29
30
  stopReason?: string;
30
31
  success: boolean;
31
32
  successfulSteps?: number;
@@ -355,10 +356,21 @@ type RuntypeExecutionStreamEvent = ({
355
356
  mode: "form" | "url";
356
357
  pauseCount?: number;
357
358
  requestedSchema?: Record<string, unknown>;
359
+ requests?: Array<{
360
+ message: string;
361
+ mode: "form" | "url";
362
+ name: string;
363
+ requestedSchema?: Record<string, unknown>;
364
+ url?: string;
365
+ }>;
358
366
  serverName?: string;
359
367
  url?: string;
360
368
  };
361
369
  executionId: string;
370
+ externalAgent?: {
371
+ contextId?: string;
372
+ taskId?: string;
373
+ };
362
374
  origin?: "webmcp" | "sdk";
363
375
  pageOrigin?: string;
364
376
  parameters?: Record<string, unknown>;
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BpWGm7_6.cjs';
1
+ import { S as StreamAnimationPlugin } from './types-DsmTD8TO.cjs';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
@@ -1,4 +1,4 @@
1
- import { S as StreamAnimationPlugin } from './types-BpWGm7_6.js';
1
+ import { S as StreamAnimationPlugin } from './types-DsmTD8TO.js';
2
2
 
3
3
  declare const wipe: StreamAnimationPlugin;
4
4
 
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,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},W=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of T(i))!M.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=_(i,a))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var z={};R(z,{generateCodeSnippet:()=>I});module.exports=H(z);var x="4.17.0";var A=x;function w(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function D(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 j=`({ text, message }: any) => {
1
+ "use strict";var $=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var M=Object.prototype.hasOwnProperty;var R=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},W=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of T(i))!M.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=_(i,a))||s.enumerable});return e};var H=e=>W($({},"__esModule",{value:!0}),e);var z={};R(z,{generateCodeSnippet:()=>I});module.exports=H(z);var x="4.17.1";var A=x;function w(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function D(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 j=`({ 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.17.0";var x=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${x}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function v(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
+ var S="4.17.1";var x=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${x}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function v(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
@@ -1052,6 +1052,7 @@ type RuntypeExecutionStreamEvent = ({
1052
1052
  iterations?: number;
1053
1053
  kind: "agent" | "flow";
1054
1054
  seq: number;
1055
+ stepErrorCount?: number;
1055
1056
  stopReason?: string;
1056
1057
  success: boolean;
1057
1058
  successfulSteps?: number;
@@ -1381,10 +1382,21 @@ type RuntypeExecutionStreamEvent = ({
1381
1382
  mode: "form" | "url";
1382
1383
  pauseCount?: number;
1383
1384
  requestedSchema?: Record<string, unknown>;
1385
+ requests?: Array<{
1386
+ message: string;
1387
+ mode: "form" | "url";
1388
+ name: string;
1389
+ requestedSchema?: Record<string, unknown>;
1390
+ url?: string;
1391
+ }>;
1384
1392
  serverName?: string;
1385
1393
  url?: string;
1386
1394
  };
1387
1395
  executionId: string;
1396
+ externalAgent?: {
1397
+ contextId?: string;
1398
+ taskId?: string;
1399
+ };
1388
1400
  origin?: "webmcp" | "sdk";
1389
1401
  pageOrigin?: string;
1390
1402
  parameters?: Record<string, unknown>;
@@ -1052,6 +1052,7 @@ type RuntypeExecutionStreamEvent = ({
1052
1052
  iterations?: number;
1053
1053
  kind: "agent" | "flow";
1054
1054
  seq: number;
1055
+ stepErrorCount?: number;
1055
1056
  stopReason?: string;
1056
1057
  success: boolean;
1057
1058
  successfulSteps?: number;
@@ -1381,10 +1382,21 @@ type RuntypeExecutionStreamEvent = ({
1381
1382
  mode: "form" | "url";
1382
1383
  pauseCount?: number;
1383
1384
  requestedSchema?: Record<string, unknown>;
1385
+ requests?: Array<{
1386
+ message: string;
1387
+ mode: "form" | "url";
1388
+ name: string;
1389
+ requestedSchema?: Record<string, unknown>;
1390
+ url?: string;
1391
+ }>;
1384
1392
  serverName?: string;
1385
1393
  url?: string;
1386
1394
  };
1387
1395
  executionId: string;
1396
+ externalAgent?: {
1397
+ contextId?: string;
1398
+ taskId?: string;
1399
+ };
1388
1400
  origin?: "webmcp" | "sdk";
1389
1401
  pageOrigin?: string;
1390
1402
  parameters?: Record<string, unknown>;
package/dist/index.cjs CHANGED
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},Cb=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)}},wb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ab=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function on(e){return e==="card"?"collapsed":e}function Lo(e){return e.split(";",1)[0].trim().toLowerCase()}function Sb(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Lo(r)===t)return{mode:on(s),selector:Lo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Lo(r)===o)return{mode:on(s),selector:o}}function _c(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:on(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?Lo(t.file.mimeType):void 0,p=i?Sb(o.files.byMediaType,i):void 0;if(i&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:i,selector:p.selector}};if(o.files.default)return{mode:on(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:on(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:on(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:on(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:on(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function $n(e,t){return _c(e,t).mode}function ta(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Tb="agent_",Eb="flow_";function wg(e){return e.startsWith(Tb)?{kind:"agentId",agentId:e}:e.startsWith(Eb)?{kind:"flowId",flowId:e}:null}function Ag(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=wg(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=wg(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Po=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Sg=()=>document.createDocumentFragment(),ke=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Hn=(...e)=>e.filter(Boolean).join(" ");var oa="ask_user_question",na=8,ns="data-persona-ask-sheet-for",Mb="Other",kb="Other\u2026",Eg="Type your own answer here",Mg="Send",Lb="Next",Pb="Back",Rb="Submit all",Ib="Skip",Wb=3,$c="data-ask-current-index",jc="data-ask-question-count",kg="data-ask-answers",Uc="data-ask-grouped",Lg="data-ask-layout",Hb=e=>e.layout==="pills"?"pills":"rows",Bb=e=>e.getAttribute(Lg)==="pills"?"pills":"rows",Tg=!1,Pg=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===oa,bi=e=>e?.features?.askUserQuestion??{},ro=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,Po.parse)(r,Po.STR|Po.OBJ|Po.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ra=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>na&&!Tg&&(Tg=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${na}.`)),t.slice(0,na)},Db=e=>ra(e)[0]??null,Ob=(e,t)=>ra(e)[t]??null,Rg=(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))},Ig=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Nb=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Ig(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Fb=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},_b=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Wb;c++)s.appendChild(Fb(o));return s}if(p.forEach((c,g)=>{s.appendChild(Nb(c,g,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Mb:kb;if(o==="rows"){let g=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(p.length)),g.setAttribute("data-ask-other-row","true");let b=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Eg,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),g.appendChild(b);let x=Ig(o,a,p.length);x&&g.appendChild(x),s.appendChild(g)}else{let g=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??c,s.appendChild(g)}}return s},Wg=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Eg,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Mg,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},$b=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Mg,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},jb=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Pb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ib,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Rb:n.nextLabel??Lb,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},yr=e=>{let t=e.getAttribute(kg);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Hg=(e,t)=>{e.setAttribute(kg,JSON.stringify(t))},Cn=e=>{let t=Number(e.getAttribute($c)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ub=(e,t)=>{e.setAttribute($c,String(Math.max(0,Math.floor(t))))},os=e=>{let t=Number(e.getAttribute(jc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ro=e=>e.getAttribute(Uc)==="true",zb=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},qb=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},vi=(e,t)=>{let{payload:n}=ro(t),o=ra(n),r=yr(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Bg=e=>{let t=yr(e),n=Cn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},Dg=e=>{if(!Ro(e))return;let t=yr(e),n=Cn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},zc=(e,t,n)=>{let o=bi(n),r=Bb(e),{payload:s,complete:a}=ro(t),i=Ro(e),p=Cn(e),d=os(e),c=i?Ob(s,p):Db(s),g=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof c?.question=="string"?c.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=_b(c,o,a,r);C.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Wg(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!S?e.appendChild($b(o)):(!g||i)&&S&&S.remove(),e.setAttribute("data-multi-select",g?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=jb(p,d,o);k?k.replaceWith(R):e.appendChild(R)}else k&&k.remove();Bg(e),Dg(e)},Vb=(e,t,n)=>{let o=bi(t),r=Hb(o),s=e.toolCall.id,a=ra(n),i=Math.max(1,a.length),p=i>1,d=zb(e,a),c=p?qb(e,i):0,g=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ns,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(jc,String(i)),g.setAttribute($c,String(c)),g.setAttribute(Uc,p?"true":"false"),g.setAttribute(Lg,r),Hg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Rg(g,o);let b=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",b.appendChild(x),g.appendChild(b);let S=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),g.appendChild(S),r!=="rows"&&g.appendChild(Wg(o,r)),zc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Kb=(e,t,n)=>{let{payload:o}=ro(t),r=Math.max(1,ra(o).length);r>os(e)&&(e.setAttribute(jc,String(r)),r>1&&!Ro(e)&&e.setAttribute(Uc,"true")),zc(e,t,n)},Og=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=bi(t);Rg(n,o);let r=y("span","persona-ask-stub-label"),{complete:s}=ro(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},rs=(e,t,n)=>{if(!n||!oo(e)||bi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ns}]`).forEach(d=>{d.getAttribute(ns)!==r&&d.remove()});let a=n.querySelector(`[${ns}="${Pg(r)}"]`);if(a){Kb(a,e,t);return}let{payload:i}=ro(e),p=Vb(e,t,i);n.appendChild(p)},Io=(e,t)=>{if(!e)return;let n=t?`[${ns}="${Pg(t)}"]`:`[${ns}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},qc=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=yr(e),o=Cn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Hg(e,n),Bg(e),Dg(e)},xi=(e,t,n,o)=>{let r=os(e),s=Math.max(0,Math.min(r-1,o));Ub(e,s),zc(e,t,n)};var Bn="suggest_replies";var Vc={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Ci={name:Bn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:Vc,origin:"sdk",annotations:{readOnlyHint:!0}},Kc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),br=e=>e.variant==="tool"&&e.toolCall?.name===Bn,Gc=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let i=r.trim();return i?[i]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},wi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!br(n))continue;let o=Gc(n.toolCall?.args);return o.length>0?o:null}return null},Ng=new Set,Gb=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ng.has(o)||(Ng.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Ho=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let i=t?.[a],p=n?.[a];i===void 0||p===void 0||i!==p&&Gb(a,p,i)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Jc={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:na,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},Yc={name:oa,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:Jc,origin:"sdk",annotations:{readOnlyHint:!0}},ss=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Yc),Ho(e).expose&&t.push(Ci),t};var so=require("partial-json"),Ai=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Bo=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)}},Jb=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Fg=e=>e.status==="complete"?Jb(e):e.status==="pending"?"Waiting":"",Yb=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var _g=e=>e.status==="complete"?Yb(e):"Using tool...",Si=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},aa=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Si(t)},Ti=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Si(t)},Xc=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=aa(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ei=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&sa(o,n.slice(s,a.index),[]),a[1]!==void 0?sa(o,a[1],["bold"]):a[2]!==void 0?sa(o,a[2],["italic"]):a[3]!==void 0&&sa(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&sa(o,n.slice(s),[]),o},sa=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Xb=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ia=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Mi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ki=()=>{let e=Xb();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Li=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,so.parse)(n,so.STR|so.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ai(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ai(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ai(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ai(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,so.parse)(s,so.STR|so.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var jg="4.17.0";var ao=jg;var Zb="https://api.runtype.com/v1/dispatch",Ri="https://api.runtype.com";function ev(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Qc=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 tv(e){switch(e){case"json":return Li;case"regex-json":return ki;case"xml":return Pi;default:return Mi}}var Ug=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nv(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Ug(n);if(!Ug(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ia(e);return ia(t)!==null&&a===null?t:e}var vr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Zb,this.headers={"Content-Type":"application/json","X-Persona-Version":ao,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??tv(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new ts(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ag(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Qc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Cg(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ri}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Qc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Qc).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=M=>{let W=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,H=M.tools?M.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...M,reasoning:W,toolCall:h,tools:H}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let W=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||W||h||!!M.stopReason},f=M=>{b(M)&&n({type:"message",message:g(M)})},x=null,C=null,S={current:null},k={current:null},R=null,E="",P=new Map,B=new Map,N=new Map,$=new Map,z=new Map,q={lastId:null,byStep:new Map},X={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},J=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Z=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ce=o,Y=!1,he=()=>{if(x)return x;let M,W="",h=R;return!Y&&ce?(M=ce,Y=!0,W=r??""):ce&&h?M=`${ce}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:M,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},te=(M,W)=>{q.lastId=W,M&&q.byStep.set(M,W)},be=(M,W)=>{let h=M.reasoningId??M.id,H=J(M);if(h){let D=String(h);return te(H,D),D}if(H){let D=q.byStep.get(H);if(D)return q.lastId=D,D}if(q.lastId&&!W)return q.lastId;if(!W)return null;let I=`reason-${c()}`;return te(H,I),I},ee=M=>{let W=$.get(M);if(W)return W;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return $.set(M,h),f(h),h},ge=(M,W)=>{X.lastId=W,M&&X.byCall.set(M,W)},ne=new Set,me=new Map,ve=new Set,ye=new Map,De=M=>{if(!M)return!1;let W=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return W==="emit_artifact_markdown"||W==="emit_artifact_component"},at=(M,W)=>{let h=M.toolId??M.id,H=Z(M);if(h){let D=String(h);return ge(H,D),D}if(H){let D=X.byCall.get(H);if(D)return X.lastId=D,D}if(X.lastId&&!W)return X.lastId;if(!W)return null;let I=`tool-${c()}`;return ge(H,I),I},je=M=>{let W=z.get(M);if(W)return W;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),f(h),h},Ke=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let W=Number(M);if(!Number.isNaN(W)&&Number.isFinite(W))return W;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Pe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},$e=new Map,Ae=new Map,ie=new Map,Ie=(M,W,h)=>{let H=ie.get(M);H||(H=[],ie.set(M,H));let I=0,D=H.length;for(;I<D;){let j=I+D>>>1;H[j].seq<W?I=j+1:D=j}H[I]?.seq===W?H[I]={seq:W,text:h}:H.splice(I,0,{seq:W,text:h});let K="";for(let j=0;j<H.length;j++)K+=H[j].text;return K},dt=(M,W)=>{let h=Pe(W),H=Ae.get(M.id),I=nv(H,h);M.rawContent=I;let D=$e.get(M.id),K=ue=>{let Re=M.content??"";ue.trim()!==""&&(Re.trim().length===0||ue.startsWith(Re)||ue.trimStart().startsWith(Re.trim()))&&(M.content=ue)},j=()=>{if(D){let ue=D.close?.();ue instanceof Promise&&ue.catch(()=>{})}$e.delete(M.id),Ae.delete(M.id),M.streaming=!1,f(M)};if(!D){K(h),j();return}let G=ia(I);if(G!==null&&G.trim()!==""){K(G),j();return}let pe=ue=>{let Re=typeof ue=="string"?ue:ue?.text??null;if(Re!==null&&Re.trim()!=="")return Re;let qe=D.getExtractedText();return qe!==null&&qe.trim()!==""?qe:h},ze;try{ze=D.processChunk(I)}catch{K(h),j();return}if(ze instanceof Promise){ze.then(ue=>{K(pe(ue)),j()}).catch(()=>{K(h),j()});return}K(pe(ze)),j()},tt=null,xt=(M,W,h,H)=>{M.rawContent=W,$e.has(M.id)||$e.set(M.id,this.createStreamParser());let I=$e.get(M.id),D=W.trim().startsWith("{")||W.trim().startsWith("[");if(D&&Ae.set(M.id,W),I.__isPlainTextParser===!0){M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M);return}let j=I.processChunk(W);if(j instanceof Promise)j.then(G=>{let pe=typeof G=="string"?G:G?.text??null;pe!==null&&pe.trim()!==""?(M.content=pe,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M)});else{let G=typeof j=="string"?j:j?.text??null;G!==null&&G.trim()!==""?(M.content=G,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}},An=(M,W)=>{let h=W??M.content;if(h==null||h===""){M.streaming=!1,f(M);return}let I=Ae.get(M.id)??Pe(h);M.rawContent=I;let D=$e.get(M.id),K=null,j=!1;if(D&&(K=D.getExtractedText(),K===null&&(K=ia(I)),K===null)){let G=D.processChunk(I);G instanceof Promise?(j=!0,G.then(pe=>{let ze=typeof pe=="string"?pe:pe?.text??null;ze!==null&&(M.content=ze,M.streaming=!1,$e.delete(M.id),Ae.delete(M.id),f(M))}).catch(()=>{})):K=typeof G=="string"?G:G?.text??null}if(!j){K!==null&&K.trim()!==""?M.content=K:Ae.has(M.id)||(M.content=Pe(h));let G=$e.get(M.id);if(G){let pe=G.close?.();pe instanceof Promise&&pe.catch(()=>{}),$e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,f(M)}},Sn=(M,W,h)=>{let H=B.get(M);if(H)return H;let I={id:`nested-${W}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:W}};return B.set(M,I),f(I),I},et=[],Le,xe=new Map,nt=0,Ee="agent",we=!1,ae=null,Se=null,Tn=new Map,oe=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let W=et[M].payloadType,h=et[M].payload;if(!we&&Ee!=="flow"&&typeof h.stepType=="string"&&(Ee="flow"),W==="reasoning_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I),Sn(H,I,"reasoning");continue}let D=be(h,!0)??`reason-${c()}`,K=ee(D);K.reasoning=K.reasoning??{id:D,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ke(h.startedAt??h.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(W==="reasoning_delta"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let j=B.get(H),G=h.reasoningText??h.text??h.delta??"";G&&h.hidden!==!0&&j.reasoning&&(j.reasoning.chunks.push(String(G)),f(j));continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=ee(I);D.reasoning=D.reasoning??{id:I,status:"streaming",chunks:[]},D.reasoning.startedAt=D.reasoning.startedAt??Ke(h.startedAt??h.timestamp);let K=h.reasoningText??h.text??h.delta??"";if(K&&h.hidden!==!0){let j=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(j!==void 0){let G=Ie(I,j,String(K));D.reasoning.chunks=[G]}else D.reasoning.chunks.push(String(K))}if(D.reasoning.status=h.done?"complete":"streaming",h.done){D.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let j=D.reasoning.startedAt??Date.now();D.reasoning.durationMs=Math.max(0,(D.reasoning.completedAt??Date.now())-j)}D.streaming=D.reasoning.status!=="complete",f(D)}else if(W==="reasoning_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let G=B.get(H);if(G.reasoning){let pe=typeof h.text=="string"?h.text:"";pe&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(pe),G.reasoning.status="complete",G.streaming=!1,f(G)}P.delete(H),B.delete(H);continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=typeof h.text=="string"?h.text:"";!$.get(I)&&(D||h.scope==="loop")&&ee(I);let K=$.get(I);if(K?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),D&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(D),K.reasoning.status="complete",K.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let G=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-G),K.streaming=!1,f(K)}let j=J(h);j&&q.byStep.delete(j)}else if(W==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(nt=h.iteration);let H=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??at(h,!0)??`tool-${c()}`,I=h.toolName??h.name;if(De(I)){ne.add(H);continue}ge(Z(h),H);let D=je(H),K=D.toolCall??{id:H,status:"pending"};K.name=I??K.name,K.status="running",h.parameters!==void 0?K.args=h.parameters:h.args!==void 0&&(K.args=h.args),K.startedAt=K.startedAt??Ke(h.startedAt??h.timestamp),K.completedAt=void 0,K.durationMs=void 0,D.toolCall=K,D.streaming=!0,h.executionId&&(D.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(D)}else if(W==="tool_output_delta"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H))continue;let I=je(H),D=I.toolCall??{id:H,status:"running"};D.startedAt=D.startedAt??Ke(h.startedAt??h.timestamp);let K=h.text??h.delta??h.message??"";K&&(D.chunks=D.chunks??[],D.chunks.push(String(K))),D.status="running",I.toolCall=D,I.streaming=!0;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I)}else if(W==="tool_complete"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H)){ne.delete(H);continue}let I=je(H),D=I.toolCall??{id:H,status:"running"};D.status="complete",h.result!==void 0&&(D.result=h.result),typeof h.duration=="number"&&(D.duration=h.duration),D.completedAt=Ke(h.completedAt??h.timestamp);let K=h.duration??h.executionTime;if(typeof K=="number")D.durationMs=K;else{let pe=D.startedAt??Date.now();D.durationMs=Math.max(0,(D.completedAt??Date.now())-pe)}I.toolCall=D,I.streaming=!1;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I);let G=Z(h);G&&X.byCall.delete(G)}else if(W==="await"&&h.toolName){let H=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,I=H??h.toolId??`local-${c()}`,D=je(I),K=h.toolName,j=h.origin==="webmcp"&&!ko(K)?`webmcp:${K}`:K,G=ko(j),pe=D.toolCall??{id:I,status:"pending"};pe.name=j,pe.args=h.parameters,pe.status=G?"running":"complete",pe.chunks=pe.chunks??[],pe.startedAt=pe.startedAt??Ke(h.startedAt??h.timestamp??h.awaitedAt),G?(pe.completedAt=void 0,pe.duration=void 0,pe.durationMs=void 0):pe.completedAt=pe.completedAt??pe.startedAt,D.toolCall=pe,D.streaming=!1,D.agentMetadata={...D.agentMetadata,executionId:h.executionId??D.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(D)}else if(W==="text_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I);continue}let D=x;D&&(Ee==="flow"?(An(D),tt=D):(D.streaming=!1,f(D)),x=null),R=typeof h.id=="string"?h.id:R,E=""}else if(W==="text_delta"){let H=typeof h.id=="string"?h.id:null,I=H?P.get(H):void 0;if(H&&I){let K=typeof h.delta=="string"?h.delta:"",j=(N.get(H)??"")+K;if(N.set(H,j),j.trim()==="")continue;let G=Sn(H,I);G.agentMetadata={...G.agentMetadata,executionId:h.executionId,parentToolId:I},xt(G,j,K,void 0);continue}if(R=typeof h.id=="string"?h.id:R,Ee==="flow"){let K=typeof h.delta=="string"?h.delta:"";if(E+=K,E.trim()==="")continue;let j=he();j.agentMetadata={executionId:h.executionId,iteration:h.iteration},xt(j,E,K,void 0),C=j;continue}let D=he();D.content+=h.delta??"",D.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:ae??void 0,agentName:Se?.agentName},C=D,f(D)}else if(W==="text_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)){let D=B.get(H);D&&An(D),P.delete(H),N.delete(H),B.delete(H);continue}let I=x;I&&(Ee==="flow"?(An(I),tt=I):((I.content??"")===""&&typeof h.text=="string"&&(I.content=h.text),I.streaming=!1,f(I)),x=null),R=null,E=""}else if(W==="step_complete"){let H=h.stepType,I=h.executionType;if(H==="tool"||I==="context")continue;if(h.success===!1){let D=h.error,K=typeof D=="string"&&D!==""?D:D!=null&&typeof D=="object"&&Reflect.has(D,"message")?String(D.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let j=x;j&&j.streaming&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"});continue}{let D=tt;tt=null;let K=h.stopReason,j=h.result?.response;if(D)K&&(D.stopReason=K),j!=null?dt(D,j):D.streaming!==!1&&($e.delete(D.id),Ae.delete(D.id),D.streaming=!1,f(D));else{let G=j!=null&&j!=="";if(G||K){let pe=he();K&&(pe.stopReason=K),G?An(pe,j):(pe.streaming=!1,f(pe))}}continue}}else if(W==="execution_start")Ee=h.kind==="flow"?"flow":"agent",we=!0,Ee==="agent"&&(Se={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ke(h.startedAt)});else if(W==="turn_start"){let H=typeof h.iteration=="number"?h.iteration:nt;if(H!==nt){if(Se&&(Se.currentIteration=H),oe==="separate"&&H>1){let I=x;I&&(I.streaming=!1,f(I),Tn.set(H-1,I),x=null)}nt=H}ae=typeof h.id=="string"?h.id:null,C=null}else if(W==="tool_input_delta"){let H=h.toolCallId??X.lastId;if(H){let I=z.get(H);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(h.delta??""),f(I))}}else{if(W==="tool_input_complete")continue;if(W==="turn_complete"){let H=h.stopReason,I=x??C;if(H&&I!==null){let D=h.id;(!D||I.agentMetadata?.turnId===D)&&(I.stopReason=H,f(I))}ae===h.id&&(ae=null)}else if(W==="media_start"){let H=String(h.id);xe.set(H,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(W==="media_delta"){let H=xe.get(String(h.id));H&&typeof h.delta=="string"&&H.parts.push(h.delta)}else if(W==="media_complete"){let H=String(h.id),I=xe.get(H);xe.delete(H);let D=(typeof h.mediaType=="string"?h.mediaType:void 0)??I?.mediaType??"application/octet-stream",K=typeof h.data=="string"?h.data:void 0,j=typeof h.url=="string"?h.url:I&&I.parts.length>0?I.parts.join(""):void 0,G=null;if(K)G={type:"media",data:K,mediaType:D};else if(j){let Re=D.toLowerCase();G={type:Re==="image"||Re.startsWith("image/")?"image-url":"file-url",url:j,mediaType:D}}let pe=h.toolCallId??I?.toolCallId,ze=G?[G]:[],ue=[];for(let Re of ze){if(!Re||typeof Re!="object")continue;let qe=Re,Ue=typeof qe.type=="string"?qe.type:void 0,Be=typeof qe.mediaType=="string"?qe.mediaType.toLowerCase():"",Te=null,ot="";if(Ue==="media"){let Tt=typeof qe.data=="string"?qe.data:void 0;if(!Tt)continue;ot=Be.length>0?Be:"application/octet-stream",Te=`data:${ot};base64,${Tt}`}else if(Ue==="image-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else if(Ue==="file-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else continue;if(Te)if(Ue==="image-url"||ot.startsWith("image/"))ue.push({type:"image",image:Te,...ot.includes("/")?{mimeType:ot}:{}});else if(ot.startsWith("audio/"))ue.push({type:"audio",audio:Te,mimeType:ot});else if(ot.startsWith("video/"))ue.push({type:"video",video:Te,mimeType:ot});else{let Tt=ot||"application/octet-stream";ue.push({type:"file",data:Te,mimeType:Tt,filename:ev(Tt)})}}if(ue.length>0){let Re=c(),qe=pe,Be={id:`agent-media-${typeof qe=="string"&&qe.length>0?`${qe}-${Re}`:String(Re)}`,role:"assistant",content:"",contentParts:ue,createdAt:new Date().toISOString(),streaming:!1,sequence:Re,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:nt}};f(Be);let Te=x;Te&&(Te.streaming=!1,f(Te)),x=null,S.current=null}}else if(W==="execution_complete"){let H=h.kind??Ee;H==="agent"&&Se&&(Se.status=h.success?"complete":"error",Se.completedAt=Ke(h.completedAt),Se.stopReason=h.stopReason);let I=x;I&&(H==="flow"&&I.streaming!==!1?An(I):(I.streaming=!1,f(I)),x=null),R=null,E="",tt=null,n({type:"status",status:"idle",terminal:!0})}else if(W==="execution_error"){let H=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(W!=="ping"){if(W==="approval_start"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="step_await"&&h.awaitReason==="approval_required"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="approval_complete"){let H=h.approvalId;if(H){let D={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:h.decision??"approved",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(D)}}else if(W==="artifact_start"||W==="artifact_delta"||W==="artifact_update"||W==="artifact_complete"){if(W==="artifact_start"){let H=h.artifactType,I=String(h.id),D=typeof h.title=="string"?h.title:void 0,K=h.file,j;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(j={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:I,artifactType:H,title:D,component:typeof h.component=="string"?h.component:void 0,...j?{file:j}:{}});let G=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(ye.set(I,{markdown:"",title:D,file:j,...G?{props:G}:{}}),!ve.has(I)){ve.add(I);let pe=$n(this.config.features?.artifacts,{artifactType:H,...j?{file:j}:{}}),ze=typeof h.component=="string"?h.component:void 0,ue={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ta(pe,{artifactId:I,title:D,artifactType:H,status:"streaming",...j?{file:j}:{},...ze?{component:ze}:{}})};me.set(I,ue),f(ue)}}else if(W==="artifact_delta"){let H=String(h.id),I=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:H,artDelta:I});let D=ye.get(H);D&&(D.markdown+=I)}else if(W==="artifact_update"){let H=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:H,component:typeof h.component=="string"?h.component:void 0});let I=ye.get(String(h.id));I&&(I.props={...I.props??{},...H})}else if(W==="artifact_complete"){let H=String(h.id);n({type:"artifact_complete",id:H});let I=me.get(H);if(I){I.streaming=!1;try{let D=JSON.parse(I.rawContent??"{}");if(D.props){D.props.status="complete";let K=ye.get(H);K?.markdown&&(D.props.markdown=K.markdown),K?.file&&(D.props.file=K.file),D.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(D.props.componentProps=K.props)}I.rawContent=JSON.stringify(D)}catch{}ye.delete(H),f(I),me.delete(H)}}}else if(W==="transcript_insert"){let H=h.message;if(!H||typeof H!="object")continue;let I=String(H.id??`msg-${c()}`),D=H.role,j={id:I,role:D==="user"?"user":D==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:c()};if(f(j),j.rawContent)try{let pe=JSON.parse(j.rawContent)?.props?.artifactId;typeof pe=="string"&&ve.add(pe)}catch{}x=null,S.current=null,$e.delete(I),Ae.delete(I)}else if(W==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let H=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(H)});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(W==="step_error"||W==="dispatch_error"||W==="flow_error"){let H=null;if(h.error instanceof Error)H=h.error;else if(W==="dispatch_error"){let I=h.message??h.error;I!=null&&I!==""&&(H=new Error(String(I)))}else{let I=h.error;typeof I=="string"&&I!==""?H=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(H=new Error(String(I.message??I)))}if(H){n({type:"error",error:H});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:W}=await s.read();if(M)break;i+=a.decode(W,{stream:!0});let h=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ia=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Mi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ki=()=>{let e=Xb();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},Li=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,so.parse)(n,so.STR|so.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ai(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ai(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ai(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ai(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,so.parse)(s,so.STR|so.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var jg="4.17.1";var ao=jg;var Zb="https://api.runtype.com/v1/dispatch",Ri="https://api.runtype.com";function ev(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Qc=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 tv(e){switch(e){case"json":return Li;case"regex-json":return ki;case"xml":return Pi;default:return Mi}}var Ug=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nv(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Ug(n);if(!Ug(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ia(e);return ia(t)!==null&&a===null?t:e}var vr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Zb,this.headers={"Content-Type":"application/json","X-Persona-Version":ao,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??tv(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new ts(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ag(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Qc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Cg(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ri}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Qc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Qc).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=M=>{let W=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,H=M.tools?M.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...M,reasoning:W,toolCall:h,tools:H}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let W=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||W||h||!!M.stopReason},f=M=>{b(M)&&n({type:"message",message:g(M)})},x=null,C=null,S={current:null},k={current:null},R=null,E="",P=new Map,B=new Map,N=new Map,$=new Map,z=new Map,q={lastId:null,byStep:new Map},X={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},J=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Z=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ce=o,Y=!1,he=()=>{if(x)return x;let M,W="",h=R;return!Y&&ce?(M=ce,Y=!0,W=r??""):ce&&h?M=`${ce}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:M,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},te=(M,W)=>{q.lastId=W,M&&q.byStep.set(M,W)},be=(M,W)=>{let h=M.reasoningId??M.id,H=J(M);if(h){let D=String(h);return te(H,D),D}if(H){let D=q.byStep.get(H);if(D)return q.lastId=D,D}if(q.lastId&&!W)return q.lastId;if(!W)return null;let I=`reason-${c()}`;return te(H,I),I},ee=M=>{let W=$.get(M);if(W)return W;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return $.set(M,h),f(h),h},ge=(M,W)=>{X.lastId=W,M&&X.byCall.set(M,W)},ne=new Set,me=new Map,ve=new Set,ye=new Map,De=M=>{if(!M)return!1;let W=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return W==="emit_artifact_markdown"||W==="emit_artifact_component"},at=(M,W)=>{let h=M.toolId??M.id,H=Z(M);if(h){let D=String(h);return ge(H,D),D}if(H){let D=X.byCall.get(H);if(D)return X.lastId=D,D}if(X.lastId&&!W)return X.lastId;if(!W)return null;let I=`tool-${c()}`;return ge(H,I),I},je=M=>{let W=z.get(M);if(W)return W;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),f(h),h},Ke=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let W=Number(M);if(!Number.isNaN(W)&&Number.isFinite(W))return W;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Pe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},$e=new Map,Ae=new Map,ie=new Map,Ie=(M,W,h)=>{let H=ie.get(M);H||(H=[],ie.set(M,H));let I=0,D=H.length;for(;I<D;){let j=I+D>>>1;H[j].seq<W?I=j+1:D=j}H[I]?.seq===W?H[I]={seq:W,text:h}:H.splice(I,0,{seq:W,text:h});let K="";for(let j=0;j<H.length;j++)K+=H[j].text;return K},dt=(M,W)=>{let h=Pe(W),H=Ae.get(M.id),I=nv(H,h);M.rawContent=I;let D=$e.get(M.id),K=ue=>{let Re=M.content??"";ue.trim()!==""&&(Re.trim().length===0||ue.startsWith(Re)||ue.trimStart().startsWith(Re.trim()))&&(M.content=ue)},j=()=>{if(D){let ue=D.close?.();ue instanceof Promise&&ue.catch(()=>{})}$e.delete(M.id),Ae.delete(M.id),M.streaming=!1,f(M)};if(!D){K(h),j();return}let G=ia(I);if(G!==null&&G.trim()!==""){K(G),j();return}let pe=ue=>{let Re=typeof ue=="string"?ue:ue?.text??null;if(Re!==null&&Re.trim()!=="")return Re;let qe=D.getExtractedText();return qe!==null&&qe.trim()!==""?qe:h},ze;try{ze=D.processChunk(I)}catch{K(h),j();return}if(ze instanceof Promise){ze.then(ue=>{K(pe(ue)),j()}).catch(()=>{K(h),j()});return}K(pe(ze)),j()},tt=null,xt=(M,W,h,H)=>{M.rawContent=W,$e.has(M.id)||$e.set(M.id,this.createStreamParser());let I=$e.get(M.id),D=W.trim().startsWith("{")||W.trim().startsWith("[");if(D&&Ae.set(M.id,W),I.__isPlainTextParser===!0){M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M);return}let j=I.processChunk(W);if(j instanceof Promise)j.then(G=>{let pe=typeof G=="string"?G:G?.text??null;pe!==null&&pe.trim()!==""?(M.content=pe,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M)});else{let G=typeof j=="string"?j:j?.text??null;G!==null&&G.trim()!==""?(M.content=G,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}},An=(M,W)=>{let h=W??M.content;if(h==null||h===""){M.streaming=!1,f(M);return}let I=Ae.get(M.id)??Pe(h);M.rawContent=I;let D=$e.get(M.id),K=null,j=!1;if(D&&(K=D.getExtractedText(),K===null&&(K=ia(I)),K===null)){let G=D.processChunk(I);G instanceof Promise?(j=!0,G.then(pe=>{let ze=typeof pe=="string"?pe:pe?.text??null;ze!==null&&(M.content=ze,M.streaming=!1,$e.delete(M.id),Ae.delete(M.id),f(M))}).catch(()=>{})):K=typeof G=="string"?G:G?.text??null}if(!j){K!==null&&K.trim()!==""?M.content=K:Ae.has(M.id)||(M.content=Pe(h));let G=$e.get(M.id);if(G){let pe=G.close?.();pe instanceof Promise&&pe.catch(()=>{}),$e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,f(M)}},Sn=(M,W,h)=>{let H=B.get(M);if(H)return H;let I={id:`nested-${W}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:W}};return B.set(M,I),f(I),I},et=[],Le,xe=new Map,nt=0,Ee="agent",we=!1,ae=null,Se=null,Tn=new Map,oe=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let W=et[M].payloadType,h=et[M].payload;if(!we&&Ee!=="flow"&&typeof h.stepType=="string"&&(Ee="flow"),W==="reasoning_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I),Sn(H,I,"reasoning");continue}let D=be(h,!0)??`reason-${c()}`,K=ee(D);K.reasoning=K.reasoning??{id:D,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ke(h.startedAt??h.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(W==="reasoning_delta"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let j=B.get(H),G=h.reasoningText??h.text??h.delta??"";G&&h.hidden!==!0&&j.reasoning&&(j.reasoning.chunks.push(String(G)),f(j));continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=ee(I);D.reasoning=D.reasoning??{id:I,status:"streaming",chunks:[]},D.reasoning.startedAt=D.reasoning.startedAt??Ke(h.startedAt??h.timestamp);let K=h.reasoningText??h.text??h.delta??"";if(K&&h.hidden!==!0){let j=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(j!==void 0){let G=Ie(I,j,String(K));D.reasoning.chunks=[G]}else D.reasoning.chunks.push(String(K))}if(D.reasoning.status=h.done?"complete":"streaming",h.done){D.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let j=D.reasoning.startedAt??Date.now();D.reasoning.durationMs=Math.max(0,(D.reasoning.completedAt??Date.now())-j)}D.streaming=D.reasoning.status!=="complete",f(D)}else if(W==="reasoning_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let G=B.get(H);if(G.reasoning){let pe=typeof h.text=="string"?h.text:"";pe&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(pe),G.reasoning.status="complete",G.streaming=!1,f(G)}P.delete(H),B.delete(H);continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=typeof h.text=="string"?h.text:"";!$.get(I)&&(D||h.scope==="loop")&&ee(I);let K=$.get(I);if(K?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),D&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(D),K.reasoning.status="complete",K.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let G=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-G),K.streaming=!1,f(K)}let j=J(h);j&&q.byStep.delete(j)}else if(W==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(nt=h.iteration);let H=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??at(h,!0)??`tool-${c()}`,I=h.toolName??h.name;if(De(I)){ne.add(H);continue}ge(Z(h),H);let D=je(H),K=D.toolCall??{id:H,status:"pending"};K.name=I??K.name,K.status="running",h.parameters!==void 0?K.args=h.parameters:h.args!==void 0&&(K.args=h.args),K.startedAt=K.startedAt??Ke(h.startedAt??h.timestamp),K.completedAt=void 0,K.durationMs=void 0,D.toolCall=K,D.streaming=!0,h.executionId&&(D.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(D)}else if(W==="tool_output_delta"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H))continue;let I=je(H),D=I.toolCall??{id:H,status:"running"};D.startedAt=D.startedAt??Ke(h.startedAt??h.timestamp);let K=h.text??h.delta??h.message??"";K&&(D.chunks=D.chunks??[],D.chunks.push(String(K))),D.status="running",I.toolCall=D,I.streaming=!0;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I)}else if(W==="tool_complete"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H)){ne.delete(H);continue}let I=je(H),D=I.toolCall??{id:H,status:"running"};D.status="complete",h.result!==void 0&&(D.result=h.result),typeof h.duration=="number"&&(D.duration=h.duration),D.completedAt=Ke(h.completedAt??h.timestamp);let K=h.duration??h.executionTime;if(typeof K=="number")D.durationMs=K;else{let pe=D.startedAt??Date.now();D.durationMs=Math.max(0,(D.completedAt??Date.now())-pe)}I.toolCall=D,I.streaming=!1;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I);let G=Z(h);G&&X.byCall.delete(G)}else if(W==="await"&&h.toolName){let H=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,I=H??h.toolId??`local-${c()}`,D=je(I),K=h.toolName,j=h.origin==="webmcp"&&!ko(K)?`webmcp:${K}`:K,G=ko(j),pe=D.toolCall??{id:I,status:"pending"};pe.name=j,pe.args=h.parameters,pe.status=G?"running":"complete",pe.chunks=pe.chunks??[],pe.startedAt=pe.startedAt??Ke(h.startedAt??h.timestamp??h.awaitedAt),G?(pe.completedAt=void 0,pe.duration=void 0,pe.durationMs=void 0):pe.completedAt=pe.completedAt??pe.startedAt,D.toolCall=pe,D.streaming=!1,D.agentMetadata={...D.agentMetadata,executionId:h.executionId??D.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(D)}else if(W==="text_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I);continue}let D=x;D&&(Ee==="flow"?(An(D),tt=D):(D.streaming=!1,f(D)),x=null),R=typeof h.id=="string"?h.id:R,E=""}else if(W==="text_delta"){let H=typeof h.id=="string"?h.id:null,I=H?P.get(H):void 0;if(H&&I){let K=typeof h.delta=="string"?h.delta:"",j=(N.get(H)??"")+K;if(N.set(H,j),j.trim()==="")continue;let G=Sn(H,I);G.agentMetadata={...G.agentMetadata,executionId:h.executionId,parentToolId:I},xt(G,j,K,void 0);continue}if(R=typeof h.id=="string"?h.id:R,Ee==="flow"){let K=typeof h.delta=="string"?h.delta:"";if(E+=K,E.trim()==="")continue;let j=he();j.agentMetadata={executionId:h.executionId,iteration:h.iteration},xt(j,E,K,void 0),C=j;continue}let D=he();D.content+=h.delta??"",D.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:ae??void 0,agentName:Se?.agentName},C=D,f(D)}else if(W==="text_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)){let D=B.get(H);D&&An(D),P.delete(H),N.delete(H),B.delete(H);continue}let I=x;I&&(Ee==="flow"?(An(I),tt=I):((I.content??"")===""&&typeof h.text=="string"&&(I.content=h.text),I.streaming=!1,f(I)),x=null),R=null,E=""}else if(W==="step_complete"){let H=h.stepType,I=h.executionType;if(H==="tool"||I==="context")continue;if(h.success===!1){let D=h.error,K=typeof D=="string"&&D!==""?D:D!=null&&typeof D=="object"&&Reflect.has(D,"message")?String(D.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let j=x;j&&j.streaming&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"});continue}{let D=tt;tt=null;let K=h.stopReason,j=h.result?.response;if(D)K&&(D.stopReason=K),j!=null?dt(D,j):D.streaming!==!1&&($e.delete(D.id),Ae.delete(D.id),D.streaming=!1,f(D));else{let G=j!=null&&j!=="";if(G||K){let pe=he();K&&(pe.stopReason=K),G?An(pe,j):(pe.streaming=!1,f(pe))}}continue}}else if(W==="execution_start")Ee=h.kind==="flow"?"flow":"agent",we=!0,Ee==="agent"&&(Se={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ke(h.startedAt)});else if(W==="turn_start"){let H=typeof h.iteration=="number"?h.iteration:nt;if(H!==nt){if(Se&&(Se.currentIteration=H),oe==="separate"&&H>1){let I=x;I&&(I.streaming=!1,f(I),Tn.set(H-1,I),x=null)}nt=H}ae=typeof h.id=="string"?h.id:null,C=null}else if(W==="tool_input_delta"){let H=h.toolCallId??X.lastId;if(H){let I=z.get(H);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(h.delta??""),f(I))}}else{if(W==="tool_input_complete")continue;if(W==="turn_complete"){let H=h.stopReason,I=x??C;if(H&&I!==null){let D=h.id;(!D||I.agentMetadata?.turnId===D)&&(I.stopReason=H,f(I))}ae===h.id&&(ae=null)}else if(W==="media_start"){let H=String(h.id);xe.set(H,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(W==="media_delta"){let H=xe.get(String(h.id));H&&typeof h.delta=="string"&&H.parts.push(h.delta)}else if(W==="media_complete"){let H=String(h.id),I=xe.get(H);xe.delete(H);let D=(typeof h.mediaType=="string"?h.mediaType:void 0)??I?.mediaType??"application/octet-stream",K=typeof h.data=="string"?h.data:void 0,j=typeof h.url=="string"?h.url:I&&I.parts.length>0?I.parts.join(""):void 0,G=null;if(K)G={type:"media",data:K,mediaType:D};else if(j){let Re=D.toLowerCase();G={type:Re==="image"||Re.startsWith("image/")?"image-url":"file-url",url:j,mediaType:D}}let pe=h.toolCallId??I?.toolCallId,ze=G?[G]:[],ue=[];for(let Re of ze){if(!Re||typeof Re!="object")continue;let qe=Re,Ue=typeof qe.type=="string"?qe.type:void 0,Be=typeof qe.mediaType=="string"?qe.mediaType.toLowerCase():"",Te=null,ot="";if(Ue==="media"){let Tt=typeof qe.data=="string"?qe.data:void 0;if(!Tt)continue;ot=Be.length>0?Be:"application/octet-stream",Te=`data:${ot};base64,${Tt}`}else if(Ue==="image-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else if(Ue==="file-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else continue;if(Te)if(Ue==="image-url"||ot.startsWith("image/"))ue.push({type:"image",image:Te,...ot.includes("/")?{mimeType:ot}:{}});else if(ot.startsWith("audio/"))ue.push({type:"audio",audio:Te,mimeType:ot});else if(ot.startsWith("video/"))ue.push({type:"video",video:Te,mimeType:ot});else{let Tt=ot||"application/octet-stream";ue.push({type:"file",data:Te,mimeType:Tt,filename:ev(Tt)})}}if(ue.length>0){let Re=c(),qe=pe,Be={id:`agent-media-${typeof qe=="string"&&qe.length>0?`${qe}-${Re}`:String(Re)}`,role:"assistant",content:"",contentParts:ue,createdAt:new Date().toISOString(),streaming:!1,sequence:Re,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:nt}};f(Be);let Te=x;Te&&(Te.streaming=!1,f(Te)),x=null,S.current=null}}else if(W==="execution_complete"){let H=h.kind??Ee;H==="agent"&&Se&&(Se.status=h.success?"complete":"error",Se.completedAt=Ke(h.completedAt),Se.stopReason=h.stopReason);let I=x;I&&(H==="flow"&&I.streaming!==!1?An(I):(I.streaming=!1,f(I)),x=null),R=null,E="",tt=null,n({type:"status",status:"idle",terminal:!0})}else if(W==="execution_error"){let H=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(W!=="ping"){if(W==="approval_start"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="step_await"&&h.awaitReason==="approval_required"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="approval_complete"){let H=h.approvalId;if(H){let D={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:h.decision??"approved",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(D)}}else if(W==="artifact_start"||W==="artifact_delta"||W==="artifact_update"||W==="artifact_complete"){if(W==="artifact_start"){let H=h.artifactType,I=String(h.id),D=typeof h.title=="string"?h.title:void 0,K=h.file,j;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(j={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:I,artifactType:H,title:D,component:typeof h.component=="string"?h.component:void 0,...j?{file:j}:{}});let G=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(ye.set(I,{markdown:"",title:D,file:j,...G?{props:G}:{}}),!ve.has(I)){ve.add(I);let pe=$n(this.config.features?.artifacts,{artifactType:H,...j?{file:j}:{}}),ze=typeof h.component=="string"?h.component:void 0,ue={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ta(pe,{artifactId:I,title:D,artifactType:H,status:"streaming",...j?{file:j}:{},...ze?{component:ze}:{}})};me.set(I,ue),f(ue)}}else if(W==="artifact_delta"){let H=String(h.id),I=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:H,artDelta:I});let D=ye.get(H);D&&(D.markdown+=I)}else if(W==="artifact_update"){let H=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:H,component:typeof h.component=="string"?h.component:void 0});let I=ye.get(String(h.id));I&&(I.props={...I.props??{},...H})}else if(W==="artifact_complete"){let H=String(h.id);n({type:"artifact_complete",id:H});let I=me.get(H);if(I){I.streaming=!1;try{let D=JSON.parse(I.rawContent??"{}");if(D.props){D.props.status="complete";let K=ye.get(H);K?.markdown&&(D.props.markdown=K.markdown),K?.file&&(D.props.file=K.file),D.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(D.props.componentProps=K.props)}I.rawContent=JSON.stringify(D)}catch{}ye.delete(H),f(I),me.delete(H)}}}else if(W==="transcript_insert"){let H=h.message;if(!H||typeof H!="object")continue;let I=String(H.id??`msg-${c()}`),D=H.role,j={id:I,role:D==="user"?"user":D==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:c()};if(f(j),j.rawContent)try{let pe=JSON.parse(j.rawContent)?.props?.artifactId;typeof pe=="string"&&ve.add(pe)}catch{}x=null,S.current=null,$e.delete(I),Ae.delete(I)}else if(W==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let H=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(H)});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(W==="step_error"||W==="dispatch_error"||W==="flow_error"){let H=null;if(h.error instanceof Error)H=h.error;else if(W==="dispatch_error"){let I=h.message??h.error;I!=null&&I!==""&&(H=new Error(String(I)))}else{let I=h.error;typeof I=="string"&&I!==""?H=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(H=new Error(String(I.message??I)))}if(H){n({type:"error",error:H});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:W}=await s.read();if(M)break;i+=a.decode(W,{stream:!0});let h=i.split(`
12
12
 
13
13
  `);i=h.pop()??"";for(let H of h){let I=H.split(`
14
14
  `),D="message",K="",j=null;for(let ue of I)ue.startsWith("event:")?D=ue.replace("event:","").trim():ue.startsWith("data:")?K+=ue.replace("data:","").trim():ue.startsWith("id:")&&(j=ue.slice(3).trim());let G=()=>{j!==null&&j!==""&&n({type:"cursor",id:j})};if(!K){G();continue}let pe;try{pe=JSON.parse(K)}catch(ue){n({type:"error",error:ue instanceof Error?ue:new Error("Failed to parse chat stream payload")});continue}let ze=D!=="message"?D:pe.type??"message";if(this.onSSEEvent?.(ze,pe),this.parseSSEEvent){S.current=x;let ue=await this.handleCustomSSEEvent(pe,n,S,f,c,k);if(S.current&&S.current!==x&&(x=S.current),ue){G();continue}}et.push({payloadType:ze,payload:pe}),Le(),G()}}Le()}};function zg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function as(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Do(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ii="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Kg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oo(e){return{type:"text",text:e}}function Gg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Jg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Yg(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 Xg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ov=["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"],io=[...Xg,...ov];function rv(e){return Xg.includes(e)||e.startsWith("image/")}function Hi(e){return rv(e.type)}async function Qg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Hi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Zg(e,t=io,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 sv(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ef(e,t){let n=sv(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"}Zc();var tf=16e3,av=24e3,iv=4096,lv=1380533830;function cv(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===lv?new Uint8Array(e,44):new Uint8Array(e)}function dv(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var la=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:tf,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:tf});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new is(av);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(g=>g.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${dv(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=g=>this.handleMessage(g,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(iv,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let g=Math.max(-1,Math.min(1,p[c]));d[c]=g<0?g*32768:g*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=cv(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var xr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function No(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new la(e.runtype);case"browser":if(!xr.isSupported())throw new Error("Browser speech recognition not supported");return new xr(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 Bi(e){if(e?.type==="custom"&&e.custom)return No({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return No({type:"runtype",runtype:e.runtype});if(xr.isSupported())return No({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ca(e){try{return Bi(e),!0}catch{return!1}}function ls(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Fo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ls(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Cr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function ed(e){if(!e)return"";let t=pv(e);return nf(t!==null?t:e)}function pv(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function nf(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,`