@runtypelabs/persona 4.27.0 → 4.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -0
- package/dist/{approval-ui-QAKWNFNM.js → approval-ui-OBBI62ES.js} +1 -1
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +20 -5
- package/dist/approval-ui.d.ts +20 -5
- package/dist/approval-ui.js +2 -2
- package/dist/artifacts-ui.d.cts +20 -5
- package/dist/artifacts-ui.d.ts +20 -5
- package/dist/{chunk-NQLDCJAP.js → chunk-D4TDKCT5.js} +2 -2
- package/dist/chunk-FNXK3VTC.js +1 -0
- package/dist/{client-history-HTRKHBAF.js → client-history-QGAFMCBE.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/{client-stream-N22JHTLE.js → client-stream-WXD2FL23.js} +1 -1
- package/dist/client-stream.js +3 -3
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +5 -5
- package/dist/context-mentions.d.cts +20 -5
- package/dist/context-mentions.d.ts +20 -5
- package/dist/event-stream-view.d.cts +20 -5
- package/dist/event-stream-view.d.ts +20 -5
- package/dist/forms-ui.d.cts +26 -5
- package/dist/forms-ui.d.ts +26 -5
- package/dist/index.cjs +41 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +59 -30
- package/dist/index.d.ts +59 -30
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +41 -41
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +20 -5
- package/dist/session-reconnect.d.ts +20 -5
- package/dist/smart-dom-reader.d.cts +20 -5
- package/dist/smart-dom-reader.d.ts +20 -5
- package/dist/theme-editor-preview.cjs +63 -63
- package/dist/theme-editor-preview.d.cts +20 -5
- package/dist/theme-editor-preview.d.ts +20 -5
- package/dist/theme-editor-preview.js +6 -6
- package/dist/theme-editor.d.cts +21 -6
- package/dist/theme-editor.d.ts +21 -6
- package/dist/voice-runtime-TWFJ4UUS.js +17 -0
- package/dist/voice-runtime.cjs +8 -8
- package/dist/voice-runtime.d.cts +31 -5
- package/dist/voice-runtime.d.ts +31 -5
- package/dist/voice-runtime.js +8 -8
- package/dist/webmcp-runtime-5Q3IHAHP.js +6 -0
- package/dist/webmcp-runtime.cjs +2 -2
- package/dist/webmcp-runtime.d.cts +22 -26
- package/dist/webmcp-runtime.d.ts +22 -26
- package/dist/webmcp-runtime.js +2 -2
- package/package.json +5 -2
- package/src/client.interrupt.test.ts +18 -0
- package/src/client.ts +7 -0
- package/src/generated/runtype-openapi-contract.ts +3 -0
- package/src/session.ts +11 -3
- package/src/session.voice.test.ts +140 -0
- package/src/theme-editor/webmcp/types.ts +1 -1
- package/src/types.ts +26 -5
- package/src/voice/runtype-voice-provider.ts +93 -11
- package/src/voice/voice-clause-buffer.test.ts +143 -0
- package/src/voice/voice-clause-buffer.ts +187 -0
- package/src/voice/voice-delegation.ts +85 -3
- package/src/voice/voice.test.ts +257 -2
- package/src/webmcp-bridge.test.ts +87 -21
- package/src/webmcp-bridge.ts +21 -26
- package/src/webmcp-polyfill.integration.test.ts +339 -0
- package/src/webmcp-polyfill.ts +7 -4
- package/src/webmcp-runtime-bundle.test.ts +1 -1
- package/src/webmcp-runtime-entry.ts +34 -19
- package/dist/chunk-3255TNY7.js +0 -1
- package/dist/voice-runtime-RHRX4F3T.js +0 -17
- package/dist/webmcp-runtime-V6ZWW3PI.js +0 -6
package/dist/codegen.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var $=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var W=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},H=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of M(i))!R.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=T(i,a))||s.enumerable});return e};var N=e=>H($({},"__esModule",{value:!0}),e);var X={};W(X,{generateCodeSnippet:()=>I});module.exports=N(X);var j="4.
|
|
1
|
+
"use strict";var $=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var W=(e,i)=>{for(var r in i)$(e,r,{get:i[r],enumerable:!0})},H=(e,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of M(i))!R.call(e,a)&&a!==r&&$(e,a,{get:()=>i[a],enumerable:!(s=T(i,a))||s.enumerable});return e};var N=e=>H($({},"__esModule",{value:!0}),e);var X={};W(X,{generateCodeSnippet:()=>I});module.exports=N(X);var j="4.28.1";var A=j;function x(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${A}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function q(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var v=`({ text, message }: any) => {
|
|
2
2
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
3
3
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
4
4
|
let cleanJson = jsonSource
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
12
12
|
} catch (e) { return null; }
|
|
13
13
|
return null;
|
|
14
|
-
}`,
|
|
14
|
+
}`,O=`function(ctx) {
|
|
15
15
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
16
16
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
17
17
|
var cleanJson = jsonSource
|
|
@@ -73,9 +73,9 @@
|
|
|
73
73
|
}`;function L(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function h(e){return e.parserType??L(e.streamParser)??"plain"}function g(e,i){let r=[];return e.toolCall&&(r.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&r.push(`${i} ${s}: "${a}",`)}),r.push(`${i}},`)),r}function m(e,i,r){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([n,o])=>n!=="onFeedback"&&n!=="onCopy"&&o!==void 0),t=r?.onFeedback||r?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([n,o])=>{n==="onFeedback"||n==="onCopy"||(typeof o=="string"?s.push(`${i} ${n}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${n}: ${o},`))}),r?.onFeedback&&s.push(`${i} onFeedback: ${r.onFeedback},`),r?.onCopy&&s.push(`${i} onCopy: ${r.onCopy},`),s.push(`${i}},`)),s}function f(e,i){let r=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(r.push(`${i}markdown: {`),s&&(r.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,n])=>{typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`)}),r.push(`${i} },`)),a&&r.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${i}},`))}return r}function y(e,i){if(!e.suggestions)return[];let r=JSON.stringify(e.suggestions,null,2).split(`
|
|
74
74
|
`);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function b(e,i){let r=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||a)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function S(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function P(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),P(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),P(e,r,`${s} `),e.push(`${s}},`))}function C(e,i,r){i.future?.v5Defaults!==void 0&&e.push(`${r}future: { v5Defaults: ${i.future.v5Defaults===!0} },`)}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function I(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:q(r.hooks)}:void 0;return i==="esm"?K(s,a):i==="script-installer"?Y(s,a):i==="script-advanced"?z(s,a):i==="react-component"?G(s,a):i==="react-advanced"?B(s,a):U(s,a)}function K(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),C(t,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...b(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
75
75
|
`)}function G(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),C(t,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...b(e," ")),t.push(...S(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
76
|
-
`)}function B(e,i){let r=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),C(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),s.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...b(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${F}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${O}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${O}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${E}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${E}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
+
`)}function B(e,i){let r=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),C(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),s.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...b(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${F}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${v}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${v}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${E}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${E}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
77
77
|
`)}function _(e){let i=h(e),r=i!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),r&&(s.parserType=i),e.future?.v5Defaults!==void 0&&(s.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestions&&(s.suggestions=e.suggestions),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,w])=>{l!=="format"&&(typeof w=="string"||typeof w=="boolean")&&(p[l]=w)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function Y(e,i){let r=_(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"'");return`<script src="${x(i)}/install.global.js" data-config='${t}'></script>`}function U(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=x(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),C(n,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...b(e," ")),n.push(...S(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
|
|
78
78
|
`)}function z(e,i){let r=i?.hooks,s=_(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
|
|
79
79
|
`).map((n,o)=>o===0?n:" "+n).join(`
|
|
80
|
-
`)};`,""," // Constants",` var CDN_BASE = '${x(i)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${J});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${
|
|
80
|
+
`)};`,""," // Constants",` var CDN_BASE = '${x(i)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${J});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${O}`),t.push(" ];")),t.push(""),r?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${r.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${k}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${k}`),t.push(" ];")),t.push(""),r?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${r.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),r?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(r?.onFeedback||r?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${c(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
|
|
81
81
|
`)}0&&(module.exports={generateCodeSnippet});
|
package/dist/codegen.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var S="4.
|
|
1
|
+
var S="4.28.1";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,r=>`%${r.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${j}/dist`}function u(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(i=>i.toString()).join(", ")}]`:e.toString()}function _(e){if(e)return{getHeaders:u(e.getHeaders),onFeedback:u(e.onFeedback),onCopy:u(e.onCopy),requestMiddleware:u(e.requestMiddleware),actionHandlers:u(e.actionHandlers),actionParsers:u(e.actionParsers),postprocessMessage:u(e.postprocessMessage),contextProviders:u(e.contextProviders),streamParser:u(e.streamParser)}}var A=`({ text, message }: any) => {
|
|
2
2
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
3
3
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
4
4
|
let cleanJson = jsonSource
|
|
@@ -11,7 +11,7 @@ var S="4.27.0";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,""
|
|
|
11
11
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
12
12
|
} catch (e) { return null; }
|
|
13
13
|
return null;
|
|
14
|
-
}`,
|
|
14
|
+
}`,v=`function(ctx) {
|
|
15
15
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
16
16
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
17
17
|
var cleanJson = jsonSource
|
|
@@ -24,7 +24,7 @@ var S="4.27.0";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,""
|
|
|
24
24
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
25
25
|
} catch (e) { return null; }
|
|
26
26
|
return null;
|
|
27
|
-
}`,
|
|
27
|
+
}`,O=`(action: any, context: any) => {
|
|
28
28
|
if (action.type !== 'nav_then_click') return;
|
|
29
29
|
const payload = action.payload || action.raw || {};
|
|
30
30
|
const url = payload?.page;
|
|
@@ -73,9 +73,9 @@ var S="4.27.0";var j=S;function $(e){return e?.cdnBase?.trim().replace(/\/+$/,""
|
|
|
73
73
|
}`;function R(e){if(!e)return null;let i=e.toString();return i.includes("createJsonStreamParser")||i.includes("partial-json")?"json":i.includes("createRegexJsonParser")||i.includes("regex")?"regex-json":i.includes("createXmlParser")||i.includes("<text>")?"xml":null}function h(e){return e.parserType??R(e.streamParser)??"plain"}function g(e,i){let r=[];return e.toolCall&&(r.push(`${i}toolCall: {`),Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&r.push(`${i} ${s}: "${a}",`)}),r.push(`${i}},`)),r}function m(e,i,r){let s=[],a=e.messageActions&&Object.entries(e.messageActions).some(([n,o])=>n!=="onFeedback"&&n!=="onCopy"&&o!==void 0),t=r?.onFeedback||r?.onCopy;return(a||t)&&(s.push(`${i}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([n,o])=>{n==="onFeedback"||n==="onCopy"||(typeof o=="string"?s.push(`${i} ${n}: "${o}",`):typeof o=="boolean"&&s.push(`${i} ${n}: ${o},`))}),r?.onFeedback&&s.push(`${i} onFeedback: ${r.onFeedback},`),r?.onCopy&&s.push(`${i} onCopy: ${r.onCopy},`),s.push(`${i}},`)),s}function f(e,i){let r=[];if(e.markdown){let s=e.markdown.options&&Object.keys(e.markdown.options).length>0,a=e.markdown.disableDefaultStyles!==void 0;(s||a)&&(r.push(`${i}markdown: {`),s&&(r.push(`${i} options: {`),Object.entries(e.markdown.options).forEach(([t,n])=>{typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`)}),r.push(`${i} },`)),a&&r.push(`${i} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),r.push(`${i}},`))}return r}function y(e,i){if(!e.suggestions)return[];let r=JSON.stringify(e.suggestions,null,2).split(`
|
|
74
74
|
`);return r.map((s,a)=>{let t=a===0?`${i}suggestions: `:i,n=a===r.length-1?",":"";return`${t}${s}${n}`})}function b(e,i){let r=[];if(e.layout){let s=e.layout.header&&Object.keys(e.layout.header).some(t=>t!=="render"),a=e.layout.messages&&Object.keys(e.layout.messages).some(t=>t!=="renderUserMessage"&&t!=="renderAssistantMessage");(s||a)&&(r.push(`${i}layout: {`),s&&(r.push(`${i} header: {`),Object.entries(e.layout.header).forEach(([t,n])=>{t!=="render"&&(typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),a&&(r.push(`${i} messages: {`),Object.entries(e.layout.messages).forEach(([t,n])=>{t==="renderUserMessage"||t==="renderAssistantMessage"||(t==="avatar"&&typeof n=="object"&&n!==null?(r.push(`${i} avatar: {`),Object.entries(n).forEach(([o,p])=>{typeof p=="string"?r.push(`${i} ${o}: "${p}",`):typeof p=="boolean"&&r.push(`${i} ${o}: ${p},`)}),r.push(`${i} },`)):t==="timestamp"&&typeof n=="object"&&n!==null?Object.entries(n).some(([p])=>p!=="format")&&(r.push(`${i} timestamp: {`),Object.entries(n).forEach(([p,l])=>{p!=="format"&&(typeof l=="string"?r.push(`${i} ${p}: "${l}",`):typeof l=="boolean"&&r.push(`${i} ${p}: ${l},`))}),r.push(`${i} },`)):typeof n=="string"?r.push(`${i} ${t}: "${n}",`):typeof n=="boolean"&&r.push(`${i} ${t}: ${n},`))}),r.push(`${i} },`)),r.push(`${i}},`))}return r}function x(e,i){let r=[];return e&&(e.getHeaders&&r.push(`${i}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&r.push(`${i}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&r.push(`${i}actionParsers: ${e.actionParsers},`),e.actionHandlers&&r.push(`${i}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&r.push(`${i}contextProviders: ${e.contextProviders},`),e.streamParser&&r.push(`${i}streamParser: ${e.streamParser},`)),r}function k(e,i,r){Object.entries(i).forEach(([s,a])=>{if(!(a===void 0||typeof a=="function")){if(Array.isArray(a)){e.push(`${r}${s}: ${JSON.stringify(a)},`);return}if(a&&typeof a=="object"){e.push(`${r}${s}: {`),k(e,a,`${r} `),e.push(`${r}},`);return}e.push(`${r}${s}: ${JSON.stringify(a)},`)}})}function d(e,i,r,s){r&&(e.push(`${s}${i}: {`),k(e,r,`${s} `),e.push(`${s}},`))}function C(e,i,r){i.future?.v5Defaults!==void 0&&e.push(`${r}future: { v5Defaults: ${i.future.v5Defaults===!0} },`)}function c(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function W(e,i="esm",r){let s={...e};delete s.postprocessMessage,delete s.initialMessages;let a=r?{...r,hooks:_(r.hooks)}:void 0;return i==="esm"?H(s,a):i==="script-installer"?q(s,a):i==="script-advanced"?J(s,a):i==="react-component"?N(s,a):i==="react-advanced"?D(s,a):F(s,a)}function H(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),C(t,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...b(e," ")),t.push(...x(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
75
75
|
`)}function N(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&t.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&t.push(` clientToken: "${e.clientToken}",`),e.agentId&&t.push(` agentId: "${e.agentId}",`),e.target&&t.push(` target: "${e.target}",`),e.flowId&&t.push(` flowId: "${e.flowId}",`),a&&t.push(` parserType: "${s}",`),C(t,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(t,"theme",e.theme," "),e.launcher&&d(t,"launcher",e.launcher," "),e.copy&&(t.push(" copy: {"),Object.entries(e.copy).forEach(([n,o])=>{t.push(` ${n}: "${o}",`)}),t.push(" },")),e.sendButton&&(t.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"?t.push(` ${n}: ${o},`):typeof o=="number"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([n,o])=>{typeof o=="string"?t.push(` ${n}: "${o}",`):typeof o=="boolean"&&t.push(` ${n}: ${o},`)}),t.push(" },")),e.features&&(t.push(" features: {"),Object.entries(e.features).forEach(([n,o])=>{t.push(` ${n}: ${o},`)}),t.push(" },")),t.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(t.push(" suggestionChips: ["),e.suggestionChips.forEach(n=>{t.push(` "${n}",`)}),t.push(" ],")),e.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),t.push(" },")),t.push(...g(e," ")),t.push(...m(e," ",r)),t.push(...f(e," ")),t.push(...b(e," ")),t.push(...x(r," ")),e.debug&&t.push(` debug: ${e.debug},`),r?.postprocessMessage?t.push(` postprocessMessage: ${r.postprocessMessage}`):t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
76
|
-
`)}function D(e,i){let r=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),C(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),s.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...b(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${T}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${v}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${v}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
76
|
+
`)}function D(e,i){let r=i?.hooks,s=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${c(i)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),C(s,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(s,"theme",e.theme," "),e.launcher&&d(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,t])=>{s.push(` ${a}: "${t}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"?s.push(` ${a}: ${t},`):typeof t=="number"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,t])=>{typeof t=="string"?s.push(` ${a}: "${t}",`):typeof t=="boolean"&&s.push(` ${a}: ${t},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,t])=>{s.push(` ${a}: ${t},`)}),s.push(" },")),s.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...g(e," ")),s.push(...m(e," ",r)),s.push(...f(e," ")),s.push(...b(e," ")),r?.getHeaders&&s.push(` getHeaders: ${r.getHeaders},`),r?.contextProviders&&s.push(` contextProviders: ${r.contextProviders},`),e.debug&&s.push(` debug: ${e.debug},`),s.push(" initialMessages: loadSavedMessages(),"),r?.streamParser?s.push(` streamParser: ${r.streamParser},`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(` streamParser: () => createFlexibleJsonStreamParser(${T}),`)),r?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),s.push(" // Built-in parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" actionParsers: ["),s.push(" defaultJsonActionParser,"),s.push(" // Parser for markdown-wrapped JSON"),s.push(` ${A}`),s.push(" ],")),r?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` actionHandlers: [...(${r.actionHandlers}),`),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Built-in handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")):(s.push(" // Action handlers for navigation and other actions"),s.push(" actionHandlers: ["),s.push(" defaultActionHandlers.message,"),s.push(" defaultActionHandlers.messageAndClick,"),s.push(" // Handler for nav_then_click action"),s.push(` ${O}`),s.push(" ],")),r?.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage},`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" requestMiddleware: ({ payload, config }) => {"),s.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),s.push(" const merged = customResult || payload;"),s.push(" return {"),s.push(" ...merged,"),s.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),s.push(" };"),s.push(" }")):(s.push(" requestMiddleware: ({ payload }) => {"),s.push(" return {"),s.push(" ...payload,"),s.push(" metadata: collectDOMContext()"),s.push(" };"),s.push(" }")),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Save state on message events"),s.push(" const handleMessage = () => {"),s.push(" const session = handle?.getSession?.();"),s.push(" if (session) {"),s.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),s.push(" messages: session.messages,"),s.push(" timestamp: new Date().toISOString()"),s.push(" }));"),s.push(" }"),s.push(" };"),s.push(""),s.push(" // Clear state on clear chat"),s.push(" const handleClearChat = () => {"),s.push(" localStorage.removeItem(STORAGE_KEY);"),s.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),s.push(" };"),s.push(""),s.push(" window.addEventListener('persona:message', handleMessage);"),s.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" window.removeEventListener('persona:message', handleMessage);"),s.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage: Collects DOM context for AI-powered navigation"),s.push("// Features:"),s.push("// - Extracts page elements (products, buttons, links)"),s.push("// - Persists chat history across page loads"),s.push("// - Handles navigation actions (nav_then_click)"),s.push("// - Processes structured JSON actions from AI"),s.push("//"),s.push("// Example usage in Next.js:"),s.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),s.push("//"),s.push("// export default function RootLayout({ children }) {"),s.push("// return ("),s.push('// <html lang="en">'),s.push("// <body>"),s.push("// {children}"),s.push("// <ChatWidgetAdvanced />"),s.push("// </body>"),s.push("// </html>"),s.push("// );"),s.push("// }"),s.join(`
|
|
77
77
|
`)}function P(e){let i=h(e),r=i!=="plain",s={};if(e.apiUrl&&(s.apiUrl=e.apiUrl),e.clientToken&&(s.clientToken=e.clientToken),e.agentId&&(s.agentId=e.agentId),e.target&&(s.target=e.target),e.flowId&&(s.flowId=e.flowId),r&&(s.parserType=i),e.future?.v5Defaults!==void 0&&(s.future={v5Defaults:e.future.v5Defaults===!0}),e.theme&&(s.theme=e.theme),e.launcher&&(s.launcher=e.launcher),e.copy&&(s.copy=e.copy),e.sendButton&&(s.sendButton=e.sendButton),e.voiceRecognition&&(s.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(s.statusIndicator=e.statusIndicator),e.features&&(s.features=e.features),e.suggestions&&(s.suggestions=e.suggestions),e.suggestionChips?.length>0&&(s.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(s.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(s.debug=e.debug),e.toolCall){let a={};Object.entries(e.toolCall).forEach(([t,n])=>{typeof n=="string"&&(a[t]=n)}),Object.keys(a).length>0&&(s.toolCall=a)}if(e.messageActions){let a={};Object.entries(e.messageActions).forEach(([t,n])=>{t!=="onFeedback"&&t!=="onCopy"&&n!==void 0&&(typeof n=="string"||typeof n=="boolean")&&(a[t]=n)}),Object.keys(a).length>0&&(s.messageActions=a)}if(e.markdown){let a={};e.markdown.options&&(a.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(a.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(a).length>0&&(s.markdown=a)}if(e.layout){let a={};if(e.layout.header){let t={};Object.entries(e.layout.header).forEach(([n,o])=>{n!=="render"&&(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.header=t)}if(e.layout.messages){let t={};Object.entries(e.layout.messages).forEach(([n,o])=>{if(n!=="renderUserMessage"&&n!=="renderAssistantMessage")if(n==="avatar"&&typeof o=="object"&&o!==null)t.avatar=o;else if(n==="timestamp"&&typeof o=="object"&&o!==null){let p={};Object.entries(o).forEach(([l,w])=>{l!=="format"&&(typeof w=="string"||typeof w=="boolean")&&(p[l]=w)}),Object.keys(p).length>0&&(t.timestamp=p)}else(typeof o=="string"||typeof o=="boolean")&&(t[n]=o)}),Object.keys(t).length>0&&(a.messages=t)}Object.keys(a).length>0&&(s.layout=a)}return s}function q(e,i){let r=P(e),a=!!(i?.windowKey||i?.target)?{config:r,...i?.windowKey?{windowKey:i.windowKey}:{},...i?.target?{target:i.target}:{}}:r,t=JSON.stringify(a,null,0).replace(/'/g,"'");return`<script src="${$(i)}/install.global.js" data-config='${t}'></script>`}function F(e,i){let r=i?.hooks,s=h(e),a=s!=="plain",t=$(i),n=["<!-- Load CSS -->",`<link rel="stylesheet" href="${t}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${t}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${c(i)}',`,...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.agentId&&n.push(` agentId: "${e.agentId}",`),e.target&&n.push(` target: "${e.target}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),a&&n.push(` parserType: "${s}",`),C(n,e," "),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&d(n,"theme",e.theme," "),e.launcher&&d(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([o,p])=>{n.push(` ${o}: "${p}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"?n.push(` ${o}: ${p},`):typeof p=="number"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,p])=>{typeof p=="string"?n.push(` ${o}: "${p}",`):typeof p=="boolean"&&n.push(` ${o}: ${p},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([o,p])=>{n.push(` ${o}: ${p},`)}),n.push(" },")),n.push(...y(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{n.push(` "${o}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...g(e," ")),n.push(...m(e," ",r)),n.push(...f(e," ")),n.push(...b(e," ")),n.push(...x(r," ")),e.debug&&n.push(` debug: ${e.debug},`),r?.postprocessMessage?n.push(` postprocessMessage: ${r.postprocessMessage}`):n.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),n.push(" }"),n.push(" });"),n.push("</script>"),n.join(`
|
|
78
78
|
`)}function J(e,i){let r=i?.hooks,s=P(e),t=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(s,null,2).split(`
|
|
79
79
|
`).map((n,o)=>o===0?n:" "+n).join(`
|
|
80
|
-
`)};`,""," // Constants",` var CDN_BASE = '${$(i)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${M});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${
|
|
80
|
+
`)};`,""," // Constants",` var CDN_BASE = '${$(i)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r?.getHeaders&&(t.push(` widgetConfig.getHeaders = ${r.getHeaders};`),t.push("")),r?.contextProviders&&(t.push(` widgetConfig.contextProviders = ${r.contextProviders};`),t.push("")),r?.streamParser?t.push(` widgetConfig.streamParser = ${r.streamParser};`):(t.push(" // Flexible JSON stream parser for handling structured actions"),t.push(" widgetConfig.streamParser = function() {"),t.push(` return agentWidget.createFlexibleJsonStreamParser(${M});`),t.push(" };")),t.push(""),r?.actionParsers?(t.push(" // Action parsers (custom merged with defaults)"),t.push(` var customParsers = ${r.actionParsers};`),t.push(" widgetConfig.actionParsers = customParsers.concat(["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${v}`),t.push(" ]);")):(t.push(" // Action parsers to detect JSON actions in responses"),t.push(" widgetConfig.actionParsers = ["),t.push(" agentWidget.defaultJsonActionParser,"),t.push(` ${v}`),t.push(" ];")),t.push(""),r?.actionHandlers?(t.push(" // Action handlers (custom merged with defaults)"),t.push(` var customHandlers = ${r.actionHandlers};`),t.push(" widgetConfig.actionHandlers = customHandlers.concat(["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${E}`),t.push(" ]);")):(t.push(" // Action handlers for navigation and other actions"),t.push(" widgetConfig.actionHandlers = ["),t.push(" agentWidget.defaultActionHandlers.message,"),t.push(" agentWidget.defaultActionHandlers.messageAndClick,"),t.push(` ${E}`),t.push(" ];")),t.push(""),r?.requestMiddleware?(t.push(" // Request middleware (custom merged with DOM context)"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(` var customResult = (${r.requestMiddleware})(ctx);`),t.push(" var merged = customResult || ctx.payload;"),t.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),t.push(" };")):(t.push(" // Send DOM context with each request"),t.push(" widgetConfig.requestMiddleware = function(ctx) {"),t.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),t.push(" };")),t.push(""),r?.postprocessMessage?t.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(t.push(" // Markdown postprocessor"),t.push(" widgetConfig.postprocessMessage = function(ctx) {"),t.push(" return agentWidget.markdownPostprocessor(ctx.text);"),t.push(" };")),t.push(""),(r?.onFeedback||r?.onCopy)&&(t.push(" // Message action callbacks"),t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r?.onFeedback&&t.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r?.onCopy&&t.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),t.push("")),t.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${c(i)}',`," useShadowDom: false,",...i?.windowKey?[` windowKey: '${i.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),t.join(`
|
|
81
81
|
`)}export{W as generateCodeSnippet};
|
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -7125,6 +7124,13 @@ type VoiceDelegationRequest = {
|
|
|
7125
7124
|
role: string;
|
|
7126
7125
|
content: unknown;
|
|
7127
7126
|
}>;
|
|
7127
|
+
/**
|
|
7128
|
+
* Set when the server streams delegated answers (`delegation_stream`): called
|
|
7129
|
+
* with each speakable piece of the turn's answer, in order, while it renders.
|
|
7130
|
+
* The pieces, concatenated, are a prefix of the result's `text`; the result
|
|
7131
|
+
* says how much of it with `streamedChars`.
|
|
7132
|
+
*/
|
|
7133
|
+
stream?: (text: string) => void;
|
|
7128
7134
|
};
|
|
7129
7135
|
/**
|
|
7130
7136
|
* How a delegated turn ended, or that it waits on an approval (contract
|
|
@@ -7155,6 +7161,12 @@ type VoiceDelegationResult = {
|
|
|
7155
7161
|
* @default true
|
|
7156
7162
|
*/
|
|
7157
7163
|
inChat?: boolean;
|
|
7164
|
+
/**
|
|
7165
|
+
* How many leading characters of `text` already went out through
|
|
7166
|
+
* `request.stream` (the rest, such as an approval script, is unstreamed).
|
|
7167
|
+
* Omitted or 0: nothing was streamed.
|
|
7168
|
+
*/
|
|
7169
|
+
streamedChars?: number;
|
|
7158
7170
|
/**
|
|
7159
7171
|
* Set when the turn parked on approvals (`text` then asks for the decision).
|
|
7160
7172
|
* Resolves with the terminal result once the visitor decides (or the
|
|
@@ -9274,8 +9286,11 @@ type AgentWidgetConfig = {
|
|
|
9274
9286
|
/**
|
|
9275
9287
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9276
9288
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9277
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9278
|
-
* returned `webmcp:*`
|
|
9289
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9290
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9291
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9292
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9293
|
+
* and callback-result behavior.
|
|
9279
9294
|
*
|
|
9280
9295
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9281
9296
|
* fields layer on top.
|
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -7125,6 +7124,13 @@ type VoiceDelegationRequest = {
|
|
|
7125
7124
|
role: string;
|
|
7126
7125
|
content: unknown;
|
|
7127
7126
|
}>;
|
|
7127
|
+
/**
|
|
7128
|
+
* Set when the server streams delegated answers (`delegation_stream`): called
|
|
7129
|
+
* with each speakable piece of the turn's answer, in order, while it renders.
|
|
7130
|
+
* The pieces, concatenated, are a prefix of the result's `text`; the result
|
|
7131
|
+
* says how much of it with `streamedChars`.
|
|
7132
|
+
*/
|
|
7133
|
+
stream?: (text: string) => void;
|
|
7128
7134
|
};
|
|
7129
7135
|
/**
|
|
7130
7136
|
* How a delegated turn ended, or that it waits on an approval (contract
|
|
@@ -7155,6 +7161,12 @@ type VoiceDelegationResult = {
|
|
|
7155
7161
|
* @default true
|
|
7156
7162
|
*/
|
|
7157
7163
|
inChat?: boolean;
|
|
7164
|
+
/**
|
|
7165
|
+
* How many leading characters of `text` already went out through
|
|
7166
|
+
* `request.stream` (the rest, such as an approval script, is unstreamed).
|
|
7167
|
+
* Omitted or 0: nothing was streamed.
|
|
7168
|
+
*/
|
|
7169
|
+
streamedChars?: number;
|
|
7158
7170
|
/**
|
|
7159
7171
|
* Set when the turn parked on approvals (`text` then asks for the decision).
|
|
7160
7172
|
* Resolves with the terminal result once the visitor decides (or the
|
|
@@ -9274,8 +9286,11 @@ type AgentWidgetConfig = {
|
|
|
9274
9286
|
/**
|
|
9275
9287
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9276
9288
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9277
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9278
|
-
* returned `webmcp:*`
|
|
9289
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9290
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9291
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9292
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9293
|
+
* and callback-result behavior.
|
|
9279
9294
|
*
|
|
9280
9295
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9281
9296
|
* fields layer on top.
|
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -7125,6 +7124,13 @@ type VoiceDelegationRequest = {
|
|
|
7125
7124
|
role: string;
|
|
7126
7125
|
content: unknown;
|
|
7127
7126
|
}>;
|
|
7127
|
+
/**
|
|
7128
|
+
* Set when the server streams delegated answers (`delegation_stream`): called
|
|
7129
|
+
* with each speakable piece of the turn's answer, in order, while it renders.
|
|
7130
|
+
* The pieces, concatenated, are a prefix of the result's `text`; the result
|
|
7131
|
+
* says how much of it with `streamedChars`.
|
|
7132
|
+
*/
|
|
7133
|
+
stream?: (text: string) => void;
|
|
7128
7134
|
};
|
|
7129
7135
|
/**
|
|
7130
7136
|
* How a delegated turn ended, or that it waits on an approval (contract
|
|
@@ -7155,6 +7161,12 @@ type VoiceDelegationResult = {
|
|
|
7155
7161
|
* @default true
|
|
7156
7162
|
*/
|
|
7157
7163
|
inChat?: boolean;
|
|
7164
|
+
/**
|
|
7165
|
+
* How many leading characters of `text` already went out through
|
|
7166
|
+
* `request.stream` (the rest, such as an approval script, is unstreamed).
|
|
7167
|
+
* Omitted or 0: nothing was streamed.
|
|
7168
|
+
*/
|
|
7169
|
+
streamedChars?: number;
|
|
7158
7170
|
/**
|
|
7159
7171
|
* Set when the turn parked on approvals (`text` then asks for the decision).
|
|
7160
7172
|
* Resolves with the terminal result once the visitor decides (or the
|
|
@@ -9274,8 +9286,11 @@ type AgentWidgetConfig = {
|
|
|
9274
9286
|
/**
|
|
9275
9287
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9276
9288
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9277
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9278
|
-
* returned `webmcp:*`
|
|
9289
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9290
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9291
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9292
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9293
|
+
* and callback-result behavior.
|
|
9279
9294
|
*
|
|
9280
9295
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9281
9296
|
* fields layer on top.
|
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -7125,6 +7124,13 @@ type VoiceDelegationRequest = {
|
|
|
7125
7124
|
role: string;
|
|
7126
7125
|
content: unknown;
|
|
7127
7126
|
}>;
|
|
7127
|
+
/**
|
|
7128
|
+
* Set when the server streams delegated answers (`delegation_stream`): called
|
|
7129
|
+
* with each speakable piece of the turn's answer, in order, while it renders.
|
|
7130
|
+
* The pieces, concatenated, are a prefix of the result's `text`; the result
|
|
7131
|
+
* says how much of it with `streamedChars`.
|
|
7132
|
+
*/
|
|
7133
|
+
stream?: (text: string) => void;
|
|
7128
7134
|
};
|
|
7129
7135
|
/**
|
|
7130
7136
|
* How a delegated turn ended, or that it waits on an approval (contract
|
|
@@ -7155,6 +7161,12 @@ type VoiceDelegationResult = {
|
|
|
7155
7161
|
* @default true
|
|
7156
7162
|
*/
|
|
7157
7163
|
inChat?: boolean;
|
|
7164
|
+
/**
|
|
7165
|
+
* How many leading characters of `text` already went out through
|
|
7166
|
+
* `request.stream` (the rest, such as an approval script, is unstreamed).
|
|
7167
|
+
* Omitted or 0: nothing was streamed.
|
|
7168
|
+
*/
|
|
7169
|
+
streamedChars?: number;
|
|
7158
7170
|
/**
|
|
7159
7171
|
* Set when the turn parked on approvals (`text` then asks for the decision).
|
|
7160
7172
|
* Resolves with the terminal result once the visitor decides (or the
|
|
@@ -9274,8 +9286,11 @@ type AgentWidgetConfig = {
|
|
|
9274
9286
|
/**
|
|
9275
9287
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9276
9288
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9277
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9278
|
-
* returned `webmcp:*`
|
|
9289
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9290
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9291
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9292
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9293
|
+
* and callback-result behavior.
|
|
9279
9294
|
*
|
|
9280
9295
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9281
9296
|
* fields layer on top.
|