@runtypelabs/persona 4.11.1 → 4.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +13 -13
- package/dist/codegen.d.cts +9 -0
- package/dist/codegen.d.ts +9 -0
- package/dist/codegen.js +13 -13
- package/dist/index.cjs +41 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +42 -42
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/theme-editor-preview.cjs +1 -1
- package/dist/theme-editor-preview.js +1 -1
- package/package.json +1 -1
- package/src/codegen.test.ts +43 -0
- package/src/install.test.ts +83 -0
- package/src/install.ts +48 -2
- package/src/utils/code-generators.ts +30 -4
package/dist/install.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var SiteAgentInstaller=(()=>{var
|
|
1
|
+
"use strict";var SiteAgentInstaller=(()=>{var j=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var Q=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var B=(l,i,f,w)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Q(i))!R.call(l,r)&&r!==f&&j(l,r,{get:()=>i[r],enumerable:!(w=J(i,r))||w.enumerable});return l};var K=l=>B(j({},"__esModule",{value:!0}),l);var N={};(function(){"use strict";if(window.__siteAgentInstallerLoaded)return;window.__siteAgentInstallerLoaded=!0;let i=(()=>{let t=document.currentScript;if(!t)return{};let e={},n=t.getAttribute("data-config");if(n)try{let m=n.replace(/[\r\n]+\s*/g,""),y=JSON.parse(m);if(y.config){let{__proto__:V,constructor:X,prototype:Y,...H}=y;Object.assign(e,H)}else e.config=y}catch(m){console.error("Failed to parse data-config JSON:",m)}let o=t.getAttribute("data-runtype-token");o&&(e.clientToken=o);let a=t.getAttribute("data-flow-id");a&&(e.flowId=a);let s=t.getAttribute("data-agent-id");s&&(e.agentId=s);let u=t.getAttribute("data-api-url");u&&(e.apiUrl=u);let P=t.getAttribute("data-preview-param");return P&&(e.previewQueryParam=P),e})(),f=document.currentScript?.src||"",r={...window.siteAgentConfig||{},...i},c=(t,e)=>{try{t?.(e)}catch(n){console.error("[Persona] lifecycle callback threw:",n)}},d=(t,e)=>{try{window.dispatchEvent(new CustomEvent(t,{detail:e}))}catch{}},p=(t,e)=>{console.error("Failed to install AgentWidget:",e),c(r.onError,{phase:t,error:e}),d("persona:error",{phase:t,error:e})},b=t=>{let e=t.launcher??{};return e.enabled===!1?!1:(e.mountMode??"floating")==="floating"};if(c(r.onScriptLoad,{version:r.version||"latest"}),d("persona:script-load",{version:r.version||"latest"}),!(()=>{if(!r.previewQueryParam)return!0;let e=new URLSearchParams(window.location.search).get(r.previewQueryParam);return e!==null&&e!==""&&e.toLowerCase()!=="false"&&e!=="0"})())return;let k=r.version||"latest",S=r.cdn||"jsdelivr",E=r.autoInit!==!1,T=()=>{if(!f)return null;try{let t=new URL(f,document.baseURI);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.origin+t.pathname.slice(0,t.pathname.lastIndexOf("/"))}catch{return null}},$=()=>{if(r.cssUrl&&r.jsUrl){let o=r.jsUrl.replace(/index\.global\.js($|\?)/,"launcher.global.js$1");return{cssUrl:r.cssUrl,jsUrl:r.jsUrl,launcherUrl:o!==r.jsUrl?o:null}}if(!r.cdn&&!r.version){let o=T();if(o)return{cssUrl:`${o}/widget.css`,jsUrl:`${o}/index.global.js`,launcherUrl:`${o}/launcher.global.js`}}let t="@runtypelabs/persona",e=S==="unpkg"?`/${t}@${k}/dist`:`/npm/${t}@${k}/dist`,n=S==="unpkg"?"https://unpkg.com":"https://cdn.jsdelivr.net";return{cssUrl:`${n}${e}/widget.css`,jsUrl:`${n}${e}/index.global.js`,launcherUrl:`${n}${e}/launcher.global.js`}},{cssUrl:v,jsUrl:g,launcherUrl:h}=$(),W=()=>!!document.head.querySelector("link[data-persona]")||!!document.head.querySelector('link[href*="widget.css"]'),A=()=>!!window.AgentWidget,F=t=>{let e=!1,n=()=>{e||(e=!0,t())},o=()=>{typeof requestIdleCallback<"u"?requestIdleCallback(()=>{requestAnimationFrame(()=>{requestAnimationFrame(n)})},{timeout:3e3}):setTimeout(n,300)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",o):o()},C=()=>new Promise((t,e)=>{if(W()){t();return}let n=document.createElement("link");n.rel="stylesheet",n.href=v,n.setAttribute("data-persona","true"),n.onload=()=>t(),n.onerror=()=>e(new Error(`Failed to load CSS from ${v}`)),document.head.appendChild(n)}),I=()=>new Promise((t,e)=>{if(A()){t();return}let n=document.createElement("script");n.src=g,n.async=!0,n.onload=()=>t(),n.onerror=()=>e(new Error(`Failed to load JS from ${g}`)),document.head.appendChild(n)}),M=()=>!!window.AgentWidgetLauncher,x=()=>new Promise((t,e)=>{if(M()||!h){t();return}let n=document.createElement("script");n.src=h,n.async=!0,n.onload=()=>t(),n.onerror=()=>e(new Error(`Failed to load launcher from ${h}`)),document.head.appendChild(n)}),_=()=>{let t=()=>{if(!A()){let n=document.createElement("link");n.rel="prefetch",n.as="script",n.href=g,document.head.appendChild(n)}let e=g.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");if(e!==g){let n=document.createElement("link");n.rel="prefetch",n.as="script",n.href=e,document.head.appendChild(n)}};typeof requestIdleCallback<"u"?requestIdleCallback(t,{timeout:4e3}):setTimeout(t,1200)},U=()=>{let t=r.target||"body",e={...r.config};r.apiUrl&&!e.apiUrl&&(e.apiUrl=r.apiUrl),r.clientToken&&!e.clientToken&&(e.clientToken=r.clientToken),r.flowId&&!e.flowId&&(e.flowId=r.flowId),r.agentId&&!e.agentId&&(e.agentId=r.agentId);let n=!!(e.apiUrl||e.clientToken);return{target:t,widgetConfig:e,hasApiConfig:n}},L=(t=!1)=>{if(!window.AgentWidget||!window.AgentWidget.initAgentWidget){console.warn("AgentWidget not available. Make sure the script loaded successfully.");return}let{target:e,widgetConfig:n,hasApiConfig:o}=U();if(!(!o&&Object.keys(n).length===0)){!n.postprocessMessage&&window.AgentWidget.markdownPostprocessor&&(n.postprocessMessage=({text:a})=>window.AgentWidget.markdownPostprocessor(a));try{let a=window.AgentWidget.initAgentWidget({target:e,config:n,useShadowDom:r.useShadowDom??!1,windowKey:r.windowKey});return t&&a&&typeof a.open=="function"&&a.open(),!t&&b(n)&&(c(r.onLauncherShown,{deferred:!1}),d("persona:launcher-shown",{deferred:!1})),c(r.onChatReady,a),d("persona:chat-ready",a),a}catch(a){p("init",a)}}},O=t=>{let e=t.persistState;if(!e)return!1;let n=typeof e=="object"?e:null;if(n&&n.persist?.openState===!1)return!1;let o=n&&n.keyPrefix||"persona-",a=n&&n.storage||"session";try{return(a==="local"?window.localStorage:window.sessionStorage).getItem(`${o}widget-open`)==="true"}catch{return!1}},q=t=>!(!h||!b(t)||(t.launcher??{}).autoExpand===!0||typeof t.onStateLoaded=="function"||O(t)),D=(t,e)=>{let n="idle",o,a=()=>{n==="idle"&&(n="loading",I().then(()=>{L(!0),o?.destroy(),n="done"}).catch(u=>{n="idle",console.error("Failed to load AgentWidget on open:",u),c(r.onError,{phase:"bundle",error:u}),d("persona:error",{phase:"bundle",error:u})}))},s=window.AgentWidgetLauncher.mount({target:t,config:e,onOpen:a});o=s,c(r.onLauncherShown,{deferred:!0,element:s.element}),d("persona:launcher-shown",{deferred:!0,element:s.element}),_()};F(async()=>{try{let t=E&&(r.config||r.apiUrl||r.clientToken);if(t){let{target:e,widgetConfig:n}=U();if(q(n))try{if(await Promise.all([C(),x()]),window.AgentWidgetLauncher&&window.AgentWidgetLauncher.mount){D(e,n);return}}catch(o){console.warn("Deferred launcher failed; falling back to eager load.",o)}}try{await C()}catch(e){return p("css",e)}try{await I()}catch(e){return p("bundle",e)}t&&setTimeout(()=>L(!1),0)}catch(t){p("init",t)}})})();return K(N);})();
|
|
2
2
|
//# sourceMappingURL=install.global.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/install.ts"],"sourcesContent":["/**\n * Standalone installer script for easy script tag installation\n * This script automatically loads CSS and JS, then initializes the widget\n * if configuration is provided via window.siteAgentConfig\n */\n\nexport {};\n\ninterface SiteAgentInstallConfig {\n version?: string;\n cdn?: \"unpkg\" | \"jsdelivr\";\n cssUrl?: string;\n jsUrl?: string;\n target?: string | HTMLElement;\n config?: any;\n autoInit?: boolean;\n // Client token mode options (can also be set via data attributes)\n clientToken?: string;\n flowId?: string;\n agentId?: string;\n apiUrl?: string;\n // Optional query param key that gates widget installation in preview mode\n previewQueryParam?: string;\n // Shadow DOM option (defaults to false for better CSS compatibility)\n useShadowDom?: boolean;\n // Expose the widget handle on window[windowKey] for programmatic access\n windowKey?: string;\n /**\n * Fired as soon as the installer script executes, before it loads or gates\n * anything. For diagnostics / load-timing baselines (\"did my embed run\").\n */\n onScriptLoad?: (info: { version: string }) => void;\n /**\n * Fired when the floating launcher is painted on the page: at page-load time.\n * Deferred installs: the critical launcher mounts. Eager floating installs:\n * the full widget's launcher mounts. Use this for \"widget appeared\" analytics.\n * Does NOT fire for inline / docked / composer-bar installs (no floating\n * launcher): use `onChatReady` there.\n */\n onLauncherShown?: (info: { deferred: boolean; element?: HTMLElement }) => void;\n /**\n * Fired when the full widget is initialized and its controller API is\n * callable. Deferred installs: after the user first opens the panel. Eager\n * installs: on page load.\n */\n onChatReady?: (handle: any) => void;\n /**\n * Fired when a load step fails (stylesheet, full bundle, or init), so you can\n * detect ad-blocked / timed-out installs instead of failing silently.\n */\n onError?: (info: { phase: \"css\" | \"bundle\" | \"init\"; error: unknown }) => void;\n}\n\ndeclare global {\n interface Window {\n siteAgentConfig?: SiteAgentInstallConfig;\n AgentWidget?: any;\n AgentWidgetLauncher?: any;\n }\n}\n\n(function() {\n \"use strict\";\n\n // Prevent double installation\n if ((window as any).__siteAgentInstallerLoaded) {\n return;\n }\n (window as any).__siteAgentInstallerLoaded = true;\n\n /**\n * Read configuration from data attributes on the current script tag.\n * Supports: data-config (JSON), data-runtype-token, data-flow-id, data-agent-id, data-api-url\n */\n const getConfigFromScript = (): Partial<SiteAgentInstallConfig> => {\n // Try to get the current script element\n const script = document.currentScript as HTMLScriptElement | null;\n if (!script) return {};\n\n const scriptConfig: Partial<SiteAgentInstallConfig> = {};\n\n // Full config from data-config attribute (JSON string)\n const configJson = script.getAttribute('data-config');\n if (configJson) {\n try {\n // HTML attributes preserve literal newlines/tabs which are invalid\n // control characters inside JSON string literals: strip them.\n const normalizedJson = configJson.replace(/[\\r\\n]+\\s*/g, '');\n const parsedConfig = JSON.parse(normalizedJson);\n // If it has nested 'config' property, use it; otherwise treat as widget config\n if (parsedConfig.config) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { __proto__: _a, constructor: _b, prototype: _c, ...safeConfig } = parsedConfig;\n Object.assign(scriptConfig, safeConfig);\n } else {\n // Treat the entire object as widget config\n scriptConfig.config = parsedConfig;\n }\n } catch (e) {\n console.error(\"Failed to parse data-config JSON:\", e);\n }\n }\n\n // Client token from data attribute (primary method for client token mode)\n const token = script.getAttribute('data-runtype-token');\n if (token) {\n scriptConfig.clientToken = token;\n }\n\n // Optional flow ID\n const flowId = script.getAttribute('data-flow-id');\n if (flowId) {\n scriptConfig.flowId = flowId;\n }\n\n // Optional agent ID\n const agentId = script.getAttribute('data-agent-id');\n if (agentId) {\n scriptConfig.agentId = agentId;\n }\n\n // Optional API URL override\n const apiUrl = script.getAttribute('data-api-url');\n if (apiUrl) {\n scriptConfig.apiUrl = apiUrl;\n }\n\n // Optional preview query param gate\n const previewQueryParam = script.getAttribute('data-preview-param');\n if (previewQueryParam) {\n scriptConfig.previewQueryParam = previewQueryParam;\n }\n\n return scriptConfig;\n };\n\n // Get config from script attributes (must be called synchronously during script execution)\n const scriptConfig = getConfigFromScript();\n\n // Merge script attributes with window config (script attributes take precedence)\n const windowConfig: SiteAgentInstallConfig = window.siteAgentConfig || {};\n const config: SiteAgentInstallConfig = { ...windowConfig, ...scriptConfig };\n\n // --- Lifecycle helpers -----------------------------------------------------\n // A throwing user callback must never break the installer.\n const safeCall = <T>(fn: ((arg: T) => void) | undefined, arg: T): void => {\n try {\n fn?.(arg);\n } catch (e) {\n console.error(\"[Persona] lifecycle callback threw:\", e);\n }\n };\n const dispatchLifecycle = (name: string, detail: unknown): void => {\n try {\n window.dispatchEvent(new CustomEvent(name, { detail }));\n } catch {\n /* CustomEvent unsupported: ignore */\n }\n };\n const fail = (phase: \"css\" | \"bundle\" | \"init\", error: unknown): void => {\n console.error(\"Failed to install AgentWidget:\", error);\n safeCall(config.onError, { phase, error });\n dispatchLifecycle(\"persona:error\", { phase, error });\n };\n // True when the config renders a standard floating launcher button: the only\n // case that paints a clickable launcher at load. Shared by the deferral gate\n // and the eager-path `onLauncherShown` so the event name stays honest.\n const hasFloatingLauncher = (widgetConfig: any): boolean => {\n const launcher = widgetConfig.launcher ?? {};\n if (launcher.enabled === false) return false; // inline embed\n return (launcher.mountMode ?? \"floating\") === \"floating\"; // not docked / composer-bar\n };\n\n // Earliest signal: the installer has executed. Fire before any loading or\n // preview-gating so it's a reliable \"did my embed run\" beacon for diagnostics.\n safeCall(config.onScriptLoad, { version: config.version || \"latest\" });\n dispatchLifecycle(\"persona:script-load\", { version: config.version || \"latest\" });\n\n const isPreviewModeEnabled = (): boolean => {\n if (!config.previewQueryParam) {\n return true;\n }\n\n const params = new URLSearchParams(window.location.search);\n const value = params.get(config.previewQueryParam);\n return value !== null && value !== \"\" && value.toLowerCase() !== \"false\" && value !== \"0\";\n };\n\n if (!isPreviewModeEnabled()) {\n return;\n }\n \n const version = config.version || \"latest\";\n const cdn = config.cdn || \"jsdelivr\";\n const autoInit = config.autoInit !== false; // Default to true\n\n // Determine CDN base URL\n const getCdnBase = () => {\n // For a custom URL override, derive the sibling launcher URL when the\n // override mirrors the dist layout (…/index.global.js → …/launcher.global.js)\n // so self-hosted deployments still get the optimization. A non-standard\n // jsUrl yields null → eager-load fallback.\n if (config.cssUrl && config.jsUrl) {\n const derivedLauncherUrl = config.jsUrl.replace(/index\\.global\\.js($|\\?)/, \"launcher.global.js$1\");\n return {\n cssUrl: config.cssUrl,\n jsUrl: config.jsUrl,\n launcherUrl: (derivedLauncherUrl !== config.jsUrl ? derivedLauncherUrl : null) as string | null,\n };\n }\n\n const packageName = \"@runtypelabs/persona\";\n const basePath = `/npm/${packageName}@${version}/dist`;\n const host = cdn === \"unpkg\" ? \"https://unpkg.com\" : \"https://cdn.jsdelivr.net\";\n\n return {\n cssUrl: `${host}${basePath}/widget.css`,\n jsUrl: `${host}${basePath}/index.global.js`,\n launcherUrl: `${host}${basePath}/launcher.global.js` as string | null,\n };\n };\n\n const { cssUrl, jsUrl, launcherUrl } = getCdnBase();\n\n // Check if CSS is already loaded\n const isCssLoaded = () => {\n return !!document.head.querySelector('link[data-persona]') ||\n !!document.head.querySelector(`link[href*=\"widget.css\"]`);\n };\n\n // Check if JS is already loaded\n const isJsLoaded = () => {\n return !!(window as any).AgentWidget;\n };\n\n /**\n * Wait for framework hydration to complete (Next.js, Nuxt, etc.)\n * This prevents the framework from removing dynamically added CSS during reconciliation.\n * Uses requestIdleCallback + double requestAnimationFrame for reliable detection.\n */\n const waitForHydration = (callback: () => void): void => {\n let executed = false;\n \n const execute = () => {\n if (executed) return;\n executed = true;\n callback();\n };\n\n const afterDom = () => {\n // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)\n if (typeof requestIdleCallback !== 'undefined') {\n requestIdleCallback(() => {\n // Double requestAnimationFrame ensures at least one full paint cycle completed\n requestAnimationFrame(() => {\n requestAnimationFrame(execute);\n });\n }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway\n } else {\n // Strategy 2: Fallback for Safari (no requestIdleCallback)\n // 300ms is typically enough for hydration on most pages\n setTimeout(execute, 300);\n }\n };\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', afterDom);\n } else {\n // DOM already ready, but still wait for potential hydration\n afterDom();\n }\n };\n\n // Load CSS\n const loadCSS = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isCssLoaded()) {\n resolve();\n return;\n }\n\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = cssUrl;\n link.setAttribute(\"data-persona\", \"true\");\n \n link.onload = () => resolve();\n link.onerror = () => reject(new Error(`Failed to load CSS from ${cssUrl}`));\n document.head.appendChild(link);\n });\n };\n\n // Load JS\n const loadJS = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isJsLoaded()) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = jsUrl;\n script.async = true;\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(`Failed to load JS from ${jsUrl}`));\n document.head.appendChild(script);\n });\n };\n\n // Load the tiny launcher-only critical bundle (launcher.global.js)\n const isLauncherLoaded = () => !!window.AgentWidgetLauncher;\n\n const loadLauncher = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isLauncherLoaded() || !launcherUrl) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = launcherUrl;\n script.async = true;\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(`Failed to load launcher from ${launcherUrl}`));\n document.head.appendChild(script);\n });\n };\n\n // Warm the full bundle in the background (download-only, not executed) so the\n // first open is quick. Runs at idle so it never competes with the launcher.\n const prefetchFullBundle = (): void => {\n const addPrefetch = () => {\n if (!isJsLoaded()) {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.as = \"script\";\n link.href = jsUrl;\n document.head.appendChild(link);\n }\n\n // Also prefetch the markdown parsers chunk\n const markdownUrl = jsUrl.replace(/index\\.global\\.js($|\\?)/, \"markdown-parsers.js$1\");\n if (markdownUrl !== jsUrl) {\n const link2 = document.createElement(\"link\");\n link2.rel = \"prefetch\";\n link2.as = \"script\";\n link2.href = markdownUrl;\n document.head.appendChild(link2);\n }\n };\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(addPrefetch, { timeout: 4000 });\n } else {\n setTimeout(addPrefetch, 1200);\n }\n };\n\n // Merge top-level installer options into the widget config. Shared by the\n // eager init path and the deferred-launcher path.\n const buildWidgetInit = (): { target: string | HTMLElement; widgetConfig: any; hasApiConfig: boolean } => {\n const target = config.target || \"body\";\n const widgetConfig: any = { ...config.config };\n\n if (config.apiUrl && !widgetConfig.apiUrl) widgetConfig.apiUrl = config.apiUrl;\n if (config.clientToken && !widgetConfig.clientToken) widgetConfig.clientToken = config.clientToken;\n if (config.flowId && !widgetConfig.flowId) widgetConfig.flowId = config.flowId;\n if (config.agentId && !widgetConfig.agentId) widgetConfig.agentId = config.agentId;\n\n const hasApiConfig = !!(widgetConfig.apiUrl || widgetConfig.clientToken);\n return { target, widgetConfig, hasApiConfig };\n };\n\n // Initialize the full widget. When `openAfter` is true (the deferred-launcher\n // handoff), open the panel immediately via the public controller API so the\n // user's click on the critical launcher carries through.\n const initWidget = (openAfter = false): any => {\n if (!window.AgentWidget || !window.AgentWidget.initAgentWidget) {\n console.warn(\"AgentWidget not available. Make sure the script loaded successfully.\");\n return;\n }\n\n const { target, widgetConfig, hasApiConfig } = buildWidgetInit();\n\n // Only initialize if we have either apiUrl OR clientToken (or other config)\n if (!hasApiConfig && Object.keys(widgetConfig).length === 0) {\n return;\n }\n\n // Auto-apply markdown postprocessor if not explicitly set and available\n if (!widgetConfig.postprocessMessage && window.AgentWidget.markdownPostprocessor) {\n widgetConfig.postprocessMessage = ({ text }: { text: string }) =>\n window.AgentWidget.markdownPostprocessor(text);\n }\n\n try {\n const handle = window.AgentWidget.initAgentWidget({\n target,\n config: widgetConfig,\n // Explicitly disable shadow DOM for better CSS compatibility with host page\n useShadowDom: config.useShadowDom ?? false,\n windowKey: config.windowKey\n });\n\n // Handoff from the critical launcher: the user already clicked, so open\n // the panel via the existing public controller method.\n if (openAfter && handle && typeof handle.open === \"function\") {\n handle.open();\n }\n\n // Eager floating installs paint their launcher at load time too: emit the\n // same page-load \"appeared\" signal as the deferred path. The deferred\n // handoff (openAfter) already fired it at launcher mount, and non-floating\n // modes have no launcher, so guard on both.\n if (!openAfter && hasFloatingLauncher(widgetConfig)) {\n safeCall(config.onLauncherShown, { deferred: false });\n dispatchLifecycle(\"persona:launcher-shown\", { deferred: false });\n }\n\n // The full widget is initialized and its controller API is callable.\n safeCall(config.onChatReady, handle);\n dispatchLifecycle(\"persona:chat-ready\", handle);\n return handle;\n } catch (error) {\n fail(\"init\", error);\n }\n };\n\n // A persisted \"open\" state reopens the panel on reload with no click\n // (ui.ts:7513). The installer can't see that from config, so it reads the very\n // same storage key the widget writes. Mirrors normalizePersistStateConfig\n // (ui.ts:213): openState persistence defaults on, storage to sessionStorage,\n // key prefix to \"persona-\".\n const hasPersistedOpenState = (widgetConfig: any): boolean => {\n const persistState = widgetConfig.persistState;\n if (!persistState) return false; // persistence off → nothing to restore\n const asObject = typeof persistState === \"object\" ? persistState : null;\n if (asObject && asObject.persist?.openState === false) return false; // open-state persistence opted out\n const keyPrefix = (asObject && asObject.keyPrefix) || \"persona-\";\n const storageType = (asObject && asObject.storage) || \"session\";\n try {\n const storage = storageType === \"local\" ? window.localStorage : window.sessionStorage;\n return storage.getItem(`${keyPrefix}widget-open`) === \"true\";\n } catch {\n return false; // storage blocked (private mode) → the widget can't restore either\n }\n };\n\n // The deferred-launcher optimization only applies to the common floating case\n // that paints a collapsed launcher and waits for a click. Anything that starts\n // open or renders differently eager-loads the full bundle exactly as before: // including the two open triggers config alone can't express: a host\n // onStateLoaded hook that may request open, and a restored \"was open\" state.\n const shouldDeferPanel = (widgetConfig: any): boolean => {\n if (!launcherUrl) return false; // custom bundle URL override: can't derive launcher URL\n if (!hasFloatingLauncher(widgetConfig)) return false; // inline / docked / composer-bar\n const launcher = widgetConfig.launcher ?? {};\n if (launcher.autoExpand === true) return false; // starts open\n if (typeof widgetConfig.onStateLoaded === \"function\") return false; // hook may request open\n if (hasPersistedOpenState(widgetConfig)) return false; // restored \"was open\"\n return true;\n };\n\n // Render the real launcher from the tiny critical bundle; load + mount the\n // full widget on first click, then remove the critical launcher.\n const mountDeferredLauncher = (target: string | HTMLElement, widgetConfig: any): void => {\n let phase: \"idle\" | \"loading\" | \"done\" = \"idle\";\n let launcherHandle: { destroy: () => void } | undefined;\n\n const onOpen = () => {\n if (phase !== \"idle\") return; // already loading or handed off\n phase = \"loading\";\n loadJS()\n .then(() => {\n initWidget(true); // mount the full widget + open the panel\n launcherHandle?.destroy(); // remove the critical launcher (same component → invisible)\n phase = \"done\";\n })\n .catch((error) => {\n phase = \"idle\"; // allow the click to be retried\n console.error(\"Failed to load AgentWidget on open:\", error);\n safeCall(config.onError, { phase: \"bundle\", error });\n dispatchLifecycle(\"persona:error\", { phase: \"bundle\", error });\n });\n };\n\n const mounted = window.AgentWidgetLauncher.mount({ target, config: widgetConfig, onOpen });\n launcherHandle = mounted;\n\n // The real launcher is now painted at page-load time: emit the page-load\n // \"appeared\" signal (distinct from `onChatReady`, which waits for first open).\n safeCall(config.onLauncherShown, { deferred: true, element: mounted.element });\n dispatchLifecycle(\"persona:launcher-shown\", { deferred: true, element: mounted.element });\n\n // Warm the full bundle so the first open is quick.\n prefetchFullBundle();\n };\n\n // Main installation flow (called after hydration completes)\n const install = async () => {\n try {\n // Auto-init if we have config OR apiUrl OR clientToken\n const shouldAutoInit = autoInit && (\n config.config ||\n config.apiUrl ||\n config.clientToken\n );\n\n // Fast path: render the real launcher from the ~13 KB critical bundle and\n // defer the full widget until first open. Only for the common floating\n // case; everything else falls through to the eager path below.\n if (shouldAutoInit) {\n const { target, widgetConfig } = buildWidgetInit();\n if (shouldDeferPanel(widgetConfig)) {\n try {\n // CSS + launcher in parallel so the launcher paints correctly styled.\n await Promise.all([loadCSS(), loadLauncher()]);\n if (window.AgentWidgetLauncher && window.AgentWidgetLauncher.mount) {\n mountDeferredLauncher(target, widgetConfig);\n return;\n }\n } catch (error) {\n console.warn(\"Deferred launcher failed; falling back to eager load.\", error);\n }\n // Fall through to the eager path on any failure.\n }\n }\n\n // Eager path (unchanged behavior): load the full bundle, then init.\n try {\n await loadCSS();\n } catch (error) {\n return fail(\"css\", error);\n }\n try {\n await loadJS();\n } catch (error) {\n return fail(\"bundle\", error);\n }\n if (shouldAutoInit) {\n // Wait a tick to ensure AgentWidget is fully initialized\n setTimeout(() => initWidget(false), 0);\n }\n } catch (error) {\n // Safety net for anything unexpected before the eager loads above.\n fail(\"init\", error);\n }\n };\n\n // Start installation after hydration completes\n // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS\n waitForHydration(install);\n})();\n\n"],"mappings":"4YAAA,IAAAA,EAAA,IA6DC,UAAW,CACV,aAGA,GAAK,OAAe,2BAClB,OAED,OAAe,2BAA6B,GAqE7C,IAAMC,GA/DsB,IAAuC,CAEjE,IAAMC,EAAS,SAAS,cACxB,GAAI,CAACA,EAAQ,MAAO,CAAC,EAErB,IAAMD,EAAgD,CAAC,EAGjDE,EAAaD,EAAO,aAAa,aAAa,EACpD,GAAIC,EACF,GAAI,CAGF,IAAMC,EAAiBD,EAAW,QAAQ,cAAe,EAAE,EACrDE,EAAe,KAAK,MAAMD,CAAc,EAE9C,GAAIC,EAAa,OAAQ,CAEvB,GAAM,CAAE,UAAWC,EAAI,YAAaC,EAAI,UAAWC,EAAI,GAAGC,CAAW,EAAIJ,EACzE,OAAO,OAAOJ,EAAcQ,CAAU,CACxC,MAEER,EAAa,OAASI,CAE1B,OAASK,EAAG,CACV,QAAQ,MAAM,oCAAqCA,CAAC,CACtD,CAIF,IAAMC,EAAQT,EAAO,aAAa,oBAAoB,EAClDS,IACFV,EAAa,YAAcU,GAI7B,IAAMC,EAASV,EAAO,aAAa,cAAc,EAC7CU,IACFX,EAAa,OAASW,GAIxB,IAAMC,EAAUX,EAAO,aAAa,eAAe,EAC/CW,IACFZ,EAAa,QAAUY,GAIzB,IAAMC,EAASZ,EAAO,aAAa,cAAc,EAC7CY,IACFb,EAAa,OAASa,GAIx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O,CAAC,EACzFD,EAAiBE,EAIjBzD,EAASD,EAAO,gBAAiB,CAAE,SAAU,GAAM,QAAS0D,EAAQ,OAAQ,CAAC,EAC7EtD,EAAkB,yBAA0B,CAAE,SAAU,GAAM,QAASsD,EAAQ,OAAQ,CAAC,EAGxFpB,EAAmB,CACrB,EAuDAZ,EApDgB,SAAY,CAC1B,GAAI,CAEF,IAAMiC,EAAiB3C,IACrBhB,EAAO,QACPA,EAAO,QACPA,EAAO,aAMT,GAAI2D,EAAgB,CAClB,GAAM,CAAE,OAAAhB,EAAQ,aAAAhC,CAAa,EAAI+B,EAAgB,EACjD,GAAIY,EAAiB3C,CAAY,EAC/B,GAAI,CAGF,GADA,MAAM,QAAQ,IAAI,CAACoB,EAAQ,EAAGM,EAAa,CAAC,CAAC,EACzC,OAAO,qBAAuB,OAAO,oBAAoB,MAAO,CAClEkB,EAAsBZ,EAAQhC,CAAY,EAC1C,MACF,CACF,OAASF,EAAO,CACd,QAAQ,KAAK,wDAAyDA,CAAK,CAC7E,CAGJ,CAGA,GAAI,CACF,MAAMsB,EAAQ,CAChB,OAAStB,EAAO,CACd,OAAOF,EAAK,MAAOE,CAAK,CAC1B,CACA,GAAI,CACF,MAAM0B,EAAO,CACf,OAAS1B,EAAO,CACd,OAAOF,EAAK,SAAUE,CAAK,CAC7B,CACIkD,GAEF,WAAW,IAAMd,EAAW,EAAK,EAAG,CAAC,CAEzC,OAASpC,EAAO,CAEdF,EAAK,OAAQE,CAAK,CACpB,CACF,CAIwB,CAC1B,GAAG","names":["install_exports","scriptConfig","script","configJson","normalizedJson","parsedConfig","_a","_b","_c","safeConfig","e","token","flowId","agentId","apiUrl","previewQueryParam","config","safeCall","fn","arg","dispatchLifecycle","name","detail","fail","phase","error","hasFloatingLauncher","widgetConfig","launcher","value","version","cdn","autoInit","getCdnBase","derivedLauncherUrl","basePath","host","cssUrl","jsUrl","launcherUrl","isCssLoaded","isJsLoaded","waitForHydration","callback","executed","execute","afterDom","loadCSS","resolve","reject","link","loadJS","isLauncherLoaded","loadLauncher","prefetchFullBundle","addPrefetch","markdownUrl","link2","buildWidgetInit","target","hasApiConfig","initWidget","openAfter","text","handle","hasPersistedOpenState","persistState","asObject","keyPrefix","storageType","shouldDeferPanel","mountDeferredLauncher","launcherHandle","onOpen","mounted","shouldAutoInit"]}
|
|
1
|
+
{"version":3,"sources":["../src/install.ts"],"sourcesContent":["/**\n * Standalone installer script for easy script tag installation\n * This script automatically loads CSS and JS, then initializes the widget\n * if configuration is provided via window.siteAgentConfig\n */\n\nexport {};\n\ninterface SiteAgentInstallConfig {\n // Setting `version` or `cdn` explicitly opts into npm-CDN asset URLs\n // (jsDelivr/unpkg). When neither is set, assets load from the directory the\n // installer script itself was served from — see getCdnBase().\n version?: string;\n cdn?: \"unpkg\" | \"jsdelivr\";\n cssUrl?: string;\n jsUrl?: string;\n target?: string | HTMLElement;\n config?: any;\n autoInit?: boolean;\n // Client token mode options (can also be set via data attributes)\n clientToken?: string;\n flowId?: string;\n agentId?: string;\n apiUrl?: string;\n // Optional query param key that gates widget installation in preview mode\n previewQueryParam?: string;\n // Shadow DOM option (defaults to false for better CSS compatibility)\n useShadowDom?: boolean;\n // Expose the widget handle on window[windowKey] for programmatic access\n windowKey?: string;\n /**\n * Fired as soon as the installer script executes, before it loads or gates\n * anything. For diagnostics / load-timing baselines (\"did my embed run\").\n */\n onScriptLoad?: (info: { version: string }) => void;\n /**\n * Fired when the floating launcher is painted on the page: at page-load time.\n * Deferred installs: the critical launcher mounts. Eager floating installs:\n * the full widget's launcher mounts. Use this for \"widget appeared\" analytics.\n * Does NOT fire for inline / docked / composer-bar installs (no floating\n * launcher): use `onChatReady` there.\n */\n onLauncherShown?: (info: { deferred: boolean; element?: HTMLElement }) => void;\n /**\n * Fired when the full widget is initialized and its controller API is\n * callable. Deferred installs: after the user first opens the panel. Eager\n * installs: on page load.\n */\n onChatReady?: (handle: any) => void;\n /**\n * Fired when a load step fails (stylesheet, full bundle, or init), so you can\n * detect ad-blocked / timed-out installs instead of failing silently.\n */\n onError?: (info: { phase: \"css\" | \"bundle\" | \"init\"; error: unknown }) => void;\n}\n\ndeclare global {\n interface Window {\n siteAgentConfig?: SiteAgentInstallConfig;\n AgentWidget?: any;\n AgentWidgetLauncher?: any;\n }\n}\n\n(function() {\n \"use strict\";\n\n // Prevent double installation\n if ((window as any).__siteAgentInstallerLoaded) {\n return;\n }\n (window as any).__siteAgentInstallerLoaded = true;\n\n /**\n * Read configuration from data attributes on the current script tag.\n * Supports: data-config (JSON), data-runtype-token, data-flow-id, data-agent-id, data-api-url\n */\n const getConfigFromScript = (): Partial<SiteAgentInstallConfig> => {\n // Try to get the current script element\n const script = document.currentScript as HTMLScriptElement | null;\n if (!script) return {};\n\n const scriptConfig: Partial<SiteAgentInstallConfig> = {};\n\n // Full config from data-config attribute (JSON string)\n const configJson = script.getAttribute('data-config');\n if (configJson) {\n try {\n // HTML attributes preserve literal newlines/tabs which are invalid\n // control characters inside JSON string literals: strip them.\n const normalizedJson = configJson.replace(/[\\r\\n]+\\s*/g, '');\n const parsedConfig = JSON.parse(normalizedJson);\n // If it has nested 'config' property, use it; otherwise treat as widget config\n if (parsedConfig.config) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { __proto__: _a, constructor: _b, prototype: _c, ...safeConfig } = parsedConfig;\n Object.assign(scriptConfig, safeConfig);\n } else {\n // Treat the entire object as widget config\n scriptConfig.config = parsedConfig;\n }\n } catch (e) {\n console.error(\"Failed to parse data-config JSON:\", e);\n }\n }\n\n // Client token from data attribute (primary method for client token mode)\n const token = script.getAttribute('data-runtype-token');\n if (token) {\n scriptConfig.clientToken = token;\n }\n\n // Optional flow ID\n const flowId = script.getAttribute('data-flow-id');\n if (flowId) {\n scriptConfig.flowId = flowId;\n }\n\n // Optional agent ID\n const agentId = script.getAttribute('data-agent-id');\n if (agentId) {\n scriptConfig.agentId = agentId;\n }\n\n // Optional API URL override\n const apiUrl = script.getAttribute('data-api-url');\n if (apiUrl) {\n scriptConfig.apiUrl = apiUrl;\n }\n\n // Optional preview query param gate\n const previewQueryParam = script.getAttribute('data-preview-param');\n if (previewQueryParam) {\n scriptConfig.previewQueryParam = previewQueryParam;\n }\n\n return scriptConfig;\n };\n\n // Get config from script attributes (must be called synchronously during script execution)\n const scriptConfig = getConfigFromScript();\n\n // The installer's own URL, captured now because document.currentScript is\n // null once synchronous execution ends (and always inside modules).\n const installerSrc = (document.currentScript as HTMLScriptElement | null)?.src || \"\";\n\n // Merge script attributes with window config (script attributes take precedence)\n const windowConfig: SiteAgentInstallConfig = window.siteAgentConfig || {};\n const config: SiteAgentInstallConfig = { ...windowConfig, ...scriptConfig };\n\n // --- Lifecycle helpers -----------------------------------------------------\n // A throwing user callback must never break the installer.\n const safeCall = <T>(fn: ((arg: T) => void) | undefined, arg: T): void => {\n try {\n fn?.(arg);\n } catch (e) {\n console.error(\"[Persona] lifecycle callback threw:\", e);\n }\n };\n const dispatchLifecycle = (name: string, detail: unknown): void => {\n try {\n window.dispatchEvent(new CustomEvent(name, { detail }));\n } catch {\n /* CustomEvent unsupported: ignore */\n }\n };\n const fail = (phase: \"css\" | \"bundle\" | \"init\", error: unknown): void => {\n console.error(\"Failed to install AgentWidget:\", error);\n safeCall(config.onError, { phase, error });\n dispatchLifecycle(\"persona:error\", { phase, error });\n };\n // True when the config renders a standard floating launcher button: the only\n // case that paints a clickable launcher at load. Shared by the deferral gate\n // and the eager-path `onLauncherShown` so the event name stays honest.\n const hasFloatingLauncher = (widgetConfig: any): boolean => {\n const launcher = widgetConfig.launcher ?? {};\n if (launcher.enabled === false) return false; // inline embed\n return (launcher.mountMode ?? \"floating\") === \"floating\"; // not docked / composer-bar\n };\n\n // Earliest signal: the installer has executed. Fire before any loading or\n // preview-gating so it's a reliable \"did my embed run\" beacon for diagnostics.\n safeCall(config.onScriptLoad, { version: config.version || \"latest\" });\n dispatchLifecycle(\"persona:script-load\", { version: config.version || \"latest\" });\n\n const isPreviewModeEnabled = (): boolean => {\n if (!config.previewQueryParam) {\n return true;\n }\n\n const params = new URLSearchParams(window.location.search);\n const value = params.get(config.previewQueryParam);\n return value !== null && value !== \"\" && value.toLowerCase() !== \"false\" && value !== \"0\";\n };\n\n if (!isPreviewModeEnabled()) {\n return;\n }\n \n const version = config.version || \"latest\";\n const cdn = config.cdn || \"jsdelivr\";\n const autoInit = config.autoInit !== false; // Default to true\n\n // Directory the installer itself was served from. Every published layout\n // (npm CDN dist/, first-party CDN, self-hosted copies) keeps the sibling\n // assets next to install.global.js, so this base is valid wherever the\n // installer loaded from — and always satisfies the same CSP/origin rules\n // that let the installer through. Non-http(s) sources (inline, blob:) and\n // module contexts (no currentScript) yield null.\n const getInstallerBase = (): string | null => {\n if (!installerSrc) return null;\n try {\n const url = new URL(installerSrc, document.baseURI);\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") return null;\n return url.origin + url.pathname.slice(0, url.pathname.lastIndexOf(\"/\"));\n } catch {\n return null;\n }\n };\n\n // Determine CDN base URL. Precedence:\n // 1. explicit cssUrl + jsUrl\n // 2. explicit `cdn` / `version` → npm CDN construction\n // 3. the installer's own directory (default)\n // 4. npm CDN construction (currentScript unavailable)\n const getCdnBase = () => {\n // For a custom URL override, derive the sibling launcher URL when the\n // override mirrors the dist layout (…/index.global.js → …/launcher.global.js)\n // so self-hosted deployments still get the optimization. A non-standard\n // jsUrl yields null → eager-load fallback.\n if (config.cssUrl && config.jsUrl) {\n const derivedLauncherUrl = config.jsUrl.replace(/index\\.global\\.js($|\\?)/, \"launcher.global.js$1\");\n return {\n cssUrl: config.cssUrl,\n jsUrl: config.jsUrl,\n launcherUrl: (derivedLauncherUrl !== config.jsUrl ? derivedLauncherUrl : null) as string | null,\n };\n }\n\n // Default: load assets from wherever the installer was served, so a page\n // whose CSP allows only its own CDN (e.g. cdn.runtype.com) never has\n // sibling requests fan out to a third-party host. An explicit `cdn` or\n // `version` keeps the documented npm-CDN behavior.\n if (!config.cdn && !config.version) {\n const selfBase = getInstallerBase();\n if (selfBase) {\n return {\n cssUrl: `${selfBase}/widget.css`,\n jsUrl: `${selfBase}/index.global.js`,\n launcherUrl: `${selfBase}/launcher.global.js` as string | null,\n };\n }\n }\n\n const packageName = \"@runtypelabs/persona\";\n // jsDelivr namespaces npm packages under /npm/; unpkg serves them at the root.\n const basePath = cdn === \"unpkg\"\n ? `/${packageName}@${version}/dist`\n : `/npm/${packageName}@${version}/dist`;\n const host = cdn === \"unpkg\" ? \"https://unpkg.com\" : \"https://cdn.jsdelivr.net\";\n\n return {\n cssUrl: `${host}${basePath}/widget.css`,\n jsUrl: `${host}${basePath}/index.global.js`,\n launcherUrl: `${host}${basePath}/launcher.global.js` as string | null,\n };\n };\n\n const { cssUrl, jsUrl, launcherUrl } = getCdnBase();\n\n // Check if CSS is already loaded\n const isCssLoaded = () => {\n return !!document.head.querySelector('link[data-persona]') ||\n !!document.head.querySelector(`link[href*=\"widget.css\"]`);\n };\n\n // Check if JS is already loaded\n const isJsLoaded = () => {\n return !!(window as any).AgentWidget;\n };\n\n /**\n * Wait for framework hydration to complete (Next.js, Nuxt, etc.)\n * This prevents the framework from removing dynamically added CSS during reconciliation.\n * Uses requestIdleCallback + double requestAnimationFrame for reliable detection.\n */\n const waitForHydration = (callback: () => void): void => {\n let executed = false;\n \n const execute = () => {\n if (executed) return;\n executed = true;\n callback();\n };\n\n const afterDom = () => {\n // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)\n if (typeof requestIdleCallback !== 'undefined') {\n requestIdleCallback(() => {\n // Double requestAnimationFrame ensures at least one full paint cycle completed\n requestAnimationFrame(() => {\n requestAnimationFrame(execute);\n });\n }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway\n } else {\n // Strategy 2: Fallback for Safari (no requestIdleCallback)\n // 300ms is typically enough for hydration on most pages\n setTimeout(execute, 300);\n }\n };\n\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', afterDom);\n } else {\n // DOM already ready, but still wait for potential hydration\n afterDom();\n }\n };\n\n // Load CSS\n const loadCSS = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isCssLoaded()) {\n resolve();\n return;\n }\n\n const link = document.createElement(\"link\");\n link.rel = \"stylesheet\";\n link.href = cssUrl;\n link.setAttribute(\"data-persona\", \"true\");\n \n link.onload = () => resolve();\n link.onerror = () => reject(new Error(`Failed to load CSS from ${cssUrl}`));\n document.head.appendChild(link);\n });\n };\n\n // Load JS\n const loadJS = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isJsLoaded()) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = jsUrl;\n script.async = true;\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(`Failed to load JS from ${jsUrl}`));\n document.head.appendChild(script);\n });\n };\n\n // Load the tiny launcher-only critical bundle (launcher.global.js)\n const isLauncherLoaded = () => !!window.AgentWidgetLauncher;\n\n const loadLauncher = (): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (isLauncherLoaded() || !launcherUrl) {\n resolve();\n return;\n }\n\n const script = document.createElement(\"script\");\n script.src = launcherUrl;\n script.async = true;\n script.onload = () => resolve();\n script.onerror = () => reject(new Error(`Failed to load launcher from ${launcherUrl}`));\n document.head.appendChild(script);\n });\n };\n\n // Warm the full bundle in the background (download-only, not executed) so the\n // first open is quick. Runs at idle so it never competes with the launcher.\n const prefetchFullBundle = (): void => {\n const addPrefetch = () => {\n if (!isJsLoaded()) {\n const link = document.createElement(\"link\");\n link.rel = \"prefetch\";\n link.as = \"script\";\n link.href = jsUrl;\n document.head.appendChild(link);\n }\n\n // Also prefetch the markdown parsers chunk\n const markdownUrl = jsUrl.replace(/index\\.global\\.js($|\\?)/, \"markdown-parsers.js$1\");\n if (markdownUrl !== jsUrl) {\n const link2 = document.createElement(\"link\");\n link2.rel = \"prefetch\";\n link2.as = \"script\";\n link2.href = markdownUrl;\n document.head.appendChild(link2);\n }\n };\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(addPrefetch, { timeout: 4000 });\n } else {\n setTimeout(addPrefetch, 1200);\n }\n };\n\n // Merge top-level installer options into the widget config. Shared by the\n // eager init path and the deferred-launcher path.\n const buildWidgetInit = (): { target: string | HTMLElement; widgetConfig: any; hasApiConfig: boolean } => {\n const target = config.target || \"body\";\n const widgetConfig: any = { ...config.config };\n\n if (config.apiUrl && !widgetConfig.apiUrl) widgetConfig.apiUrl = config.apiUrl;\n if (config.clientToken && !widgetConfig.clientToken) widgetConfig.clientToken = config.clientToken;\n if (config.flowId && !widgetConfig.flowId) widgetConfig.flowId = config.flowId;\n if (config.agentId && !widgetConfig.agentId) widgetConfig.agentId = config.agentId;\n\n const hasApiConfig = !!(widgetConfig.apiUrl || widgetConfig.clientToken);\n return { target, widgetConfig, hasApiConfig };\n };\n\n // Initialize the full widget. When `openAfter` is true (the deferred-launcher\n // handoff), open the panel immediately via the public controller API so the\n // user's click on the critical launcher carries through.\n const initWidget = (openAfter = false): any => {\n if (!window.AgentWidget || !window.AgentWidget.initAgentWidget) {\n console.warn(\"AgentWidget not available. Make sure the script loaded successfully.\");\n return;\n }\n\n const { target, widgetConfig, hasApiConfig } = buildWidgetInit();\n\n // Only initialize if we have either apiUrl OR clientToken (or other config)\n if (!hasApiConfig && Object.keys(widgetConfig).length === 0) {\n return;\n }\n\n // Auto-apply markdown postprocessor if not explicitly set and available\n if (!widgetConfig.postprocessMessage && window.AgentWidget.markdownPostprocessor) {\n widgetConfig.postprocessMessage = ({ text }: { text: string }) =>\n window.AgentWidget.markdownPostprocessor(text);\n }\n\n try {\n const handle = window.AgentWidget.initAgentWidget({\n target,\n config: widgetConfig,\n // Explicitly disable shadow DOM for better CSS compatibility with host page\n useShadowDom: config.useShadowDom ?? false,\n windowKey: config.windowKey\n });\n\n // Handoff from the critical launcher: the user already clicked, so open\n // the panel via the existing public controller method.\n if (openAfter && handle && typeof handle.open === \"function\") {\n handle.open();\n }\n\n // Eager floating installs paint their launcher at load time too: emit the\n // same page-load \"appeared\" signal as the deferred path. The deferred\n // handoff (openAfter) already fired it at launcher mount, and non-floating\n // modes have no launcher, so guard on both.\n if (!openAfter && hasFloatingLauncher(widgetConfig)) {\n safeCall(config.onLauncherShown, { deferred: false });\n dispatchLifecycle(\"persona:launcher-shown\", { deferred: false });\n }\n\n // The full widget is initialized and its controller API is callable.\n safeCall(config.onChatReady, handle);\n dispatchLifecycle(\"persona:chat-ready\", handle);\n return handle;\n } catch (error) {\n fail(\"init\", error);\n }\n };\n\n // A persisted \"open\" state reopens the panel on reload with no click\n // (ui.ts:7513). The installer can't see that from config, so it reads the very\n // same storage key the widget writes. Mirrors normalizePersistStateConfig\n // (ui.ts:213): openState persistence defaults on, storage to sessionStorage,\n // key prefix to \"persona-\".\n const hasPersistedOpenState = (widgetConfig: any): boolean => {\n const persistState = widgetConfig.persistState;\n if (!persistState) return false; // persistence off → nothing to restore\n const asObject = typeof persistState === \"object\" ? persistState : null;\n if (asObject && asObject.persist?.openState === false) return false; // open-state persistence opted out\n const keyPrefix = (asObject && asObject.keyPrefix) || \"persona-\";\n const storageType = (asObject && asObject.storage) || \"session\";\n try {\n const storage = storageType === \"local\" ? window.localStorage : window.sessionStorage;\n return storage.getItem(`${keyPrefix}widget-open`) === \"true\";\n } catch {\n return false; // storage blocked (private mode) → the widget can't restore either\n }\n };\n\n // The deferred-launcher optimization only applies to the common floating case\n // that paints a collapsed launcher and waits for a click. Anything that starts\n // open or renders differently eager-loads the full bundle exactly as before: // including the two open triggers config alone can't express: a host\n // onStateLoaded hook that may request open, and a restored \"was open\" state.\n const shouldDeferPanel = (widgetConfig: any): boolean => {\n if (!launcherUrl) return false; // custom bundle URL override: can't derive launcher URL\n if (!hasFloatingLauncher(widgetConfig)) return false; // inline / docked / composer-bar\n const launcher = widgetConfig.launcher ?? {};\n if (launcher.autoExpand === true) return false; // starts open\n if (typeof widgetConfig.onStateLoaded === \"function\") return false; // hook may request open\n if (hasPersistedOpenState(widgetConfig)) return false; // restored \"was open\"\n return true;\n };\n\n // Render the real launcher from the tiny critical bundle; load + mount the\n // full widget on first click, then remove the critical launcher.\n const mountDeferredLauncher = (target: string | HTMLElement, widgetConfig: any): void => {\n let phase: \"idle\" | \"loading\" | \"done\" = \"idle\";\n let launcherHandle: { destroy: () => void } | undefined;\n\n const onOpen = () => {\n if (phase !== \"idle\") return; // already loading or handed off\n phase = \"loading\";\n loadJS()\n .then(() => {\n initWidget(true); // mount the full widget + open the panel\n launcherHandle?.destroy(); // remove the critical launcher (same component → invisible)\n phase = \"done\";\n })\n .catch((error) => {\n phase = \"idle\"; // allow the click to be retried\n console.error(\"Failed to load AgentWidget on open:\", error);\n safeCall(config.onError, { phase: \"bundle\", error });\n dispatchLifecycle(\"persona:error\", { phase: \"bundle\", error });\n });\n };\n\n const mounted = window.AgentWidgetLauncher.mount({ target, config: widgetConfig, onOpen });\n launcherHandle = mounted;\n\n // The real launcher is now painted at page-load time: emit the page-load\n // \"appeared\" signal (distinct from `onChatReady`, which waits for first open).\n safeCall(config.onLauncherShown, { deferred: true, element: mounted.element });\n dispatchLifecycle(\"persona:launcher-shown\", { deferred: true, element: mounted.element });\n\n // Warm the full bundle so the first open is quick.\n prefetchFullBundle();\n };\n\n // Main installation flow (called after hydration completes)\n const install = async () => {\n try {\n // Auto-init if we have config OR apiUrl OR clientToken\n const shouldAutoInit = autoInit && (\n config.config ||\n config.apiUrl ||\n config.clientToken\n );\n\n // Fast path: render the real launcher from the ~13 KB critical bundle and\n // defer the full widget until first open. Only for the common floating\n // case; everything else falls through to the eager path below.\n if (shouldAutoInit) {\n const { target, widgetConfig } = buildWidgetInit();\n if (shouldDeferPanel(widgetConfig)) {\n try {\n // CSS + launcher in parallel so the launcher paints correctly styled.\n await Promise.all([loadCSS(), loadLauncher()]);\n if (window.AgentWidgetLauncher && window.AgentWidgetLauncher.mount) {\n mountDeferredLauncher(target, widgetConfig);\n return;\n }\n } catch (error) {\n console.warn(\"Deferred launcher failed; falling back to eager load.\", error);\n }\n // Fall through to the eager path on any failure.\n }\n }\n\n // Eager path (unchanged behavior): load the full bundle, then init.\n try {\n await loadCSS();\n } catch (error) {\n return fail(\"css\", error);\n }\n try {\n await loadJS();\n } catch (error) {\n return fail(\"bundle\", error);\n }\n if (shouldAutoInit) {\n // Wait a tick to ensure AgentWidget is fully initialized\n setTimeout(() => initWidget(false), 0);\n }\n } catch (error) {\n // Safety net for anything unexpected before the eager loads above.\n fail(\"init\", error);\n }\n };\n\n // Start installation after hydration completes\n // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS\n waitForHydration(install);\n})();\n\n"],"mappings":"4YAAA,IAAAA,EAAA,IAgEC,UAAW,CACV,aAGA,GAAK,OAAe,2BAClB,OAED,OAAe,2BAA6B,GAqE7C,IAAMC,GA/DsB,IAAuC,CAEjE,IAAMC,EAAS,SAAS,cACxB,GAAI,CAACA,EAAQ,MAAO,CAAC,EAErB,IAAMD,EAAgD,CAAC,EAGjDE,EAAaD,EAAO,aAAa,aAAa,EACpD,GAAIC,EACF,GAAI,CAGF,IAAMC,EAAiBD,EAAW,QAAQ,cAAe,EAAE,EACrDE,EAAe,KAAK,MAAMD,CAAc,EAE9C,GAAIC,EAAa,OAAQ,CAEvB,GAAM,CAAE,UAAWC,EAAI,YAAaC,EAAI,UAAWC,EAAI,GAAGC,CAAW,EAAIJ,EACzE,OAAO,OAAOJ,EAAcQ,CAAU,CACxC,MAEER,EAAa,OAASI,CAE1B,OAASK,EAAG,CACV,QAAQ,MAAM,oCAAqCA,CAAC,CACtD,CAIF,IAAMC,EAAQT,EAAO,aAAa,oBAAoB,EAClDS,IACFV,EAAa,YAAcU,GAI7B,IAAMC,EAASV,EAAO,aAAa,cAAc,EAC7CU,IACFX,EAAa,OAASW,GAIxB,IAAMC,EAAUX,EAAO,aAAa,eAAe,EAC/CW,IACFZ,EAAa,QAAUY,GAIzB,IAAMC,EAASZ,EAAO,aAAa,cAAc,EAC7CY,IACFb,EAAa,OAASa,GAIxB,IAAMC,EAAoBb,EAAO,aAAa,oBAAoB,EACl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AAS1B,EAAO,CACd,OAAOF,EAAK,MAAOE,CAAK,CAC1B,CACA,GAAI,CACF,MAAM8B,EAAO,CACf,OAAS9B,EAAO,CACd,OAAOF,EAAK,SAAUE,CAAK,CAC7B,CACIsD,GAEF,WAAW,IAAMd,EAAW,EAAK,EAAG,CAAC,CAEzC,OAASxC,EAAO,CAEdF,EAAK,OAAQE,CAAK,CACpB,CACF,CAIwB,CAC1B,GAAG","names":["install_exports","scriptConfig","script","configJson","normalizedJson","parsedConfig","_a","_b","_c","safeConfig","e","token","flowId","agentId","apiUrl","previewQueryParam","installerSrc","config","safeCall","fn","arg","dispatchLifecycle","name","detail","fail","phase","error","hasFloatingLauncher","widgetConfig","launcher","value","version","cdn","autoInit","getInstallerBase","url","getCdnBase","derivedLauncherUrl","selfBase","packageName","basePath","host","cssUrl","jsUrl","launcherUrl","isCssLoaded","isJsLoaded","waitForHydration","callback","executed","execute","afterDom","loadCSS","resolve","reject","link","loadJS","isLauncherLoaded","loadLauncher","prefetchFullBundle","addPrefetch","markdownUrl","link2","buildWidgetInit","target","hasApiConfig","initWidget","openAfter","text","handle","hasPersistedOpenState","persistState","asObject","keyPrefix","storageType","shouldDeferPanel","mountDeferredLauncher","launcherHandle","onOpen","mounted","shouldAutoInit"]}
|
|
@@ -181,7 +181,7 @@ ${e}`:"")+(t.description?`
|
|
|
181
181
|
${t.description}`:"");return window.confirm(n)},Wm=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Hm=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Bm=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Lo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function pi(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Dm="agent_",Nm="flow_";function tp(t){return t.startsWith(Dm)?{kind:"agentId",agentId:t}:t.startsWith(Nm)?{kind:"flowId",flowId:t}:null}function np(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let c=tp(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[i];if(!p)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=tp(n);if(r)return r;let s=e?.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 ro=require("partial-json");nt();var sl="ask_user_question",Kr=8,er="data-persona-ask-sheet-for",Om="Other",Fm="Other\u2026",sp="Type your own answer here",ip="Send",_m="Next",$m="Back",zm="Submit all",Um="Skip",jm=3,il="data-ask-current-index",al="data-ask-question-count",ap="data-ask-answers",ll="data-ask-grouped",lp="data-ask-layout",qm=t=>t.layout==="pills"?"pills":"rows",Vm=t=>t.getAttribute(lp)==="pills"?"pills":"rows",rp=!1,cp=t=>t.replace(/["\\]/g,"\\$&"),Po=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===sl,cl=t=>t?.features?.askUserQuestion??{},tr=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,ro.parse)(r,ro.STR|ro.OBJ|ro.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Kr&&!rp&&(rp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Kr}.`)),e.slice(0,Kr)},Km=t=>Gr(t)[0]??null,Gm=(t,e)=>Gr(t)[e]??null,Qm=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},dp=(t,e,n)=>{if(t!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Xm=(t,e,n,o)=>{let s=h("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(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let i=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=h("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=dp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Jm=t=>{let n=h("span",t==="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},Ym=(t,e,n,o)=>{let s=h("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 i=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<jm;d++)s.appendChild(Jm(o));return s}if(p.forEach((d,u)=>{s.appendChild(Xm(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Om:Fm;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let y=h("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??sp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??d),y.appendChild(g),u.appendChild(y);let m=dp(o,i,p.length);m&&u.appendChild(m),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??d,s.appendChild(u)}}return s},pp=(t,e)=>{let o=h("div",e==="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=t.freeTextPlaceholder??sp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ip,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Zm=t=>{let e=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ip,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},eh=(t,e,n)=>{let o=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??$m,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=h("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??Um,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??zm:n.nextLabel??_m,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Io=t=>{let e=t.getAttribute(ap);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},up=(t,e)=>{t.setAttribute(ap,JSON.stringify(e))},fn=t=>{let e=Number(t.getAttribute(il)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},th=(t,e)=>{t.setAttribute(il,String(Math.max(0,Math.floor(e))))},nr=t=>{let e=Number(t.getAttribute(al)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=t=>t.getAttribute(ll)==="true",nh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},oh=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},ui=(t,e)=>{let{payload:n}=tr(e),o=Gr(n),r=Io(t),s={},i=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(i.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),i.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(s[c]=r[p]))}),s},gp=t=>{let e=Io(t),n=fn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},fp=t=>{if(!so(t))return;let e=Io(t),n=fn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=t.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},dl=(t,e,n)=>{let o=cl(n),r=Vm(t),{payload:s,complete:i}=tr(e),l=so(t),p=fn(t),c=nr(t),d=l?Gm(s,p):Km(s),u=!!d?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${p+1}/${c}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let E=typeof d?.question=="string"?d.question:"";m.textContent=E,m.classList.toggle("persona-ask-question-skeleton",!E&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=Ym(d,o,i,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(pp(o,r))}let D=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!D?t.appendChild(Zm(o)):(!u||l)&&D&&D.remove(),t.setAttribute("data-multi-select",u?"true":"false");let B=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=eh(p,c,o);B?B.replaceWith(E):t.appendChild(E)}else B&&B.remove();gp(t),fp(t)},rh=(t,e,n)=>{let o=cl(e),r=qm(o),s=t.toolCall.id,i=Gr(n),l=Math.max(1,i.length),p=l>1,c=nh(t,i),d=p?oh(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(er,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(al,String(l)),u.setAttribute(il,String(d)),u.setAttribute(ll,p?"true":"false"),u.setAttribute(lp,r),up(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Qm(u,o);let y=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",y.appendChild(g);let m=h("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",y.appendChild(m),u.appendChild(y);let D=h("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 D.setAttribute("data-ask-pill-list","true"),D.setAttribute("role","group"),u.appendChild(D),r!=="rows"&&u.appendChild(pp(o,r)),dl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sh=(t,e,n)=>{let{payload:o}=tr(e),r=Math.max(1,Gr(o).length);r>nr(t)&&(t.setAttribute(al,String(r)),r>1&&!so(t)&&t.setAttribute(ll,"true")),dl(t,e,n)};var gi=(t,e,n)=>{if(!n||!Po(t)||cl(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${er}]`).forEach(c=>{c.getAttribute(er)!==r&&c.remove()});let i=n.querySelector(`[${er}="${cp(r)}"]`);if(i){sh(i,t,e);return}let{payload:l}=tr(t),p=rh(t,e,l);n.appendChild(p)},or=(t,e)=>{if(!t)return;let n=e?`[${er}="${cp(e)}"]`:`[${er}]`;t.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)})},pl=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),io=(t,e)=>{let n=Io(t),o=fn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,up(t,n),gp(t),fp(t)},fi=(t,e,n,o)=>{let r=nr(t),s=Math.max(0,Math.min(r-1,o));th(t,s),dl(t,e,n)};var _n="suggest_replies";var ih={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},mp={name:_n,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ih,origin:"sdk",annotations:{readOnlyHint:!0}},ul=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gl=t=>t.variant==="tool"&&t.toolCall?.name===_n,ah=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},hp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!gl(n))continue;let o=ah(n.toolCall?.args);return o.length>0?o:null}return null},bp=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var lh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Kr,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},ch={name:sl,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:lh,origin:"sdk",annotations:{readOnlyHint:!0}},mi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(ch),bp(t)&&e.push(mp),e};var rr=require("partial-json"),yp=t=>t.replace(/\\n/g,`
|
|
182
182
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},dh=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},vp=t=>t.status==="complete"?dh(t):t.status==="pending"?"Waiting":"",ph=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.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 xp=t=>t.status==="complete"?ph(t):"Using tool...",hi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Xr=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return hi(e)},bi=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return hi(e)},fl=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Xr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},yi=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Qr(o,n.slice(s,i.index),[]),i[1]!==void 0?Qr(o,i[1],["bold"]):i[2]!==void 0?Qr(o,i[2],["italic"]):i[3]!==void 0&&Qr(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Qr(o,n.slice(s),[]),o},Qr=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},uh=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
183
183
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
184
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Jr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},wp=()=>{let t=uh();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Ap=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,rr.parse)(n,rr.STR|rr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?yp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=yp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Sp=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Mp="4.11.1";var Yr=Mp;var fh="https://api.runtype.com/v1/dispatch",vi="https://api.runtype.com";function mh(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var ml=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function hh(t){switch(t){case"json":return Ap;case"regex-json":return wp;case"xml":return Sp;default:return Cp}}var Tp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bh(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Tp(n);if(!Tp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=Jr(t);return Jr(e)!==null&&i===null?e:t}var Zr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??fh,this.headers={"Content-Type":"application/json","X-Persona-Version":Yr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??hh(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new di(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=np(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(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||vi}/v1/client/${e}`}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let i=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(i.sessionId),{sessionId:i.sessionId,expiresAt:new Date(i.expiresAt),flow:i.flow,config:{welcomeMessage:i.config.welcomeMessage,placeholder:i.config.placeholder,theme:i.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$/,"")||vi}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let i=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(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,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:e,comment:n})}async submitNPSFeedback(e,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:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,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 c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,i={sessionId:o.sessionId,messages:e.messages.filter(ml).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...i,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(d),signal:e.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.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(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||vi}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),i=s?Zd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let y=0;;y++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&y===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||vi}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(p.sessionId=i),r&&i){let c=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,y=>{let g={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,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(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(ml).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);return i&&(r.context=i),r}async buildPayload(e){let n=e.slice().filter(ml).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),i=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=k=>{let j=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,v=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,T=k.tools?k.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...k,reasoning:j,toolCall:v,tools:T}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let j=Array.isArray(k.contentParts)&&k.contentParts.length>0,v=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||j||v||!!k.stopReason},g=k=>{y(k)&&n({type:"message",message:u(k)})},m=null,C=null,D={current:null},B={current:null},E=null,A="",W=new Map,z=new Map,G=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},P=k=>{if(k==null)return null;try{return String(k)}catch{return null}},I=k=>P(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),Y=k=>P(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),de=o,ue=!1,pe=()=>{if(m)return m;let k,j="",v=E;return!ue&&de?(k=de,ue=!0,j=r??""):de&&v?k=`${de}_${v}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:k,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},g(m),m},ee=(k,j)=>{N.lastId=j,k&&N.byStep.set(k,j)},oe=(k,j)=>{let v=k.reasoningId??k.id,T=I(k);if(v){let _=String(v);return ee(T,_),_}if(T){let _=N.byStep.get(T);if(_)return N.lastId=_,_}if(N.lastId&&!j)return N.lastId;if(!j)return null;let R=`reason-${d()}`;return ee(T,R),R},V=k=>{let j=w.get(k);if(j)return j;let v={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,v),g(v),v},ae=(k,j)=>{L.lastId=j,k&&L.byCall.set(k,j)},ne=new Set,me=new Map,be=new Set,fe=new Map,Te=k=>{if(!k)return!1;let j=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Se=(k,j)=>{let v=k.toolId??k.id,T=Y(k);if(v){let _=String(v);return ae(T,_),_}if(T){let _=L.byCall.get(T);if(_)return L.lastId=_,_}if(L.lastId&&!j)return L.lastId;if(!j)return null;let R=`tool-${d()}`;return ae(T,R),R},Fe=k=>{let j=O.get(k);if(j)return j;let v={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:k,status:"pending"}};return O.set(k,v),g(v),v},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let j=Number(k);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let v=Date.parse(k);if(!Number.isNaN(v))return v}return Date.now()},Ve=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Je=new Map,Ne=new Map,Pe=new Map,Ye=(k,j,v)=>{let T=Pe.get(k);T||(T=[],Pe.set(k,T));let R=0,_=T.length;for(;R<_;){let $=R+_>>>1;T[$].seq<j?R=$+1:_=$}T[R]?.seq===j?T[R]={seq:j,text:v}:T.splice(R,0,{seq:j,text:v});let Q="";for(let $=0;$<T.length;$++)Q+=T[$].text;return Q},ln=(k,j)=>{let v=Ve(j),T=Ne.get(k.id),R=bh(T,v);k.rawContent=R;let _=Je.get(k.id),Q=Ie=>{let it=k.content??"";Ie.trim()!==""&&(it.trim().length===0||Ie.startsWith(it)||Ie.trimStart().startsWith(it.trim()))&&(k.content=Ie)},$=()=>{if(_){let Ie=_.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}Je.delete(k.id),Ne.delete(k.id),k.streaming=!1,g(k)};if(!_){Q(v),$();return}let K=Jr(R);if(K!==null&&K.trim()!==""){Q(K),$();return}let ce=Ie=>{let it=typeof Ie=="string"?Ie:Ie?.text??null;if(it!==null&&it.trim()!=="")return it;let X=_.getExtractedText();return X!==null&&X.trim()!==""?X:v},Ke;try{Ke=_.processChunk(R)}catch{Q(v),$();return}if(Ke instanceof Promise){Ke.then(Ie=>{Q(ce(Ie)),$()}).catch(()=>{Q(v),$()});return}Q(ce(Ke)),$()},kt=null,vt=(k,j,v,T)=>{k.rawContent=j,Je.has(k.id)||Je.set(k.id,this.createStreamParser());let R=Je.get(k.id),_=j.trim().startsWith("{")||j.trim().startsWith("[");if(_&&Ne.set(k.id,j),R.__isPlainTextParser===!0){k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k);return}let $=R.processChunk(j);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(k.content=ce,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(k.content=K,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}},Oe=(k,j)=>{let v=j??k.content;if(v==null||v===""){k.streaming=!1,g(k);return}let R=Ne.get(k.id)??Ve(v);k.rawContent=R;let _=Je.get(k.id),Q=null,$=!1;if(_&&(Q=_.getExtractedText(),Q===null&&(Q=Jr(R)),Q===null)){let K=_.processChunk(R);K instanceof Promise?($=!0,K.then(ce=>{let Ke=typeof ce=="string"?ce:ce?.text??null;Ke!==null&&(k.content=Ke,k.streaming=!1,Je.delete(k.id),Ne.delete(k.id),g(k))}).catch(()=>{})):Q=typeof K=="string"?K:K?.text??null}if(!$){Q!==null&&Q.trim()!==""?k.content=Q:Ne.has(k.id)||(k.content=Ve(v));let K=Je.get(k.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),Je.delete(k.id)}Ne.delete(k.id),k.streaming=!1,g(k)}},Ce=(k,j,v)=>{let T=z.get(k);if(T)return T;let R={id:`nested-${j}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return z.set(k,R),g(R),R},Qe=[],Re,ye=new Map,ge=0,we="agent",xt=!1,Ae=null,he=null,hn=new Map,te=this.config.iterationDisplay??"separate";for(Re=()=>{for(let k=0;k<Qe.length;k++){let j=Qe[k].payloadType,v=Qe[k].payload;if(!xt&&we!=="flow"&&typeof v.stepType=="string"&&(we="flow"),j==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R),Ce(T,R,"reasoning");continue}let _=oe(v,!0)??`reason-${d()}`,Q=V(_);Q.reasoning=Q.reasoning??{id:_,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??ke(v.startedAt??v.timestamp),Q.reasoning.completedAt=void 0,Q.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),Q.streaming=!0,Q.reasoning.status="streaming",g(Q)}else if(j==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let $=z.get(T),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=V(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??ke(v.startedAt??v.timestamp);let Q=v.reasoningText??v.text??v.delta??"";if(Q&&v.hidden!==!0){let $=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if($!==void 0){let K=Ye(R,$,String(Q));_.reasoning.chunks=[K]}else _.reasoning.chunks.push(String(Q))}if(_.reasoning.status=v.done?"complete":"streaming",v.done){_.reasoning.completedAt=ke(v.completedAt??v.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",g(_)}else if(j==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let K=z.get(T);if(K.reasoning){let ce=typeof v.text=="string"?v.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}W.delete(T),z.delete(T);continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=typeof v.text=="string"?v.text:"";!w.get(R)&&(_||v.scope==="loop")&&V(R);let Q=w.get(R);if(Q?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),_&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(_),Q.reasoning.status="complete",Q.reasoning.completedAt=ke(v.completedAt??v.timestamp);let K=Q.reasoning.startedAt??Date.now();Q.reasoning.durationMs=Math.max(0,(Q.reasoning.completedAt??Date.now())-K),Q.streaming=!1,g(Q)}let $=I(v);$&&N.byStep.delete($)}else if(j==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof v.iteration=="number"&&(ge=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Se(v,!0)??`tool-${d()}`,R=v.toolName??v.name;if(Te(R)){ne.add(T);continue}ae(Y(v),T);let _=Fe(T),Q=_.toolCall??{id:T,status:"pending"};Q.name=R??Q.name,Q.status="running",v.parameters!==void 0?Q.args=v.parameters:v.args!==void 0&&(Q.args=v.args),Q.startedAt=Q.startedAt??ke(v.startedAt??v.timestamp),Q.completedAt=void 0,Q.durationMs=void 0,_.toolCall=Q,_.streaming=!0,v.executionId&&(_.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(_)}else if(j==="tool_output_delta"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T))continue;let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.startedAt=_.startedAt??ke(v.startedAt??v.timestamp);let Q=v.text??v.delta??v.message??"";Q&&(_.chunks=_.chunks??[],_.chunks.push(String(Q))),_.status="running",R.toolCall=_,R.streaming=!0;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R)}else if(j==="tool_complete"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T)){ne.delete(T);continue}let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.status="complete",v.result!==void 0&&(_.result=v.result),typeof v.duration=="number"&&(_.duration=v.duration),_.completedAt=ke(v.completedAt??v.timestamp);let Q=v.duration??v.executionTime;if(typeof Q=="number")_.durationMs=Q;else{let ce=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ce)}R.toolCall=_,R.streaming=!1;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R);let K=Y(v);K&&L.byCall.delete(K)}else if(j==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,R=T??v.toolId??`local-${d()}`,_=Fe(R),Q=v.toolName,$=v.origin==="webmcp"&&!Zo(Q)?`webmcp:${Q}`:Q,K=Zo($),ce=_.toolCall??{id:R,status:"pending"};ce.name=$,ce.args=v.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??ke(v.startedAt??v.timestamp??v.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,_.toolCall=ce,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:v.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(_)}else if(j==="text_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R);continue}let _=m;_&&(we==="flow"?(Oe(_),kt=_):(_.streaming=!1,g(_)),m=null),E=typeof v.id=="string"?v.id:E,A=""}else if(j==="text_delta"){let T=typeof v.id=="string"?v.id:null,R=T?W.get(T):void 0;if(T&&R){let Q=typeof v.delta=="string"?v.delta:"",$=(G.get(T)??"")+Q;if(G.set(T,$),$.trim()==="")continue;let K=Ce(T,R);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:R},vt(K,$,Q,void 0);continue}if(E=typeof v.id=="string"?v.id:E,we==="flow"){let Q=typeof v.delta=="string"?v.delta:"";if(A+=Q,A.trim()==="")continue;let $=pe();$.agentMetadata={executionId:v.executionId,iteration:v.iteration},vt($,A,Q,void 0),C=$;continue}let _=pe();_.content+=v.delta??"",_.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ae??void 0,agentName:he?.agentName},C=_,g(_)}else if(j==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)){let _=z.get(T);_&&Oe(_),W.delete(T),G.delete(T),z.delete(T);continue}let R=m;R&&(we==="flow"?(Oe(R),kt=R):((R.content??"")===""&&typeof v.text=="string"&&(R.content=v.text),R.streaming=!1,g(R)),m=null),E=null,A=""}else if(j==="step_complete"){let T=v.stepType,R=v.executionType;if(T==="tool"||R==="context")continue;if(v.success===!1){let _=v.error,Q=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Q)});let $=m;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let _=kt;kt=null;let Q=v.stopReason,$=v.result?.response;if(_)Q&&(_.stopReason=Q),$!=null?ln(_,$):_.streaming!==!1&&(Je.delete(_.id),Ne.delete(_.id),_.streaming=!1,g(_));else{let K=$!=null&&$!=="";if(K||Q){let ce=pe();Q&&(ce.stopReason=Q),K?Oe(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(j==="execution_start")we=v.kind==="flow"?"flow":"agent",xt=!0,we==="agent"&&(he={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ke(v.startedAt)});else if(j==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:ge;if(T!==ge){if(he&&(he.currentIteration=T),te==="separate"&&T>1){let R=m;R&&(R.streaming=!1,g(R),hn.set(T-1,R),m=null)}ge=T}Ae=typeof v.id=="string"?v.id:null,C=null}else if(j==="tool_input_delta"){let T=v.toolCallId??L.lastId;if(T){let R=O.get(T);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(v.delta??""),g(R))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let T=v.stopReason,R=m??C;if(T&&R!==null){let _=v.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=T,g(R))}Ae===v.id&&(Ae=null)}else if(j==="media_start"){let T=String(v.id);ye.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(j==="media_delta"){let T=ye.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(j==="media_complete"){let T=String(v.id),R=ye.get(T);ye.delete(T);let _=(typeof v.mediaType=="string"?v.mediaType:void 0)??R?.mediaType??"application/octet-stream",Q=typeof v.data=="string"?v.data:void 0,$=typeof v.url=="string"?v.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(Q)K={type:"media",data:Q,mediaType:_};else if($){let it=_.toLowerCase();K={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let ce=v.toolCallId??R?.toolCallId,Ke=K?[K]:[],Ie=[];for(let it of Ke){if(!it||typeof it!="object")continue;let X=it,Ue=typeof X.type=="string"?X.type:void 0,Ee=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",De=null,We="";if(Ue==="media"){let Ze=typeof X.data=="string"?X.data:void 0;if(!Ze)continue;We=Ee.length>0?Ee:"application/octet-stream",De=`data:${We};base64,${Ze}`}else if(Ue==="image-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else if(Ue==="file-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else continue;if(De)if(Ue==="image-url"||We.startsWith("image/"))Ie.push({type:"image",image:De,...We.includes("/")?{mimeType:We}:{}});else if(We.startsWith("audio/"))Ie.push({type:"audio",audio:De,mimeType:We});else if(We.startsWith("video/"))Ie.push({type:"video",video:De,mimeType:We});else{let Ze=We||"application/octet-stream";Ie.push({type:"file",data:De,mimeType:Ze,filename:mh(Ze)})}}if(Ie.length>0){let it=d(),X=ce,Ee={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ge}};g(Ee);let De=m;De&&(De.streaming=!1,g(De)),m=null,D.current=null}}else if(j==="execution_complete"){let T=v.kind??we;T==="agent"&&he&&(he.status=v.success?"complete":"error",he.completedAt=ke(v.completedAt),he.stopReason=v.stopReason);let R=m;R&&(T==="flow"&&R.streaming!==!1?Oe(R):(R.streaming=!1,g(R)),m=null),E=null,A="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(j!=="ping"){if(j==="approval_start"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="approval_complete"){let T=v.approvalId;if(T){let _={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:v.decision??"approved",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(_)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let T=v.artifactType,R=String(v.id),_=typeof v.title=="string"?v.title:void 0,Q=v.file,$;Q&&typeof Q=="object"&&!Array.isArray(Q)&&typeof Q.path=="string"&&typeof Q.mimeType=="string"&&($={path:Q.path,mimeType:Q.mimeType,...typeof Q.language=="string"?{language:Q.language}:{}}),n({type:"artifact_start",id:R,artifactType:T,title:_,component:typeof v.component=="string"?v.component:void 0,...$?{file:$}:{}});let K=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(fe.set(R,{markdown:"",title:_,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let ce=Lo(this.config.features?.artifacts,T),Ke=typeof v.component=="string"?v.component:void 0,Ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:pi(ce,{artifactId:R,title:_,artifactType:T,status:"streaming",...$?{file:$}:{},...Ke?{component:Ke}:{}})};me.set(R,Ie),g(Ie)}}else if(j==="artifact_delta"){let T=String(v.id),R=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:R});let _=fe.get(T);_&&(_.markdown+=R)}else if(j==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let R=fe.get(String(v.id));R&&(R.props={...R.props??{},...T})}else if(j==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let R=me.get(T);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let Q=fe.get(T);Q?.markdown&&(_.props.markdown=Q.markdown),Q?.file&&(_.props.file=Q.file),_.component==="PersonaArtifactInline"&&Q?.props&&Object.keys(Q.props).length>0&&(_.props.componentProps=Q.props)}R.rawContent=JSON.stringify(_)}catch{}fe.delete(T),g(R),me.delete(T)}}}else if(j==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let R=String(T.id??`msg-${d()}`),_=T.role,$={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:d()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&be.add(ce)}catch{}m=null,D.current=null,Je.delete(R),Ne.delete(R)}else if(j==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(j==="dispatch_error"){let R=v.message??v.error;R!=null&&R!==""&&(T=new Error(String(R)))}else{let R=v.error;typeof R=="string"&&R!==""?T=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(T=new Error(String(R.message??R)))}if(T){n({type:"error",error:T});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:k,value:j}=await s.read();if(k)break;l+=i.decode(j,{stream:!0});let v=l.split(`
|
|
184
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Jr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},wp=()=>{let t=uh();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Ap=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,rr.parse)(n,rr.STR|rr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?yp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=yp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Sp=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Mp="4.12.0";var Yr=Mp;var fh="https://api.runtype.com/v1/dispatch",vi="https://api.runtype.com";function mh(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var ml=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function hh(t){switch(t){case"json":return Ap;case"regex-json":return wp;case"xml":return Sp;default:return Cp}}var Tp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bh(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Tp(n);if(!Tp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=Jr(t);return Jr(e)!==null&&i===null?e:t}var Zr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??fh,this.headers={"Content-Type":"application/json","X-Persona-Version":Yr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??hh(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new di(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=np(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(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||vi}/v1/client/${e}`}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 e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let i=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(i.sessionId),{sessionId:i.sessionId,expiresAt:new Date(i.expiresAt),flow:i.flow,config:{welcomeMessage:i.config.welcomeMessage,placeholder:i.config.placeholder,theme:i.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$/,"")||vi}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let i=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(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,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:e,comment:n})}async submitNPSFeedback(e,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:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,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 c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,i={sessionId:o.sessionId,messages:e.messages.filter(ml).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...i,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(d),signal:e.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.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(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||vi}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),i=s?Zd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let y=0;;y++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&y===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||vi}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(p.sessionId=i),r&&i){let c=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,y=>{let g={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,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(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(ml).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);return i&&(r.context=i),r}async buildPayload(e){let n=e.slice().filter(ml).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),i=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=k=>{let j=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,v=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,T=k.tools?k.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...k,reasoning:j,toolCall:v,tools:T}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let j=Array.isArray(k.contentParts)&&k.contentParts.length>0,v=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||j||v||!!k.stopReason},g=k=>{y(k)&&n({type:"message",message:u(k)})},m=null,C=null,D={current:null},B={current:null},E=null,A="",W=new Map,z=new Map,G=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},P=k=>{if(k==null)return null;try{return String(k)}catch{return null}},I=k=>P(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),Y=k=>P(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),de=o,ue=!1,pe=()=>{if(m)return m;let k,j="",v=E;return!ue&&de?(k=de,ue=!0,j=r??""):de&&v?k=`${de}_${v}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:k,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},g(m),m},ee=(k,j)=>{N.lastId=j,k&&N.byStep.set(k,j)},oe=(k,j)=>{let v=k.reasoningId??k.id,T=I(k);if(v){let _=String(v);return ee(T,_),_}if(T){let _=N.byStep.get(T);if(_)return N.lastId=_,_}if(N.lastId&&!j)return N.lastId;if(!j)return null;let R=`reason-${d()}`;return ee(T,R),R},V=k=>{let j=w.get(k);if(j)return j;let v={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,v),g(v),v},ae=(k,j)=>{L.lastId=j,k&&L.byCall.set(k,j)},ne=new Set,me=new Map,be=new Set,fe=new Map,Te=k=>{if(!k)return!1;let j=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Se=(k,j)=>{let v=k.toolId??k.id,T=Y(k);if(v){let _=String(v);return ae(T,_),_}if(T){let _=L.byCall.get(T);if(_)return L.lastId=_,_}if(L.lastId&&!j)return L.lastId;if(!j)return null;let R=`tool-${d()}`;return ae(T,R),R},Fe=k=>{let j=O.get(k);if(j)return j;let v={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:k,status:"pending"}};return O.set(k,v),g(v),v},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let j=Number(k);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let v=Date.parse(k);if(!Number.isNaN(v))return v}return Date.now()},Ve=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Je=new Map,Ne=new Map,Pe=new Map,Ye=(k,j,v)=>{let T=Pe.get(k);T||(T=[],Pe.set(k,T));let R=0,_=T.length;for(;R<_;){let $=R+_>>>1;T[$].seq<j?R=$+1:_=$}T[R]?.seq===j?T[R]={seq:j,text:v}:T.splice(R,0,{seq:j,text:v});let Q="";for(let $=0;$<T.length;$++)Q+=T[$].text;return Q},ln=(k,j)=>{let v=Ve(j),T=Ne.get(k.id),R=bh(T,v);k.rawContent=R;let _=Je.get(k.id),Q=Ie=>{let it=k.content??"";Ie.trim()!==""&&(it.trim().length===0||Ie.startsWith(it)||Ie.trimStart().startsWith(it.trim()))&&(k.content=Ie)},$=()=>{if(_){let Ie=_.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}Je.delete(k.id),Ne.delete(k.id),k.streaming=!1,g(k)};if(!_){Q(v),$();return}let K=Jr(R);if(K!==null&&K.trim()!==""){Q(K),$();return}let ce=Ie=>{let it=typeof Ie=="string"?Ie:Ie?.text??null;if(it!==null&&it.trim()!=="")return it;let X=_.getExtractedText();return X!==null&&X.trim()!==""?X:v},Ke;try{Ke=_.processChunk(R)}catch{Q(v),$();return}if(Ke instanceof Promise){Ke.then(Ie=>{Q(ce(Ie)),$()}).catch(()=>{Q(v),$()});return}Q(ce(Ke)),$()},kt=null,vt=(k,j,v,T)=>{k.rawContent=j,Je.has(k.id)||Je.set(k.id,this.createStreamParser());let R=Je.get(k.id),_=j.trim().startsWith("{")||j.trim().startsWith("[");if(_&&Ne.set(k.id,j),R.__isPlainTextParser===!0){k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k);return}let $=R.processChunk(j);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(k.content=ce,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(k.content=K,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}},Oe=(k,j)=>{let v=j??k.content;if(v==null||v===""){k.streaming=!1,g(k);return}let R=Ne.get(k.id)??Ve(v);k.rawContent=R;let _=Je.get(k.id),Q=null,$=!1;if(_&&(Q=_.getExtractedText(),Q===null&&(Q=Jr(R)),Q===null)){let K=_.processChunk(R);K instanceof Promise?($=!0,K.then(ce=>{let Ke=typeof ce=="string"?ce:ce?.text??null;Ke!==null&&(k.content=Ke,k.streaming=!1,Je.delete(k.id),Ne.delete(k.id),g(k))}).catch(()=>{})):Q=typeof K=="string"?K:K?.text??null}if(!$){Q!==null&&Q.trim()!==""?k.content=Q:Ne.has(k.id)||(k.content=Ve(v));let K=Je.get(k.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),Je.delete(k.id)}Ne.delete(k.id),k.streaming=!1,g(k)}},Ce=(k,j,v)=>{let T=z.get(k);if(T)return T;let R={id:`nested-${j}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return z.set(k,R),g(R),R},Qe=[],Re,ye=new Map,ge=0,we="agent",xt=!1,Ae=null,he=null,hn=new Map,te=this.config.iterationDisplay??"separate";for(Re=()=>{for(let k=0;k<Qe.length;k++){let j=Qe[k].payloadType,v=Qe[k].payload;if(!xt&&we!=="flow"&&typeof v.stepType=="string"&&(we="flow"),j==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R),Ce(T,R,"reasoning");continue}let _=oe(v,!0)??`reason-${d()}`,Q=V(_);Q.reasoning=Q.reasoning??{id:_,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??ke(v.startedAt??v.timestamp),Q.reasoning.completedAt=void 0,Q.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),Q.streaming=!0,Q.reasoning.status="streaming",g(Q)}else if(j==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let $=z.get(T),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=V(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??ke(v.startedAt??v.timestamp);let Q=v.reasoningText??v.text??v.delta??"";if(Q&&v.hidden!==!0){let $=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if($!==void 0){let K=Ye(R,$,String(Q));_.reasoning.chunks=[K]}else _.reasoning.chunks.push(String(Q))}if(_.reasoning.status=v.done?"complete":"streaming",v.done){_.reasoning.completedAt=ke(v.completedAt??v.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",g(_)}else if(j==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let K=z.get(T);if(K.reasoning){let ce=typeof v.text=="string"?v.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}W.delete(T),z.delete(T);continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=typeof v.text=="string"?v.text:"";!w.get(R)&&(_||v.scope==="loop")&&V(R);let Q=w.get(R);if(Q?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),_&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(_),Q.reasoning.status="complete",Q.reasoning.completedAt=ke(v.completedAt??v.timestamp);let K=Q.reasoning.startedAt??Date.now();Q.reasoning.durationMs=Math.max(0,(Q.reasoning.completedAt??Date.now())-K),Q.streaming=!1,g(Q)}let $=I(v);$&&N.byStep.delete($)}else if(j==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof v.iteration=="number"&&(ge=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Se(v,!0)??`tool-${d()}`,R=v.toolName??v.name;if(Te(R)){ne.add(T);continue}ae(Y(v),T);let _=Fe(T),Q=_.toolCall??{id:T,status:"pending"};Q.name=R??Q.name,Q.status="running",v.parameters!==void 0?Q.args=v.parameters:v.args!==void 0&&(Q.args=v.args),Q.startedAt=Q.startedAt??ke(v.startedAt??v.timestamp),Q.completedAt=void 0,Q.durationMs=void 0,_.toolCall=Q,_.streaming=!0,v.executionId&&(_.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(_)}else if(j==="tool_output_delta"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T))continue;let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.startedAt=_.startedAt??ke(v.startedAt??v.timestamp);let Q=v.text??v.delta??v.message??"";Q&&(_.chunks=_.chunks??[],_.chunks.push(String(Q))),_.status="running",R.toolCall=_,R.streaming=!0;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R)}else if(j==="tool_complete"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T)){ne.delete(T);continue}let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.status="complete",v.result!==void 0&&(_.result=v.result),typeof v.duration=="number"&&(_.duration=v.duration),_.completedAt=ke(v.completedAt??v.timestamp);let Q=v.duration??v.executionTime;if(typeof Q=="number")_.durationMs=Q;else{let ce=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ce)}R.toolCall=_,R.streaming=!1;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R);let K=Y(v);K&&L.byCall.delete(K)}else if(j==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,R=T??v.toolId??`local-${d()}`,_=Fe(R),Q=v.toolName,$=v.origin==="webmcp"&&!Zo(Q)?`webmcp:${Q}`:Q,K=Zo($),ce=_.toolCall??{id:R,status:"pending"};ce.name=$,ce.args=v.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??ke(v.startedAt??v.timestamp??v.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,_.toolCall=ce,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:v.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(_)}else if(j==="text_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R);continue}let _=m;_&&(we==="flow"?(Oe(_),kt=_):(_.streaming=!1,g(_)),m=null),E=typeof v.id=="string"?v.id:E,A=""}else if(j==="text_delta"){let T=typeof v.id=="string"?v.id:null,R=T?W.get(T):void 0;if(T&&R){let Q=typeof v.delta=="string"?v.delta:"",$=(G.get(T)??"")+Q;if(G.set(T,$),$.trim()==="")continue;let K=Ce(T,R);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:R},vt(K,$,Q,void 0);continue}if(E=typeof v.id=="string"?v.id:E,we==="flow"){let Q=typeof v.delta=="string"?v.delta:"";if(A+=Q,A.trim()==="")continue;let $=pe();$.agentMetadata={executionId:v.executionId,iteration:v.iteration},vt($,A,Q,void 0),C=$;continue}let _=pe();_.content+=v.delta??"",_.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ae??void 0,agentName:he?.agentName},C=_,g(_)}else if(j==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)){let _=z.get(T);_&&Oe(_),W.delete(T),G.delete(T),z.delete(T);continue}let R=m;R&&(we==="flow"?(Oe(R),kt=R):((R.content??"")===""&&typeof v.text=="string"&&(R.content=v.text),R.streaming=!1,g(R)),m=null),E=null,A=""}else if(j==="step_complete"){let T=v.stepType,R=v.executionType;if(T==="tool"||R==="context")continue;if(v.success===!1){let _=v.error,Q=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Q)});let $=m;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let _=kt;kt=null;let Q=v.stopReason,$=v.result?.response;if(_)Q&&(_.stopReason=Q),$!=null?ln(_,$):_.streaming!==!1&&(Je.delete(_.id),Ne.delete(_.id),_.streaming=!1,g(_));else{let K=$!=null&&$!=="";if(K||Q){let ce=pe();Q&&(ce.stopReason=Q),K?Oe(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(j==="execution_start")we=v.kind==="flow"?"flow":"agent",xt=!0,we==="agent"&&(he={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ke(v.startedAt)});else if(j==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:ge;if(T!==ge){if(he&&(he.currentIteration=T),te==="separate"&&T>1){let R=m;R&&(R.streaming=!1,g(R),hn.set(T-1,R),m=null)}ge=T}Ae=typeof v.id=="string"?v.id:null,C=null}else if(j==="tool_input_delta"){let T=v.toolCallId??L.lastId;if(T){let R=O.get(T);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(v.delta??""),g(R))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let T=v.stopReason,R=m??C;if(T&&R!==null){let _=v.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=T,g(R))}Ae===v.id&&(Ae=null)}else if(j==="media_start"){let T=String(v.id);ye.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(j==="media_delta"){let T=ye.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(j==="media_complete"){let T=String(v.id),R=ye.get(T);ye.delete(T);let _=(typeof v.mediaType=="string"?v.mediaType:void 0)??R?.mediaType??"application/octet-stream",Q=typeof v.data=="string"?v.data:void 0,$=typeof v.url=="string"?v.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(Q)K={type:"media",data:Q,mediaType:_};else if($){let it=_.toLowerCase();K={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let ce=v.toolCallId??R?.toolCallId,Ke=K?[K]:[],Ie=[];for(let it of Ke){if(!it||typeof it!="object")continue;let X=it,Ue=typeof X.type=="string"?X.type:void 0,Ee=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",De=null,We="";if(Ue==="media"){let Ze=typeof X.data=="string"?X.data:void 0;if(!Ze)continue;We=Ee.length>0?Ee:"application/octet-stream",De=`data:${We};base64,${Ze}`}else if(Ue==="image-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else if(Ue==="file-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else continue;if(De)if(Ue==="image-url"||We.startsWith("image/"))Ie.push({type:"image",image:De,...We.includes("/")?{mimeType:We}:{}});else if(We.startsWith("audio/"))Ie.push({type:"audio",audio:De,mimeType:We});else if(We.startsWith("video/"))Ie.push({type:"video",video:De,mimeType:We});else{let Ze=We||"application/octet-stream";Ie.push({type:"file",data:De,mimeType:Ze,filename:mh(Ze)})}}if(Ie.length>0){let it=d(),X=ce,Ee={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ge}};g(Ee);let De=m;De&&(De.streaming=!1,g(De)),m=null,D.current=null}}else if(j==="execution_complete"){let T=v.kind??we;T==="agent"&&he&&(he.status=v.success?"complete":"error",he.completedAt=ke(v.completedAt),he.stopReason=v.stopReason);let R=m;R&&(T==="flow"&&R.streaming!==!1?Oe(R):(R.streaming=!1,g(R)),m=null),E=null,A="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(j!=="ping"){if(j==="approval_start"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="approval_complete"){let T=v.approvalId;if(T){let _={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:v.decision??"approved",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(_)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let T=v.artifactType,R=String(v.id),_=typeof v.title=="string"?v.title:void 0,Q=v.file,$;Q&&typeof Q=="object"&&!Array.isArray(Q)&&typeof Q.path=="string"&&typeof Q.mimeType=="string"&&($={path:Q.path,mimeType:Q.mimeType,...typeof Q.language=="string"?{language:Q.language}:{}}),n({type:"artifact_start",id:R,artifactType:T,title:_,component:typeof v.component=="string"?v.component:void 0,...$?{file:$}:{}});let K=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(fe.set(R,{markdown:"",title:_,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let ce=Lo(this.config.features?.artifacts,T),Ke=typeof v.component=="string"?v.component:void 0,Ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:pi(ce,{artifactId:R,title:_,artifactType:T,status:"streaming",...$?{file:$}:{},...Ke?{component:Ke}:{}})};me.set(R,Ie),g(Ie)}}else if(j==="artifact_delta"){let T=String(v.id),R=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:R});let _=fe.get(T);_&&(_.markdown+=R)}else if(j==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let R=fe.get(String(v.id));R&&(R.props={...R.props??{},...T})}else if(j==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let R=me.get(T);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let Q=fe.get(T);Q?.markdown&&(_.props.markdown=Q.markdown),Q?.file&&(_.props.file=Q.file),_.component==="PersonaArtifactInline"&&Q?.props&&Object.keys(Q.props).length>0&&(_.props.componentProps=Q.props)}R.rawContent=JSON.stringify(_)}catch{}fe.delete(T),g(R),me.delete(T)}}}else if(j==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let R=String(T.id??`msg-${d()}`),_=T.role,$={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:d()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&be.add(ce)}catch{}m=null,D.current=null,Je.delete(R),Ne.delete(R)}else if(j==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(j==="dispatch_error"){let R=v.message??v.error;R!=null&&R!==""&&(T=new Error(String(R)))}else{let R=v.error;typeof R=="string"&&R!==""?T=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(T=new Error(String(R.message??R)))}if(T){n({type:"error",error:T});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:k,value:j}=await s.read();if(k)break;l+=i.decode(j,{stream:!0});let v=l.split(`
|
|
185
185
|
|
|
186
186
|
`);l=v.pop()??"";for(let T of v){let R=T.split(`
|
|
187
187
|
`),_="message",Q="",$=null;for(let Ie of R)Ie.startsWith("event:")?_=Ie.replace("event:","").trim():Ie.startsWith("data:")?Q+=Ie.replace("data:","").trim():Ie.startsWith("id:")&&($=Ie.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!Q){K();continue}let ce;try{ce=JSON.parse(Q)}catch(Ie){n({type:"error",error:Ie instanceof Error?Ie:new Error("Failed to parse chat stream payload")});continue}let Ke=_!=="message"?_:ce.type??"message";if(this.onSSEEvent?.(Ke,ce),this.parseSSEEvent){D.current=m;let Ie=await this.handleCustomSSEEvent(ce,n,D,g,d,B);if(D.current&&D.current!==m&&(m=D.current),Ie){K();continue}}Qe.push({payloadType:Ke,payload:ce}),Re(),K()}}Re()}};function xi(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function sr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Ci="[Image]";function Ep(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function ir(t){return{type:"text",text:t}}var kp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],$n=[...kp,...yh];function vh(t){return kp.includes(t)||t.startsWith("image/")}function wi(t){return vh(t.type)}async function Lp(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wi(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function Pp(t,e=$n,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function xh(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ip(t,e){let n=xh(e).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"}[t]||n||"FILE"}hl();var Rp=16e3,Ch=24e3,wh=4096,Ah=1380533830;function Sh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Ah?new Uint8Array(t,44):new Uint8Array(t)}function Mh(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var es=class{constructor(e){this.config=e;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 e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)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:Rp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ar(Ch);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.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 c=`${Mh(o)}/ws/agents/${encodeURIComponent(e)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(wh,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},s.connect(i),i.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.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(e,n){if(n!==this.callGeneration||!this.playback)return;let o=Sh(e);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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Ro=class{constructor(e={}){this.config=e;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(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,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(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function lr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new es(t.runtype);case"browser":if(!Ro.isSupported())throw new Error("Browser speech recognition not supported");return new Ro(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;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: ${t.type}`)}}function Wp(t){if(t?.type==="custom"&&t.custom)return lr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return lr({type:"runtype",runtype:t.runtype});if(Ro.isSupported())return lr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function bl(t){try{return Wp(t),!0}catch{return!1}}function Ai(t){let e=["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 e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var cr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let i=s.find(l=>l.name===e.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ai(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var ts=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"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(e,"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(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function yl(t){if(!t)return"";let e=Th(t);return Hp(e!==null?e:t)}function Th(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Hp(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|