@runtypelabs/cli 2.22.11 → 2.22.12

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.
Files changed (2) hide show
  1. package/dist/index.js +22 -19
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -40223,9 +40223,9 @@ var memoryConfigSchema = external_exports.object({
40223
40223
  injectSummary: external_exports.boolean().optional()
40224
40224
  });
40225
40225
  var sandboxNetworkAccessSchema = external_exports.union([
40226
- external_exports.enum(["none", "essentials"]),
40226
+ external_exports.enum(["none", "essentials", "open"]),
40227
40227
  external_exports.object({
40228
- profile: external_exports.enum(["none", "essentials"]).optional(),
40228
+ profile: external_exports.enum(["none", "essentials", "open"]).optional(),
40229
40229
  allow: external_exports.array(external_exports.string()).optional()
40230
40230
  })
40231
40231
  ]);
@@ -43622,6 +43622,9 @@ var AgentInputSchema = external_exports.object({
43622
43622
  // entry points stay in lockstep.
43623
43623
  sandbox: sandboxConfigSchema.optional()
43624
43624
  }).superRefine((val, ctx) => {
43625
+ if (val.agentId) {
43626
+ return;
43627
+ }
43625
43628
  if (val.agentType !== "claude_managed") {
43626
43629
  if (!val.name) {
43627
43630
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required" });
@@ -64904,13 +64907,13 @@ import { execFileSync } from "child_process";
64904
64907
  // src/lib/persona-init.ts
64905
64908
  init_credential_store();
64906
64909
 
64907
- // ../../node_modules/.pnpm/@runtypelabs+persona@4.2.0/node_modules/@runtypelabs/persona/dist/codegen.js
64908
- var S = "4.2.0";
64910
+ // ../../node_modules/.pnpm/@runtypelabs+persona@4.3.1/node_modules/@runtypelabs/persona/dist/codegen.js
64911
+ var S = "4.3.1";
64909
64912
  var c = S;
64910
64913
  function u(e) {
64911
64914
  if (e !== void 0) return typeof e == "string" ? e : Array.isArray(e) ? `[${e.map((r) => r.toString()).join(", ")}]` : e.toString();
64912
64915
  }
64913
- function _(e) {
64916
+ function I(e) {
64914
64917
  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) };
64915
64918
  }
64916
64919
  var x = `({ text, message }: any) => {
@@ -64977,28 +64980,28 @@ var O = `function(action, context) {
64977
64980
  window.location.href = targetUrl;
64978
64981
  return { handled: true, displayText: text };
64979
64982
  }`;
64980
- var T = `(parsed: any) => {
64983
+ var _ = `(parsed: any) => {
64981
64984
  if (!parsed || typeof parsed !== 'object') return null;
64982
64985
  if (parsed.action === 'nav_then_click') return 'Navigating...';
64983
64986
  if (parsed.action === 'message') return parsed.text || '';
64984
64987
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
64985
64988
  return parsed.text || null;
64986
64989
  }`;
64987
- var M = `function(parsed) {
64990
+ var T = `function(parsed) {
64988
64991
  if (!parsed || typeof parsed !== 'object') return null;
64989
64992
  if (parsed.action === 'nav_then_click') return 'Navigating...';
64990
64993
  if (parsed.action === 'message') return parsed.text || '';
64991
64994
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
64992
64995
  return parsed.text || null;
64993
64996
  }`;
64994
- function R(e) {
64997
+ function M(e) {
64995
64998
  if (!e) return null;
64996
64999
  let r = e.toString();
64997
65000
  return r.includes("createJsonStreamParser") || r.includes("partial-json") ? "json" : r.includes("createRegexJsonParser") || r.includes("regex") ? "regex-json" : r.includes("createXmlParser") || r.includes("<text>") ? "xml" : null;
64998
65001
  }
64999
65002
  function h(e) {
65000
65003
  var r, n;
65001
- return (n = (r = e.parserType) != null ? r : R(e.streamParser)) != null ? n : "plain";
65004
+ return (n = (r = e.parserType) != null ? r : M(e.streamParser)) != null ? n : "plain";
65002
65005
  }
65003
65006
  function m(e, r) {
65004
65007
  let n = [];
@@ -65064,15 +65067,15 @@ function g(e) {
65064
65067
  var r;
65065
65068
  return ((r = e == null ? void 0 : e.target) != null ? r : "body").replace(/\\/g, "\\\\").replace(/'/g, "\\'");
65066
65069
  }
65067
- function I(e, r = "esm", n) {
65070
+ function R(e, r = "esm", n) {
65068
65071
  let s = { ...e };
65069
65072
  delete s.postprocessMessage, delete s.initialMessages;
65070
- let o = n ? { ...n, hooks: _(n.hooks) } : void 0;
65073
+ let o = n ? { ...n, hooks: I(n.hooks) } : void 0;
65071
65074
  return r === "esm" ? W(s, o) : r === "script-installer" ? k(s, o) : r === "script-advanced" ? F(s, o) : r === "react-component" ? H(s, o) : r === "react-advanced" ? N(s, o) : D(s, o);
65072
65075
  }
65073
65076
  function W(e, r) {
65074
65077
  let n = r == null ? void 0 : r.hooks, s = h(e), o = s !== "plain", t = ["import '@runtypelabs/persona/widget.css';", "import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';", "", "initAgentWidget({", ` target: '${g(r)}',`, " config: {"];
65075
- return e.apiUrl && t.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && t.push(` clientToken: "${e.clientToken}",`), e.flowId && t.push(` flowId: "${e.flowId}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65078
+ 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}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65076
65079
  t.push(` ${i}: "${a}",`);
65077
65080
  }), t.push(" },")), e.sendButton && (t.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([i, a]) => {
65078
65081
  typeof a == "string" ? t.push(` ${i}: "${a}",`) : typeof a == "boolean" && t.push(` ${i}: ${a},`);
@@ -65089,7 +65092,7 @@ function W(e, r) {
65089
65092
  }
65090
65093
  function H(e, r) {
65091
65094
  let n = r == null ? void 0 : r.hooks, s = h(e), o = 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: '${g(r)}',`, " config: {"];
65092
- return e.apiUrl && t.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && t.push(` clientToken: "${e.clientToken}",`), e.flowId && t.push(` flowId: "${e.flowId}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65095
+ 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}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65093
65096
  t.push(` ${i}: "${a}",`);
65094
65097
  }), t.push(" },")), e.sendButton && (t.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([i, a]) => {
65095
65098
  typeof a == "string" ? t.push(` ${i}: "${a}",`) : typeof a == "boolean" && t.push(` ${i}: ${a},`);
@@ -65106,7 +65109,7 @@ function H(e, r) {
65106
65109
  }
65107
65110
  function N(e, r) {
65108
65111
  let n = r == null ? void 0 : r.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: '${g(r)}',`, " config: {"];
65109
- return e.apiUrl && s.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && s.push(` clientToken: "${e.clientToken}",`), e.flowId && s.push(` flowId: "${e.flowId}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(s, "theme", e.theme, " "), e.launcher && l(s, "launcher", e.launcher, " "), e.copy && (s.push(" copy: {"), Object.entries(e.copy).forEach(([o, t]) => {
65112
+ 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}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(s, "theme", e.theme, " "), e.launcher && l(s, "launcher", e.launcher, " "), e.copy && (s.push(" copy: {"), Object.entries(e.copy).forEach(([o, t]) => {
65110
65113
  s.push(` ${o}: "${t}",`);
65111
65114
  }), s.push(" },")), e.sendButton && (s.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([o, t]) => {
65112
65115
  typeof t == "string" ? s.push(` ${o}: "${t}",`) : typeof t == "boolean" && s.push(` ${o}: ${t},`);
@@ -65118,13 +65121,13 @@ function N(e, r) {
65118
65121
  s.push(` ${o}: ${t},`);
65119
65122
  }), s.push(" },")), e.suggestionChips && e.suggestionChips.length > 0 && (s.push(" suggestionChips: ["), e.suggestionChips.forEach((o) => {
65120
65123
  s.push(` "${o}",`);
65121
- }), 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(...m(e, " ")), s.push(...f(e, " ", n)), s.push(...y(e, " ")), s.push(...C(e, " ")), n != null && n.getHeaders && s.push(` getHeaders: ${n.getHeaders},`), n != null && n.contextProviders && s.push(` contextProviders: ${n.contextProviders},`), e.debug && s.push(` debug: ${e.debug},`), s.push(" initialMessages: loadSavedMessages(),"), n != null && n.streamParser ? s.push(` streamParser: ${n.streamParser},`) : (s.push(" // Flexible JSON stream parser for handling structured actions"), s.push(` streamParser: () => createFlexibleJsonStreamParser(${T}),`)), n != null && n.actionParsers ? (s.push(" // Action parsers (custom merged with defaults)"), s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`), s.push(" // Built-in parser for markdown-wrapped JSON"), s.push(` ${x}`), 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(` ${x}`), s.push(" ],")), n != null && n.actionHandlers ? (s.push(" // Action handlers (custom merged with defaults)"), s.push(` actionHandlers: [...(${n.actionHandlers}),`), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Built-in handler for nav_then_click action"), s.push(` ${j}`), 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(` ${j}`), s.push(" ],")), n != null && n.postprocessMessage ? s.push(` postprocessMessage: ${n.postprocessMessage},`) : s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"), n != null && n.requestMiddleware ? (s.push(" // Request middleware (custom merged with DOM context)"), s.push(" requestMiddleware: ({ payload, config }) => {"), s.push(` const customResult = (${n.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(`
65124
+ }), 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(...m(e, " ")), s.push(...f(e, " ", n)), s.push(...y(e, " ")), s.push(...C(e, " ")), n != null && n.getHeaders && s.push(` getHeaders: ${n.getHeaders},`), n != null && n.contextProviders && s.push(` contextProviders: ${n.contextProviders},`), e.debug && s.push(` debug: ${e.debug},`), s.push(" initialMessages: loadSavedMessages(),"), n != null && n.streamParser ? s.push(` streamParser: ${n.streamParser},`) : (s.push(" // Flexible JSON stream parser for handling structured actions"), s.push(` streamParser: () => createFlexibleJsonStreamParser(${_}),`)), n != null && n.actionParsers ? (s.push(" // Action parsers (custom merged with defaults)"), s.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`), s.push(" // Built-in parser for markdown-wrapped JSON"), s.push(` ${x}`), 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(` ${x}`), s.push(" ],")), n != null && n.actionHandlers ? (s.push(" // Action handlers (custom merged with defaults)"), s.push(` actionHandlers: [...(${n.actionHandlers}),`), s.push(" defaultActionHandlers.message,"), s.push(" defaultActionHandlers.messageAndClick,"), s.push(" // Built-in handler for nav_then_click action"), s.push(` ${j}`), 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(` ${j}`), s.push(" ],")), n != null && n.postprocessMessage ? s.push(` postprocessMessage: ${n.postprocessMessage},`) : s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"), n != null && n.requestMiddleware ? (s.push(" // Request middleware (custom merged with DOM context)"), s.push(" requestMiddleware: ({ payload, config }) => {"), s.push(` const customResult = (${n.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(`
65122
65125
  `);
65123
65126
  }
65124
65127
  function P(e) {
65125
65128
  var o;
65126
65129
  let r = h(e), n = r !== "plain", s = {};
65127
- if (e.apiUrl && (s.apiUrl = e.apiUrl), e.clientToken && (s.clientToken = e.clientToken), e.flowId && (s.flowId = e.flowId), n && (s.parserType = r), 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), ((o = e.suggestionChips) == null ? void 0 : o.length) > 0 && (s.suggestionChips = e.suggestionChips), e.suggestionChipsConfig && (s.suggestionChipsConfig = e.suggestionChipsConfig), e.debug && (s.debug = e.debug), e.toolCall) {
65130
+ 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), n && (s.parserType = r), 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), ((o = e.suggestionChips) == null ? void 0 : o.length) > 0 && (s.suggestionChips = e.suggestionChips), e.suggestionChipsConfig && (s.suggestionChipsConfig = e.suggestionChipsConfig), e.debug && (s.debug = e.debug), e.toolCall) {
65128
65131
  let t = {};
65129
65132
  Object.entries(e.toolCall).forEach(([i, a]) => {
65130
65133
  typeof a == "string" && (t[i] = a);
@@ -65170,7 +65173,7 @@ function k(e, r) {
65170
65173
  }
65171
65174
  function D(e, r) {
65172
65175
  let n = r == null ? void 0 : r.hooks, s = h(e), o = s !== "plain", t = ["<!-- Load CSS -->", `<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/widget.css" />`, "", "<!-- Load JavaScript -->", `<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist/index.global.js"></script>`, "", "<!-- Initialize widget -->", "<script>", " var handle = window.AgentWidget.initAgentWidget({", ` target: '${g(r)}',`, ...r != null && r.windowKey ? [` windowKey: '${r.windowKey}',`] : [], " config: {"];
65173
- return e.apiUrl && t.push(` apiUrl: "${e.apiUrl}",`), e.clientToken && t.push(` clientToken: "${e.clientToken}",`), e.flowId && t.push(` flowId: "${e.flowId}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65176
+ 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}",`), o && t.push(` parserType: "${s}",`), e.theme && typeof e.theme == "object" && Object.keys(e.theme).length > 0 && l(t, "theme", e.theme, " "), e.launcher && l(t, "launcher", e.launcher, " "), e.copy && (t.push(" copy: {"), Object.entries(e.copy).forEach(([i, a]) => {
65174
65177
  t.push(` ${i}: "${a}",`);
65175
65178
  }), t.push(" },")), e.sendButton && (t.push(" sendButton: {"), Object.entries(e.sendButton).forEach(([i, a]) => {
65176
65179
  typeof a == "string" ? t.push(` ${i}: "${a}",`) : typeof a == "boolean" && t.push(` ${i}: ${a},`);
@@ -65189,7 +65192,7 @@ function F(e, r) {
65189
65192
  let n = r == null ? void 0 : r.hooks, s = P(e), t = ["<script>", "(function() {", " 'use strict';", "", " // Configuration", ` var CONFIG = ${JSON.stringify(s, null, 2).split(`
65190
65193
  `).map((i, a) => a === 0 ? i : " " + i).join(`
65191
65194
  `)};`, "", " // Constants", ` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${c}/dist';`, " 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);", ""];
65192
- return n != null && n.getHeaders && (t.push(` widgetConfig.getHeaders = ${n.getHeaders};`), t.push("")), n != null && n.contextProviders && (t.push(` widgetConfig.contextProviders = ${n.contextProviders};`), t.push("")), n != null && n.streamParser ? t.push(` widgetConfig.streamParser = ${n.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(""), n != null && n.actionParsers ? (t.push(" // Action parsers (custom merged with defaults)"), t.push(` var customParsers = ${n.actionParsers};`), t.push(" widgetConfig.actionParsers = customParsers.concat(["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ]);")) : (t.push(" // Action parsers to detect JSON actions in responses"), t.push(" widgetConfig.actionParsers = ["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ];")), t.push(""), n != null && n.actionHandlers ? (t.push(" // Action handlers (custom merged with defaults)"), t.push(` var customHandlers = ${n.actionHandlers};`), t.push(" widgetConfig.actionHandlers = customHandlers.concat(["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${O}`), 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(` ${O}`), t.push(" ];")), t.push(""), n != null && n.requestMiddleware ? (t.push(" // Request middleware (custom merged with DOM context)"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(` var customResult = (${n.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(""), n != null && n.postprocessMessage ? t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`) : (t.push(" // Markdown postprocessor"), t.push(" widgetConfig.postprocessMessage = function(ctx) {"), t.push(" return agentWidget.markdownPostprocessor(ctx.text);"), t.push(" };")), t.push(""), (n != null && n.onFeedback || n != null && n.onCopy) && (t.push(" // Message action callbacks"), t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"), n != null && n.onFeedback && t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`), n != null && n.onCopy && t.push(` widgetConfig.messageActions.onCopy = ${n.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: '${g(r)}',`, " useShadowDom: false,", ...r != null && r.windowKey ? [` windowKey: '${r.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(`
65195
+ return n != null && n.getHeaders && (t.push(` widgetConfig.getHeaders = ${n.getHeaders};`), t.push("")), n != null && n.contextProviders && (t.push(` widgetConfig.contextProviders = ${n.contextProviders};`), t.push("")), n != null && n.streamParser ? t.push(` widgetConfig.streamParser = ${n.streamParser};`) : (t.push(" // Flexible JSON stream parser for handling structured actions"), t.push(" widgetConfig.streamParser = function() {"), t.push(` return agentWidget.createFlexibleJsonStreamParser(${T});`), t.push(" };")), t.push(""), n != null && n.actionParsers ? (t.push(" // Action parsers (custom merged with defaults)"), t.push(` var customParsers = ${n.actionParsers};`), t.push(" widgetConfig.actionParsers = customParsers.concat(["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ]);")) : (t.push(" // Action parsers to detect JSON actions in responses"), t.push(" widgetConfig.actionParsers = ["), t.push(" agentWidget.defaultJsonActionParser,"), t.push(` ${A}`), t.push(" ];")), t.push(""), n != null && n.actionHandlers ? (t.push(" // Action handlers (custom merged with defaults)"), t.push(` var customHandlers = ${n.actionHandlers};`), t.push(" widgetConfig.actionHandlers = customHandlers.concat(["), t.push(" agentWidget.defaultActionHandlers.message,"), t.push(" agentWidget.defaultActionHandlers.messageAndClick,"), t.push(` ${O}`), 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(` ${O}`), t.push(" ];")), t.push(""), n != null && n.requestMiddleware ? (t.push(" // Request middleware (custom merged with DOM context)"), t.push(" widgetConfig.requestMiddleware = function(ctx) {"), t.push(` var customResult = (${n.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(""), n != null && n.postprocessMessage ? t.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`) : (t.push(" // Markdown postprocessor"), t.push(" widgetConfig.postprocessMessage = function(ctx) {"), t.push(" return agentWidget.markdownPostprocessor(ctx.text);"), t.push(" };")), t.push(""), (n != null && n.onFeedback || n != null && n.onCopy) && (t.push(" // Message action callbacks"), t.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"), n != null && n.onFeedback && t.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`), n != null && n.onCopy && t.push(` widgetConfig.messageActions.onCopy = ${n.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: '${g(r)}',`, " useShadowDom: false,", ...r != null && r.windowKey ? [` windowKey: '${r.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(`
65193
65196
  `);
65194
65197
  }
65195
65198
 
@@ -65229,7 +65232,7 @@ function buildWidgetConfig(input) {
65229
65232
  function generatePersonaInitSnippet(input, personaFormat) {
65230
65233
  const widgetConfig = buildWidgetConfig(input);
65231
65234
  const target = input.targetSelector?.trim();
65232
- return I(
65235
+ return R(
65233
65236
  widgetConfig,
65234
65237
  personaFormat,
65235
65238
  target ? { target } : void 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runtypelabs/cli",
3
- "version": "2.22.11",
3
+ "version": "2.22.12",
4
4
  "description": "Command-line interface for Runtype AI platform",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -28,7 +28,7 @@
28
28
  "@runtypelabs/terminal-animations": "0.2.1"
29
29
  },
30
30
  "devDependencies": {
31
- "@runtypelabs/persona": "4.2.0",
31
+ "@runtypelabs/persona": "4.3.1",
32
32
  "@types/express": "^5.0.6",
33
33
  "@types/micromatch": "^4.0.9",
34
34
  "@types/node": "^25.3.3",
@@ -39,7 +39,7 @@
39
39
  "tsx": "^4.7.1",
40
40
  "typescript": "^5.3.3",
41
41
  "vitest": "^4.1.0",
42
- "@runtypelabs/shared": "1.41.2"
42
+ "@runtypelabs/shared": "1.42.1"
43
43
  },
44
44
  "engines": {
45
45
  "node": ">=22.0.0"