@xapp/chat-widget 1.85.1 → 1.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- import require$$1, { useCallback, useState, useRef, useEffect, createContext, useContext, useMemo, memo, useLayoutEffect } from 'react';
1
+ import require$$1, { useCallback, useState, useEffect, useRef, createContext, useContext, useMemo, memo, useLayoutEffect } from 'react';
2
2
  export { default as React } from 'react';
3
3
  import require$$0, { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
4
  import { useSelector, useDispatch, Provider } from 'react-redux';
@@ -13,7 +13,6 @@ var lib = {};
13
13
 
14
14
  var ActionBar$1 = {};
15
15
 
16
- /*! Copyright (c) 2021, XAPPmedia */
17
16
  Object.defineProperty(ActionBar$1, "__esModule", { value: true });
18
17
  ActionBar$1.isActionBarChatButton = isActionBarChatButton;
19
18
  ActionBar$1.isActionBarFormButton = isActionBarFormButton;
@@ -304,12 +303,99 @@ var ActionBarButton = function (_a) {
304
303
  return (jsxs("button", { className: buttonClassName, onClick: handleClick, "aria-label": ariaLabel, "aria-pressed": isActive, tabIndex: tabIndex, children: [jsx(ActionBarIcon, { type: button.type, icon: button.icon, iconUrl: button.iconUrl, className: "xapp-action-bar__icon" }), button.label && (jsx("span", { className: "xapp-action-bar__label", children: button.label }))] }));
305
304
  };
306
305
 
306
+ /**
307
+ * CTA banner for ActionBar - a full-width rectangular banner that appears
308
+ * above the action bar to prompt users to engage with chat.
309
+ */
310
+ var ActionBarCta = function (_a) {
311
+ var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
312
+ var config = _a.config, isMobile = _a.isMobile, onClick = _a.onClick, onDismiss = _a.onDismiss, hasUserInteracted = _a.hasUserInteracted;
313
+ var _m = useState(false), isVisible = _m[0], setIsVisible = _m[1];
314
+ var _o = useState(false), isAnimating = _o[0], setIsAnimating = _o[1];
315
+ var _p = useState(false), isDismissed = _p[0], setIsDismissed = _p[1];
316
+ var message = isMobile && ((_b = config.mobile) === null || _b === void 0 ? void 0 : _b.message) ? config.mobile.message : config.message;
317
+ var delay = isMobile && ((_c = config.mobile) === null || _c === void 0 ? void 0 : _c.delay) !== undefined ? config.mobile.delay : ((_d = config.delay) !== null && _d !== void 0 ? _d : 0);
318
+ var timeout = isMobile && ((_e = config.mobile) === null || _e === void 0 ? void 0 : _e.timeout) !== undefined ? config.mobile.timeout : config.timeout;
319
+ var animation = isMobile && ((_f = config.mobile) === null || _f === void 0 ? void 0 : _f.animation) ? config.mobile.animation : config.animation;
320
+ var animationDelay = isMobile && ((_g = config.mobile) === null || _g === void 0 ? void 0 : _g.animationDelay) !== undefined
321
+ ? config.mobile.animationDelay
322
+ : ((_h = config.animationDelay) !== null && _h !== void 0 ? _h : delay);
323
+ var animationTimeout = isMobile && ((_j = config.mobile) === null || _j === void 0 ? void 0 : _j.animationTimeout) !== undefined
324
+ ? config.mobile.animationTimeout
325
+ : config.animationTimeout;
326
+ var dismissible = isMobile && ((_k = config.mobile) === null || _k === void 0 ? void 0 : _k.dismissible) !== undefined
327
+ ? config.mobile.dismissible
328
+ : ((_l = config.dismissible) !== null && _l !== void 0 ? _l : true);
329
+ // Show CTA after delay
330
+ useEffect(function () {
331
+ if (!message || hasUserInteracted || isDismissed) {
332
+ setIsVisible(false);
333
+ return undefined;
334
+ }
335
+ var showTimer = setTimeout(function () {
336
+ setIsVisible(true);
337
+ }, delay);
338
+ return function () { return clearTimeout(showTimer); };
339
+ }, [message, delay, hasUserInteracted, isDismissed]);
340
+ // Hide CTA after timeout
341
+ useEffect(function () {
342
+ if (!isVisible || !timeout) {
343
+ return undefined;
344
+ }
345
+ var hideTimer = setTimeout(function () {
346
+ setIsVisible(false);
347
+ }, timeout);
348
+ return function () { return clearTimeout(hideTimer); };
349
+ }, [isVisible, timeout]);
350
+ // Start animation after animationDelay
351
+ useEffect(function () {
352
+ if (!animation || hasUserInteracted || isDismissed) {
353
+ setIsAnimating(false);
354
+ return undefined;
355
+ }
356
+ var animateTimer = setTimeout(function () {
357
+ setIsAnimating(true);
358
+ }, animationDelay);
359
+ return function () { return clearTimeout(animateTimer); };
360
+ }, [animation, animationDelay, hasUserInteracted, isDismissed]);
361
+ // Stop animation after animationTimeout
362
+ useEffect(function () {
363
+ if (!isAnimating || !animationTimeout) {
364
+ return undefined;
365
+ }
366
+ var stopTimer = setTimeout(function () {
367
+ setIsAnimating(false);
368
+ }, animationTimeout);
369
+ return function () { return clearTimeout(stopTimer); };
370
+ }, [isAnimating, animationTimeout]);
371
+ var handleClick = function () {
372
+ onClick();
373
+ setIsVisible(false);
374
+ };
375
+ var handleDismiss = function (e) {
376
+ e.stopPropagation();
377
+ setIsDismissed(true);
378
+ setIsVisible(false);
379
+ onDismiss();
380
+ };
381
+ if (!isVisible || !message) {
382
+ return null;
383
+ }
384
+ var animationClass = isAnimating && animation ? "xapp-action-bar-cta--".concat(animation) : "";
385
+ return (jsxs("div", { className: "xapp-action-bar-cta ".concat(animationClass), onClick: handleClick, role: "button", tabIndex: 0, "aria-label": message, onKeyDown: function (e) {
386
+ if (e.key === "Enter" || e.key === " ") {
387
+ e.preventDefault();
388
+ handleClick();
389
+ }
390
+ }, children: [jsx("span", { className: "xapp-action-bar-cta__message", children: message }), dismissible && (jsx("button", { className: "xapp-action-bar-cta__dismiss", onClick: handleDismiss, "aria-label": "Dismiss", type: "button", children: jsx("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: jsx("path", { d: "M13 1L1 13M1 1L13 13", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) }) }))] }));
391
+ };
392
+
307
393
  var DEFAULT_MOBILE_BREAKPOINT = 768;
308
394
  var RESIZE_DEBOUNCE_MS = 150;
309
395
  var ActionBar = function (_a) {
310
- var _b, _c;
311
- var config = _a.config, visible = _a.visible, chatDisabled = _a.chatDisabled, onChatClick = _a.onChatClick, onChatMinimize = _a.onChatMinimize, onFormClick = _a.onFormClick;
312
- var _d = useState(false), isMobile = _d[0], setIsMobile = _d[1];
396
+ var _b, _c, _d;
397
+ var config = _a.config, visible = _a.visible, chatDisabled = _a.chatDisabled, _e = _a.hasUserInteracted, hasUserInteracted = _e === void 0 ? false : _e, onChatClick = _a.onChatClick, onChatMinimize = _a.onChatMinimize, onFormClick = _a.onFormClick, onCtaDismiss = _a.onCtaDismiss;
398
+ var _f = useState(false), isMobile = _f[0], setIsMobile = _f[1];
313
399
  var mobileBreakpoint = (_b = config.mobileBreakpoint) !== null && _b !== void 0 ? _b : DEFAULT_MOBILE_BREAKPOINT;
314
400
  var position = (_c = config.position) !== null && _c !== void 0 ? _c : "right";
315
401
  var resizeTimeoutRef = useRef(null);
@@ -345,7 +431,19 @@ var ActionBar = function (_a) {
345
431
  ]
346
432
  .filter(Boolean)
347
433
  .join(" ");
348
- return (jsx("div", { className: classNames, role: "toolbar", "aria-label": "Chat actions", children: filteredButtons.map(function (button) { return (jsx(ActionBarButton, { button: button, chatActive: visible, onChatClick: onChatClick, onChatMinimize: onChatMinimize, onFormClick: onFormClick, isMobile: isMobile }, button.id)); }) }));
434
+ // Determine if CTA should be shown:
435
+ // - Must have CTA config with a message
436
+ // - Chat must not be visible (user hasn't opened it)
437
+ // - Chat must not be disabled
438
+ var hasChatButton = config.buttons.some(lib.isActionBarChatButton);
439
+ var showCta = ((_d = config.cta) === null || _d === void 0 ? void 0 : _d.message) && !visible && !chatDisabled && hasChatButton;
440
+ var handleCtaClick = function () {
441
+ onChatClick();
442
+ };
443
+ var handleCtaDismiss = function () {
444
+ onCtaDismiss === null || onCtaDismiss === void 0 ? void 0 : onCtaDismiss();
445
+ };
446
+ return (jsxs("div", { className: classNames, role: "toolbar", "aria-label": "Chat actions", children: [showCta && (jsx("div", { className: "xapp-action-bar-cta-wrapper", children: jsx(ActionBarCta, { config: config.cta, isMobile: isMobile, onClick: handleCtaClick, onDismiss: handleCtaDismiss, hasUserInteracted: hasUserInteracted }) })), jsx("div", { className: "xapp-action-bar__buttons", children: filteredButtons.map(function (button) { return (jsx(ActionBarButton, { button: button, chatActive: visible, onChatClick: onChatClick, onChatMinimize: onChatMinimize, onFormClick: onFormClick, isMobile: isMobile }, button.id)); }) })] }));
349
447
  };
350
448
 
351
449
  /**
@@ -978,14 +1076,16 @@ function getServerConfig(env) {
978
1076
  }
979
1077
  function useServerConfig(env, nonce) {
980
1078
  var connection = getServerConfig(env);
981
- var accountKey = connection.accountKey, serverUrl = connection.serverUrl, type = connection.type, timeout = connection.timeout;
1079
+ var accountKey = connection.accountKey, serverUrl = connection.serverUrl, type = connection.type, timeout = connection.timeout, backgroundSleepDelay = connection.backgroundSleepDelay, mcp = connection.mcp;
982
1080
  return useMemo(function () { return ({
983
1081
  accountKey: accountKey,
984
1082
  serverUrl: serverUrl,
985
1083
  timeout: timeout,
986
1084
  type: type,
987
1085
  nonce: nonce,
988
- }); }, [accountKey, serverUrl, timeout, type, nonce]);
1086
+ backgroundSleepDelay: backgroundSleepDelay,
1087
+ mcp: mcp,
1088
+ }); }, [accountKey, serverUrl, timeout, type, nonce, backgroundSleepDelay, mcp]);
989
1089
  }
990
1090
  function useConnectionInfo(env) {
991
1091
  var nonce = useSelector(function (state) { return state.connection.nonce; });
@@ -994,7 +1094,7 @@ function useConnectionInfo(env) {
994
1094
  }
995
1095
 
996
1096
  var Avatar = function (props) {
997
- var _a, _b;
1097
+ var _a, _b, _c, _d, _e;
998
1098
  var style = {};
999
1099
  var child;
1000
1100
  var entity = props.entity;
@@ -1017,7 +1117,9 @@ var Avatar = function (props) {
1017
1117
  child = getVisitorSvg();
1018
1118
  }
1019
1119
  var hasImage = !!style.backgroundImage || !!child;
1020
- return (jsx("div", { className: "avatar ".concat(agentAva ? "avatar--agent" : "avatar--visitor", " ").concat(!hasImage ? "avatar--empty" : ""), style: style, title: entity ? entity.display_name : "Agent", children: child }));
1120
+ // Show AI badge if configured and the entity is an AI
1121
+ var showAiBadge = ((_e = (_d = (_c = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _c === void 0 ? void 0 : _c.connection) === null || _d === void 0 ? void 0 : _d.mcp) === null || _e === void 0 ? void 0 : _e.showAiBadge) && (entity === null || entity === void 0 ? void 0 : entity.isAI);
1122
+ return (jsxs("div", { className: "avatar ".concat(agentAva ? "avatar--agent" : "avatar--visitor", " ").concat(!hasImage ? "avatar--empty" : ""), style: style, title: entity ? entity.display_name : "Agent", children: [child, showAiBadge && jsx("span", { className: "avatar__ai-badge", children: "AI" })] }));
1021
1123
  };
1022
1124
  /**
1023
1125
  * Generates an SVG based on the
@@ -2602,236 +2704,231 @@ var parseSuggestionsResponse_1 = parseSuggestionsResponse;
2602
2704
  var useSuggestionsFetch_1 = useSuggestionsFetch$1;
2603
2705
  var uuid_1 = uuid;
2604
2706
 
2605
- /**
2606
- * Sends a POST to your STENTOR based server.
2607
- *
2608
- * @param data
2609
- * @param url
2610
- * @param key
2611
- * @param signal
2612
- * @returns
2613
- */
2614
- function postMessageToStentor(data, url, key, signal) {
2615
- return __awaiter$1(this, void 0, void 0, function () {
2616
- var body, response;
2617
- return __generator$1(this, function (_a) {
2618
- switch (_a.label) {
2619
- case 0:
2620
- body = JSON.stringify(data);
2621
- log("URL: ".concat(url));
2622
- log("BODY: ".concat(body));
2623
- return [4 /*yield*/, fetch(url, {
2624
- method: "POST",
2625
- headers: {
2626
- "Content-Type": "application/json",
2627
- "Authorization": "Bearer ".concat(key),
2628
- },
2629
- body: body,
2630
- mode: "cors",
2631
- signal: signal
2632
- })];
2633
- case 1:
2634
- response = _a.sent();
2635
- if (!response.ok) {
2636
- throw new Error("Status ".concat(response.status, ", Text: ").concat(response.statusText));
2637
- }
2638
- return [2 /*return*/, response.json()];
2639
- }
2640
- });
2641
- });
2642
- }
2707
+ var cjs = {};
2643
2708
 
2644
- function convertFromListDisplay(list) {
2645
- return {
2646
- type: list.type,
2647
- title: list.title,
2648
- items: list.items.map(function (item) {
2649
- var _a, _b;
2650
- var responseItem = {
2651
- title: item.title,
2652
- subTitle: item.description,
2653
- token: item.token,
2654
- url: item.url,
2655
- hideUrl: item.hideUrl,
2656
- imageUrl: (_a = item.image) === null || _a === void 0 ? void 0 : _a.url,
2657
- imageActionUrl: (_b = item.image) === null || _b === void 0 ? void 0 : _b.imageActionUrl
2658
- };
2659
- // TODO: Remove any when the buttons are defined on the list (ListButton - title + openUrlAction)
2660
- var itemButtons = item.buttons;
2661
- if (itemButtons && itemButtons.length > 0) {
2662
- responseItem.buttons = itemButtons.map(function (button) { return ({
2663
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2664
- actionUrl: button.openUrlAction,
2665
- label: button.title
2666
- }); });
2667
- }
2668
- return responseItem;
2669
- })
2670
- };
2671
- }
2672
- function convertToListDisplay(list) {
2673
- return {
2674
- type: list.type,
2675
- title: list.title,
2676
- items: (list.items || []).map(function (item) {
2677
- var responseItem = {
2678
- title: item.title,
2679
- description: item.subTitle,
2680
- token: item.token,
2681
- url: item.url,
2682
- hideUrl: item.hideUrl,
2683
- image: {
2684
- url: item.imageUrl,
2685
- imageActionUrl: item.imageActionUrl,
2686
- accessibilityText: ""
2687
- }
2688
- };
2689
- // TODO: Remove any when the buttons are defined on the list (ListButton - title + openUrlAction)
2690
- var itemButtons = item.buttons;
2691
- if (itemButtons && itemButtons.length > 0) {
2692
- responseItem.buttons = itemButtons.map(function (button) { return ({
2693
- openUrlAction: button.actionUrl,
2694
- title: button.label
2695
- }); });
2696
- }
2697
- return responseItem;
2698
- })
2699
- };
2700
- }
2701
- function convertFromCardDisplay(card) {
2702
- return {
2703
- content: card.content,
2704
- imageUrl: card.smallImageUrl,
2705
- title: card.title,
2706
- imageActionUrl: card === null || card === void 0 ? void 0 : card.imageActionUrl,
2707
- buttons: card.buttons ? card.buttons.map(function (button) { return ({
2708
- actionUrl: button.openUrlAction,
2709
- label: button.title
2710
- }); }) : undefined
2711
- };
2712
- }
2713
- function getOutput(value) {
2714
- if (value) {
2715
- if (typeof value === "string") {
2716
- return {
2717
- displayText: value
2718
- };
2719
- }
2720
- else {
2721
- return value;
2722
- }
2723
- }
2724
- return undefined;
2725
- }
2726
- /**
2727
- * Converts a Stentor Response to a ChatMessageRequest
2728
- *
2729
- * @param botResponse
2730
- * @param now
2731
- * @returns
2732
- */
2733
- function responseToMessage(botResponse, now) {
2734
- var _a, _b, _c, _d, _e;
2735
- if (now === void 0) { now = new Date().getTime(); }
2736
- var responseMessage;
2737
- if (!botResponse) {
2738
- return responseMessage;
2739
- }
2740
- var text;
2741
- var html;
2742
- var endSession;
2743
- var outputSpeech = getOutput(botResponse.outputSpeech);
2744
- var reprompt = getOutput(botResponse.reprompt);
2745
- if (outputSpeech) {
2746
- text = outputSpeech.displayText;
2747
- html = outputSpeech.html;
2748
- }
2749
- if (botResponse.system === "TRANSFER_CALL") {
2750
- responseMessage = {
2751
- type: "handOff",
2752
- timestamp: now,
2753
- handoffMessage: text,
2754
- handoffTarget: (_a = botResponse === null || botResponse === void 0 ? void 0 : botResponse.data) === null || _a === void 0 ? void 0 : _a.transferPhoneNumber,
2755
- endSession: false,
2756
- user: undefined
2757
- };
2758
- }
2759
- else if ((_b = botResponse.system) === null || _b === void 0 ? void 0 : _b.startsWith("PERMISSION_")) {
2760
- responseMessage = getPermissionResponse(botResponse, now);
2761
- }
2762
- else {
2763
- endSession = !reprompt || !(reprompt.displayText || reprompt.ssml);
2764
- responseMessage = {
2765
- type: "msg",
2766
- timestamp: now,
2767
- msg: {
2768
- displays: botResponse.displays,
2769
- context: (_d = (_c = botResponse.context) === null || _c === void 0 ? void 0 : _c.active) === null || _d === void 0 ? void 0 : _d.map(function (ctx) { return ctx.name; })
2770
- },
2771
- endSession: endSession,
2772
- user: undefined
2773
- };
2774
- if (text && !html) {
2775
- responseMessage.msg = __assign(__assign({}, responseMessage.msg), { text: text });
2776
- }
2777
- if (html) {
2778
- responseMessage.msg = __assign(__assign({}, responseMessage.msg), { html: html });
2779
- }
2780
- if ((_e = outputSpeech === null || outputSpeech === void 0 ? void 0 : outputSpeech.suggestions) === null || _e === void 0 ? void 0 : _e.length) {
2781
- responseMessage.msg.options = outputSpeech.suggestions.map(function (suggestion) {
2782
- if (typeof suggestion === "string") {
2783
- // Simple chips (strings)
2784
- return suggestion;
2785
- }
2786
- else {
2787
- // "call out" chips
2788
- return {
2789
- label: suggestion.title,
2790
- actionUrl: suggestion.url
2791
- };
2792
- }
2793
- });
2794
- }
2795
- }
2796
- return responseMessage;
2797
- }
2798
- function getPermissionRequestType(type) {
2799
- switch (type) {
2800
- case "PERMISSION_EMAIL":
2801
- return "EMAIL";
2802
- case "PERMISSION_LOCATION_PRECISE":
2803
- return "LOCATION_PRECISE";
2804
- default:
2805
- throw new Error("Unsupported permission: ".concat(type));
2806
- }
2807
- }
2808
- function getPermissionResponse(botResponse, now) {
2809
- var _a;
2810
- var type = getPermissionRequestType(botResponse.system);
2811
- var outputSpeech = getOutput(botResponse.outputSpeech);
2812
- var permissionPrimerAccepted = botResponse.data.permissionPrimerAccepted;
2813
- var permissionDenied = botResponse.data.permissionDenied;
2814
- return {
2815
- type: "permissionRequest",
2816
- timestamp: now,
2817
- msg: {
2818
- text: (_a = outputSpeech === null || outputSpeech === void 0 ? void 0 : outputSpeech.displayText) !== null && _a !== void 0 ? _a : "".concat(botResponse.data.permissionRequestTTSContext),
2819
- permissionRequest: {
2820
- time: now,
2821
- type: type,
2822
- approve: typeof permissionPrimerAccepted === "object" ? responseToMessage({
2823
- outputSpeech: permissionPrimerAccepted
2824
- }).msg : undefined,
2825
- deny: typeof permissionDenied === "object" ? responseToMessage({
2826
- outputSpeech: permissionDenied
2827
- }).msg : undefined
2828
- }
2829
- },
2830
- endSession: false,
2831
- user: undefined //todo: set
2832
- };
2709
+ var fetch$1 = {};
2710
+
2711
+ var parse$3 = {};
2712
+
2713
+ Object.defineProperty(parse$3, "__esModule", { value: true });
2714
+ parse$3.getMessages = parse$3.getLines = parse$3.getBytes = void 0;
2715
+ async function getBytes(stream, onChunk) {
2716
+ const reader = stream.getReader();
2717
+ let result;
2718
+ while (!(result = await reader.read()).done) {
2719
+ onChunk(result.value);
2720
+ }
2721
+ }
2722
+ parse$3.getBytes = getBytes;
2723
+ function getLines(onLine) {
2724
+ let buffer;
2725
+ let position;
2726
+ let fieldLength;
2727
+ let discardTrailingNewline = false;
2728
+ return function onChunk(arr) {
2729
+ if (buffer === undefined) {
2730
+ buffer = arr;
2731
+ position = 0;
2732
+ fieldLength = -1;
2733
+ }
2734
+ else {
2735
+ buffer = concat(buffer, arr);
2736
+ }
2737
+ const bufLength = buffer.length;
2738
+ let lineStart = 0;
2739
+ while (position < bufLength) {
2740
+ if (discardTrailingNewline) {
2741
+ if (buffer[position] === 10) {
2742
+ lineStart = ++position;
2743
+ }
2744
+ discardTrailingNewline = false;
2745
+ }
2746
+ let lineEnd = -1;
2747
+ for (; position < bufLength && lineEnd === -1; ++position) {
2748
+ switch (buffer[position]) {
2749
+ case 58:
2750
+ if (fieldLength === -1) {
2751
+ fieldLength = position - lineStart;
2752
+ }
2753
+ break;
2754
+ case 13:
2755
+ discardTrailingNewline = true;
2756
+ case 10:
2757
+ lineEnd = position;
2758
+ break;
2759
+ }
2760
+ }
2761
+ if (lineEnd === -1) {
2762
+ break;
2763
+ }
2764
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
2765
+ lineStart = position;
2766
+ fieldLength = -1;
2767
+ }
2768
+ if (lineStart === bufLength) {
2769
+ buffer = undefined;
2770
+ }
2771
+ else if (lineStart !== 0) {
2772
+ buffer = buffer.subarray(lineStart);
2773
+ position -= lineStart;
2774
+ }
2775
+ };
2776
+ }
2777
+ parse$3.getLines = getLines;
2778
+ function getMessages(onId, onRetry, onMessage) {
2779
+ let message = newMessage();
2780
+ const decoder = new TextDecoder();
2781
+ return function onLine(line, fieldLength) {
2782
+ if (line.length === 0) {
2783
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
2784
+ message = newMessage();
2785
+ }
2786
+ else if (fieldLength > 0) {
2787
+ const field = decoder.decode(line.subarray(0, fieldLength));
2788
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
2789
+ const value = decoder.decode(line.subarray(valueOffset));
2790
+ switch (field) {
2791
+ case 'data':
2792
+ message.data = message.data
2793
+ ? message.data + '\n' + value
2794
+ : value;
2795
+ break;
2796
+ case 'event':
2797
+ message.event = value;
2798
+ break;
2799
+ case 'id':
2800
+ onId(message.id = value);
2801
+ break;
2802
+ case 'retry':
2803
+ const retry = parseInt(value, 10);
2804
+ if (!isNaN(retry)) {
2805
+ onRetry(message.retry = retry);
2806
+ }
2807
+ break;
2808
+ }
2809
+ }
2810
+ };
2811
+ }
2812
+ parse$3.getMessages = getMessages;
2813
+ function concat(a, b) {
2814
+ const res = new Uint8Array(a.length + b.length);
2815
+ res.set(a);
2816
+ res.set(b, a.length);
2817
+ return res;
2818
+ }
2819
+ function newMessage() {
2820
+ return {
2821
+ data: '',
2822
+ event: '',
2823
+ id: '',
2824
+ retry: undefined,
2825
+ };
2833
2826
  }
2834
2827
 
2828
+ (function (exports$1) {
2829
+ var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
2830
+ var t = {};
2831
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2832
+ t[p] = s[p];
2833
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
2834
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2835
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2836
+ t[p[i]] = s[p[i]];
2837
+ }
2838
+ return t;
2839
+ };
2840
+ Object.defineProperty(exports$1, "__esModule", { value: true });
2841
+ exports$1.fetchEventSource = exports$1.EventStreamContentType = void 0;
2842
+ const parse_1 = parse$3;
2843
+ exports$1.EventStreamContentType = 'text/event-stream';
2844
+ const DefaultRetryInterval = 1000;
2845
+ const LastEventId = 'last-event-id';
2846
+ function fetchEventSource(input, _a) {
2847
+ var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a, rest = __rest(_a, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
2848
+ return new Promise((resolve, reject) => {
2849
+ const headers = Object.assign({}, inputHeaders);
2850
+ if (!headers.accept) {
2851
+ headers.accept = exports$1.EventStreamContentType;
2852
+ }
2853
+ let curRequestController;
2854
+ function onVisibilityChange() {
2855
+ curRequestController.abort();
2856
+ if (!document.hidden) {
2857
+ create();
2858
+ }
2859
+ }
2860
+ if (!openWhenHidden) {
2861
+ document.addEventListener('visibilitychange', onVisibilityChange);
2862
+ }
2863
+ let retryInterval = DefaultRetryInterval;
2864
+ let retryTimer = 0;
2865
+ function dispose() {
2866
+ document.removeEventListener('visibilitychange', onVisibilityChange);
2867
+ window.clearTimeout(retryTimer);
2868
+ curRequestController.abort();
2869
+ }
2870
+ inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener('abort', () => {
2871
+ dispose();
2872
+ resolve();
2873
+ });
2874
+ const fetch = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
2875
+ const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
2876
+ async function create() {
2877
+ var _a;
2878
+ curRequestController = new AbortController();
2879
+ try {
2880
+ const response = await fetch(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
2881
+ await onopen(response);
2882
+ await parse_1.getBytes(response.body, parse_1.getLines(parse_1.getMessages(id => {
2883
+ if (id) {
2884
+ headers[LastEventId] = id;
2885
+ }
2886
+ else {
2887
+ delete headers[LastEventId];
2888
+ }
2889
+ }, retry => {
2890
+ retryInterval = retry;
2891
+ }, onmessage)));
2892
+ onclose === null || onclose === void 0 ? void 0 : onclose();
2893
+ dispose();
2894
+ resolve();
2895
+ }
2896
+ catch (err) {
2897
+ if (!curRequestController.signal.aborted) {
2898
+ try {
2899
+ const interval = (_a = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a !== void 0 ? _a : retryInterval;
2900
+ window.clearTimeout(retryTimer);
2901
+ retryTimer = window.setTimeout(create, interval);
2902
+ }
2903
+ catch (innerErr) {
2904
+ dispose();
2905
+ reject(innerErr);
2906
+ }
2907
+ }
2908
+ }
2909
+ }
2910
+ create();
2911
+ });
2912
+ }
2913
+ exports$1.fetchEventSource = fetchEventSource;
2914
+ function defaultOnOpen(response) {
2915
+ const contentType = response.headers.get('content-type');
2916
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(exports$1.EventStreamContentType))) {
2917
+ throw new Error(`Expected content-type to be ${exports$1.EventStreamContentType}, Actual: ${contentType}`);
2918
+ }
2919
+ }
2920
+
2921
+ } (fetch$1));
2922
+
2923
+ (function (exports$1) {
2924
+ Object.defineProperty(exports$1, "__esModule", { value: true });
2925
+ exports$1.EventStreamContentType = exports$1.fetchEventSource = void 0;
2926
+ var fetch_1 = fetch$1;
2927
+ Object.defineProperty(exports$1, "fetchEventSource", { enumerable: true, get: function () { return fetch_1.fetchEventSource; } });
2928
+ Object.defineProperty(exports$1, "EventStreamContentType", { enumerable: true, get: function () { return fetch_1.EventStreamContentType; } });
2929
+
2930
+ } (cjs));
2931
+
2835
2932
  /**
2836
2933
  * Default configuration messages
2837
2934
  * @returns
@@ -2878,6 +2975,1416 @@ function setSessionId(sessionId) {
2878
2975
  };
2879
2976
  }
2880
2977
 
2978
+ // Endpoint path constants
2979
+ var HOMEOWNER_ENDPOINT_PATH = "/chat/stream";
2980
+ var BUSINESS_OWNER_ENDPOINT_PATH = "/api/chat/stream";
2981
+ // Default retry configuration for MCP connections
2982
+ var DEFAULT_MCP_RETRY_CONFIG = [
2983
+ { retry: 0, delay: 0, text: "" }, // Initial attempt (silent)
2984
+ { retry: 1, delay: 3, text: "Having trouble connecting. Retrying in ${sec} seconds..." },
2985
+ { retry: 2, delay: 5, text: "Still having trouble. Retrying in ${sec} seconds..." },
2986
+ { retry: 0, delay: 0, text: "Unable to connect to the assistant. Please try again later." }, // Final failure
2987
+ ];
2988
+ // Streaming throttle configuration
2989
+ // Average reading speed is ~250 words/min (~20 chars/sec). We go slightly faster.
2990
+ var STREAM_CHARS_PER_TICK = 3; // Characters to display per tick
2991
+ var STREAM_TICK_INTERVAL_MS = 30; // Milliseconds between ticks (~100 chars/sec)
2992
+ /**
2993
+ * Storage keys for MCP session persistence.
2994
+ * Uses localStorage directly (not Redux) for MCP-specific data.
2995
+ */
2996
+ var MCP_STORAGE_KEYS = {
2997
+ USER_ID: "xapp_mcp_userId",
2998
+ SESSION_ID: "xapp_mcp_sessionId",
2999
+ };
3000
+ /**
3001
+ * Gets the platform string, preferring the modern userAgentData API.
3002
+ * Falls back to the deprecated navigator.platform for older browsers.
3003
+ */
3004
+ function getPlatform() {
3005
+ // Modern API (Chrome 90+, Edge 90+, Opera 76+)
3006
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
3007
+ var userAgentData = navigator.userAgentData;
3008
+ if (userAgentData === null || userAgentData === void 0 ? void 0 : userAgentData.platform) {
3009
+ return userAgentData.platform;
3010
+ }
3011
+ // Fallback for older browsers (deprecated but widely supported)
3012
+ return navigator.platform || undefined;
3013
+ }
3014
+ /**
3015
+ * Collects non-invasive device/browser fingerprint data.
3016
+ * This helps the server identify returning users without requiring login.
3017
+ *
3018
+ * PRIVACY NOTE: Only basic, non-identifying browser characteristics are collected.
3019
+ * This data cannot be used to personally identify individual users.
3020
+ */
3021
+ function getFingerprint() {
3022
+ if (typeof window === "undefined") {
3023
+ return {};
3024
+ }
3025
+ return {
3026
+ userAgent: navigator.userAgent,
3027
+ language: navigator.language,
3028
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
3029
+ screenResolution: "".concat(window.screen.width, "x").concat(window.screen.height),
3030
+ platform: getPlatform(),
3031
+ colorDepth: window.screen.colorDepth,
3032
+ touchSupport: "ontouchstart" in window || navigator.maxTouchPoints > 0,
3033
+ };
3034
+ }
3035
+ /**
3036
+ * Retrieves stored MCP identity from localStorage.
3037
+ */
3038
+ function getStoredIdentity() {
3039
+ if (typeof window === "undefined" || !window.localStorage) {
3040
+ return {};
3041
+ }
3042
+ try {
3043
+ return {
3044
+ userId: localStorage.getItem(MCP_STORAGE_KEYS.USER_ID) || undefined,
3045
+ sessionId: localStorage.getItem(MCP_STORAGE_KEYS.SESSION_ID) || undefined,
3046
+ };
3047
+ }
3048
+ catch (_a) {
3049
+ // localStorage may be unavailable (private browsing, etc.)
3050
+ return {};
3051
+ }
3052
+ }
3053
+ /**
3054
+ * Stores MCP identity to localStorage.
3055
+ */
3056
+ function storeIdentity(userId, sessionId) {
3057
+ if (typeof window === "undefined" || !window.localStorage) {
3058
+ return;
3059
+ }
3060
+ try {
3061
+ if (userId) {
3062
+ localStorage.setItem(MCP_STORAGE_KEYS.USER_ID, userId);
3063
+ }
3064
+ if (sessionId) {
3065
+ localStorage.setItem(MCP_STORAGE_KEYS.SESSION_ID, sessionId);
3066
+ }
3067
+ }
3068
+ catch (_a) {
3069
+ // localStorage may be unavailable
3070
+ }
3071
+ }
3072
+ /**
3073
+ * Clears stored MCP session (but preserves userId for returning user identification).
3074
+ */
3075
+ function clearStoredSession() {
3076
+ if (typeof window === "undefined" || !window.localStorage) {
3077
+ return;
3078
+ }
3079
+ try {
3080
+ localStorage.removeItem(MCP_STORAGE_KEYS.SESSION_ID);
3081
+ }
3082
+ catch (_a) {
3083
+ // localStorage may be unavailable
3084
+ }
3085
+ }
3086
+ /**
3087
+ * Gets the current page context from browser globals.
3088
+ * If an override is provided, uses that instead (useful for testing).
3089
+ *
3090
+ * PRIVACY NOTE: Query strings are stripped from URLs by default as they
3091
+ * may contain sensitive data (tokens, PII). Only origin + pathname are sent.
3092
+ */
3093
+ function getPageContext(override) {
3094
+ var localTime = new Date().toISOString();
3095
+ // If override provided, merge with defaults (override wins)
3096
+ // Overrides are typically for testing and may include full URLs
3097
+ if (override && Object.keys(override).length > 0) {
3098
+ log("[getPageContext] Using override: ".concat(JSON.stringify(override)));
3099
+ return {
3100
+ url: override.url,
3101
+ path: override.path,
3102
+ title: override.title,
3103
+ referrer: override.referrer,
3104
+ localTime: localTime,
3105
+ };
3106
+ }
3107
+ if (typeof window === "undefined") {
3108
+ return { localTime: localTime };
3109
+ }
3110
+ // Strip query strings from URL for privacy (may contain tokens/PII)
3111
+ var urlWithoutQuery = window.location.origin + window.location.pathname;
3112
+ // Strip query strings from referrer as well
3113
+ var referrerWithoutQuery;
3114
+ if (document.referrer) {
3115
+ try {
3116
+ var refUrl = new URL(document.referrer);
3117
+ referrerWithoutQuery = refUrl.origin + refUrl.pathname;
3118
+ }
3119
+ catch (_a) {
3120
+ // Invalid referrer URL, skip it
3121
+ referrerWithoutQuery = undefined;
3122
+ }
3123
+ }
3124
+ return {
3125
+ url: urlWithoutQuery,
3126
+ path: window.location.pathname,
3127
+ title: document.title || undefined,
3128
+ referrer: referrerWithoutQuery,
3129
+ localTime: localTime,
3130
+ };
3131
+ }
3132
+ var MCPChat = /** @class */ (function () {
3133
+ function MCPChat(config, options) {
3134
+ this._userId = "";
3135
+ this._sessionId = "";
3136
+ this._accessToken = "";
3137
+ this._attributes = {};
3138
+ // Streaming throttle state
3139
+ this.streamBuffer = "";
3140
+ // New session initialization state
3141
+ this.isInitializingSession = false;
3142
+ // Session validation state (silent handshake - no stream dispatch)
3143
+ this.isValidatingSession = false;
3144
+ // Tool call tracking for debug mode
3145
+ this.currentToolCalls = [];
3146
+ this.config = config;
3147
+ this.options = options;
3148
+ this.configurableMessages = options === null || options === void 0 ? void 0 : options.configurableMessages;
3149
+ this.isNewSession = false;
3150
+ this.hooks = options === null || options === void 0 ? void 0 : options.hooks;
3151
+ // Validate business_owner mode requires authToken
3152
+ var mode = config.mode || "homeowner";
3153
+ if (mode === "business_owner" && !config.authToken) {
3154
+ throw new Error("authToken is required for business_owner mode");
3155
+ }
3156
+ // Load stored identity from localStorage
3157
+ var storedIdentity = getStoredIdentity();
3158
+ if (storedIdentity.userId) {
3159
+ this._userId = storedIdentity.userId;
3160
+ log("[MCPChat] Loaded stored userId: ".concat(this._userId));
3161
+ }
3162
+ if (storedIdentity.sessionId) {
3163
+ this._sessionId = storedIdentity.sessionId;
3164
+ log("[MCPChat] Loaded stored sessionId: ".concat(this._sessionId));
3165
+ }
3166
+ // Config-provided sessionId takes precedence
3167
+ if (config.sessionId) {
3168
+ this._sessionId = config.sessionId;
3169
+ }
3170
+ }
3171
+ MCPChat.prototype.init = function (dispatch) {
3172
+ this.dispatch = dispatch;
3173
+ var mode = this.config.mode || "homeowner";
3174
+ log("MCPChat initialized with mode: ".concat(mode));
3175
+ // Warn if not using HTTPS with authentication
3176
+ if (mode === "business_owner" && !this.config.serverUrl.startsWith("https://")) {
3177
+ err("WARNING: Using non-HTTPS URL with authentication tokens. This is insecure in production.");
3178
+ }
3179
+ this.setConnectionStatus("online");
3180
+ this.setAccountStatus("online");
3181
+ // Returning user with existing session - validate session silently
3182
+ // New user without session - initialize new session to get greeting
3183
+ if (this._sessionId) {
3184
+ this.validateSession();
3185
+ }
3186
+ else {
3187
+ this.initializeNewSession();
3188
+ }
3189
+ };
3190
+ /**
3191
+ * Validates an existing session with the server ("Silent Handshake").
3192
+ * Called when widget reopens with a stored sessionId.
3193
+ *
3194
+ * The server will respond with:
3195
+ * - "connected" event if session is valid
3196
+ * - "session_expired" event if session is gone (triggers initializeNewSession)
3197
+ *
3198
+ * This is lightweight - no LLM call, just a quick DB check to:
3199
+ * - Validate session before user tries to send a message
3200
+ * - Update lastActivityAt in persistent session
3201
+ * - Confirm userId is still valid
3202
+ */
3203
+ MCPChat.prototype.validateSession = function () {
3204
+ return __awaiter$1(this, void 0, void 0, function () {
3205
+ var endpoint, error_1;
3206
+ return __generator$1(this, function (_a) {
3207
+ switch (_a.label) {
3208
+ case 0:
3209
+ endpoint = this.getEndpoint();
3210
+ log("Validating existing session at ".concat(endpoint, ", sessionId: ").concat(this._sessionId));
3211
+ this.isValidatingSession = true;
3212
+ _a.label = 1;
3213
+ case 1:
3214
+ _a.trys.push([1, 3, 4, 5]);
3215
+ return [4 /*yield*/, this.performSSERequest(this.buildRequestPayload({ resumeSession: true }))];
3216
+ case 2:
3217
+ _a.sent();
3218
+ log("Session validation complete");
3219
+ return [3 /*break*/, 5];
3220
+ case 3:
3221
+ error_1 = _a.sent();
3222
+ err("Failed to validate session: ".concat(error_1));
3223
+ // If validation fails (network error, etc.), clear session and start fresh
3224
+ this._sessionId = "";
3225
+ clearStoredSession();
3226
+ this.initializeNewSession();
3227
+ return [3 /*break*/, 5];
3228
+ case 4:
3229
+ this.isValidatingSession = false;
3230
+ return [7 /*endfinally*/];
3231
+ case 5: return [2 /*return*/];
3232
+ }
3233
+ });
3234
+ });
3235
+ };
3236
+ /**
3237
+ * Builds the common request payload with identity and context.
3238
+ */
3239
+ MCPChat.prototype.buildRequestPayload = function (additionalData) {
3240
+ if (additionalData === void 0) { additionalData = {}; }
3241
+ return __assign({
3242
+ // Identity - server generates these, we just send back what we have
3243
+ userId: this._userId || undefined, sessionId: this._sessionId || undefined,
3244
+ // Fingerprint for user identification (can be disabled for privacy)
3245
+ fingerprint: this.config.disableFingerprinting ? undefined : getFingerprint(),
3246
+ // Page context
3247
+ pageContext: getPageContext(this.config.pageContextOverride) }, additionalData);
3248
+ };
3249
+ /**
3250
+ * Initializes a new session by calling the endpoint with { newSession: true }.
3251
+ * This returns a greeting message and session ID without making an LLM call.
3252
+ */
3253
+ MCPChat.prototype.initializeNewSession = function () {
3254
+ return __awaiter$1(this, void 0, void 0, function () {
3255
+ var endpoint, error_2;
3256
+ var _this = this;
3257
+ return __generator$1(this, function (_a) {
3258
+ switch (_a.label) {
3259
+ case 0:
3260
+ // Prevent multiple concurrent initialization requests
3261
+ if (this.isInitializingSession) {
3262
+ log("New session initialization already in progress, skipping");
3263
+ return [2 /*return*/];
3264
+ }
3265
+ endpoint = this.getEndpoint();
3266
+ log("Initializing new session at ".concat(endpoint));
3267
+ this.isInitializingSession = true;
3268
+ // Create a promise that resolves when initialization completes
3269
+ this.sessionInitPromise = new Promise(function (resolve) {
3270
+ _this.resolveSessionInit = resolve;
3271
+ });
3272
+ this.typing();
3273
+ _a.label = 1;
3274
+ case 1:
3275
+ _a.trys.push([1, 3, 4, 5]);
3276
+ return [4 /*yield*/, this.performSSERequest(this.buildRequestPayload({ newSession: true, generateGreeting: true }))];
3277
+ case 2:
3278
+ _a.sent();
3279
+ return [3 /*break*/, 5];
3280
+ case 3:
3281
+ error_2 = _a.sent();
3282
+ err("Failed to initialize new session: ".concat(error_2));
3283
+ this.stopTyping();
3284
+ this.setConnectionStatus("offline");
3285
+ // Show a failure message but don't block - user can still try sending messages
3286
+ this.sendFailureMessage(0, 0, this.getErrorMessage(error_2));
3287
+ return [3 /*break*/, 5];
3288
+ case 4:
3289
+ this.isInitializingSession = false;
3290
+ // Resolve the promise so any waiting postMessage calls can proceed
3291
+ if (this.resolveSessionInit) {
3292
+ this.resolveSessionInit();
3293
+ this.resolveSessionInit = undefined;
3294
+ }
3295
+ this.sessionInitPromise = undefined;
3296
+ return [7 /*endfinally*/];
3297
+ case 5: return [2 /*return*/];
3298
+ }
3299
+ });
3300
+ });
3301
+ };
3302
+ MCPChat.prototype.setConnectionStatus = function (status) {
3303
+ log("SERVER: connection_update: ".concat(JSON.stringify(status)));
3304
+ this.dispatch(setConnectionStatus(status));
3305
+ };
3306
+ MCPChat.prototype.setAccountStatus = function (status) {
3307
+ log("SERVER: account_status: ".concat(JSON.stringify(status)));
3308
+ this.dispatch(setAccountStatus(status));
3309
+ };
3310
+ MCPChat.prototype.getEndpoint = function () {
3311
+ // Normalize serverUrl to remove trailing slashes
3312
+ var serverUrl = this.config.serverUrl.replace(/\/+$/, "");
3313
+ var mode = this.config.mode || "homeowner";
3314
+ if (mode === "business_owner") {
3315
+ return "".concat(serverUrl).concat(BUSINESS_OWNER_ENDPOINT_PATH);
3316
+ }
3317
+ // homeowner mode - serverUrl should already include appId
3318
+ return "".concat(serverUrl).concat(HOMEOWNER_ENDPOINT_PATH);
3319
+ };
3320
+ MCPChat.prototype.sendNewMessage = function (msg, user) {
3321
+ log("SERVER: new message: ".concat(JSON.stringify(msg)));
3322
+ this.dispatch({
3323
+ type: "chat",
3324
+ detail: {
3325
+ type: "chat.msg",
3326
+ user: user || this.getBot(undefined),
3327
+ msg: msg,
3328
+ timestamp: +new Date(),
3329
+ },
3330
+ });
3331
+ };
3332
+ MCPChat.prototype.userJoined = function (user) {
3333
+ log("SERVER: user joined: ".concat(JSON.stringify(user)));
3334
+ this.dispatch({
3335
+ type: "chat",
3336
+ detail: {
3337
+ type: "chat.memberjoin",
3338
+ user: user,
3339
+ timestamp: +new Date(),
3340
+ },
3341
+ });
3342
+ };
3343
+ MCPChat.prototype.typing = function () {
3344
+ this.dispatch({
3345
+ type: "chat",
3346
+ detail: {
3347
+ type: "chat.typing",
3348
+ user: this.getBot(undefined),
3349
+ typing: true,
3350
+ timestamp: +new Date(),
3351
+ },
3352
+ });
3353
+ };
3354
+ MCPChat.prototype.stopTyping = function () {
3355
+ this.dispatch({
3356
+ type: "chat",
3357
+ detail: {
3358
+ type: "chat.typing",
3359
+ user: this.getBot(undefined),
3360
+ typing: false,
3361
+ timestamp: +new Date(),
3362
+ },
3363
+ });
3364
+ };
3365
+ MCPChat.prototype.sendFailureMessage = function (retry, delay, text) {
3366
+ this.stopTyping();
3367
+ this.dispatch({
3368
+ type: "chat",
3369
+ detail: {
3370
+ type: "chat.failureMsg",
3371
+ user: this.getBot(undefined),
3372
+ failureMsg: {
3373
+ retry: retry,
3374
+ delay: delay,
3375
+ text: text,
3376
+ },
3377
+ timestamp: +new Date(),
3378
+ },
3379
+ });
3380
+ };
3381
+ /**
3382
+ * Gets the retry configuration, using custom config if provided or defaults.
3383
+ */
3384
+ MCPChat.prototype.getRetryConfig = function () {
3385
+ var _a, _b;
3386
+ if (((_b = (_a = this.configurableMessages) === null || _a === void 0 ? void 0 : _a.items) === null || _b === void 0 ? void 0 : _b.length) > 0) {
3387
+ return getConfigurableMessagesConfig(this.configurableMessages);
3388
+ }
3389
+ return DEFAULT_MCP_RETRY_CONFIG;
3390
+ };
3391
+ /**
3392
+ * Delays execution for the specified number of seconds.
3393
+ */
3394
+ MCPChat.prototype.delay = function (seconds) {
3395
+ return new Promise(function (resolve) { return setTimeout(resolve, seconds * 1000); });
3396
+ };
3397
+ /**
3398
+ * Determines a user-friendly error message based on the error type.
3399
+ */
3400
+ MCPChat.prototype.getErrorMessage = function (error, statusCode) {
3401
+ // Auth errors
3402
+ if (statusCode === 401) {
3403
+ return "Authentication failed. Please check your credentials.";
3404
+ }
3405
+ if (statusCode === 403) {
3406
+ return "Access denied. You don't have permission to access this resource.";
3407
+ }
3408
+ // Server errors
3409
+ if (statusCode && statusCode >= 500) {
3410
+ return "The server is experiencing issues. Please try again later.";
3411
+ }
3412
+ // Not found (likely wrong appId or endpoint)
3413
+ if (statusCode === 404) {
3414
+ return "Service not found. Please check your configuration.";
3415
+ }
3416
+ // Network errors
3417
+ if (error instanceof TypeError && (error.message.includes("fetch") || error.message.includes("network"))) {
3418
+ return "Unable to connect to the server. Please check your internet connection.";
3419
+ }
3420
+ // Connection refused / server down
3421
+ if (error instanceof Error) {
3422
+ var msg = error.message.toLowerCase();
3423
+ if (msg.includes("failed to fetch") || msg.includes("network") || msg.includes("econnrefused")) {
3424
+ return "Unable to reach the server. Please try again later.";
3425
+ }
3426
+ }
3427
+ // Generic fallback
3428
+ return "Something went wrong. Please try again.";
3429
+ };
3430
+ MCPChat.prototype.dispatchStreamStart = function (messageId) {
3431
+ var bot = this.getBot(undefined);
3432
+ log("Stream started: ".concat(messageId, ", bot: ").concat(JSON.stringify(bot)));
3433
+ this.dispatch({
3434
+ type: "chat",
3435
+ detail: {
3436
+ type: "chat.stream.start",
3437
+ user: bot,
3438
+ messageId: messageId,
3439
+ timestamp: +new Date(),
3440
+ },
3441
+ });
3442
+ };
3443
+ MCPChat.prototype.dispatchStreamChunk = function (messageId, text) {
3444
+ this.dispatch({
3445
+ type: "chat",
3446
+ detail: {
3447
+ type: "chat.stream.chunk",
3448
+ user: this.getBot(undefined),
3449
+ messageId: messageId,
3450
+ text: text,
3451
+ timestamp: +new Date(),
3452
+ },
3453
+ });
3454
+ };
3455
+ MCPChat.prototype.dispatchStreamEnd = function (messageId, fullMessage, toolCalls) {
3456
+ log("Stream ended: ".concat(messageId));
3457
+ this.dispatch({
3458
+ type: "chat",
3459
+ detail: {
3460
+ type: "chat.stream.end",
3461
+ user: this.getBot(undefined),
3462
+ messageId: messageId,
3463
+ msg: fullMessage,
3464
+ toolCalls: toolCalls,
3465
+ timestamp: +new Date(),
3466
+ },
3467
+ });
3468
+ };
3469
+ MCPChat.prototype.dispatchToolStart = function (params) {
3470
+ this.dispatch({
3471
+ type: "chat",
3472
+ detail: {
3473
+ type: "chat.stream.tool_start",
3474
+ user: this.getBot(undefined),
3475
+ messageId: params.messageId,
3476
+ toolName: params.toolName,
3477
+ toolCallId: params.toolCallId,
3478
+ displayName: params.displayName,
3479
+ label: params.label,
3480
+ hidden: params.hidden,
3481
+ toolInput: params.toolInput,
3482
+ timestamp: +new Date(),
3483
+ },
3484
+ });
3485
+ };
3486
+ MCPChat.prototype.dispatchToolEnd = function (params) {
3487
+ this.dispatch({
3488
+ type: "chat",
3489
+ detail: {
3490
+ type: "chat.stream.tool_end",
3491
+ user: this.getBot(undefined),
3492
+ messageId: params.messageId,
3493
+ toolName: params.toolName,
3494
+ toolCallId: params.toolCallId,
3495
+ displayName: params.displayName,
3496
+ label: params.label,
3497
+ hidden: params.hidden,
3498
+ toolResult: params.toolResult,
3499
+ toolError: params.toolError,
3500
+ timestamp: +new Date(),
3501
+ },
3502
+ });
3503
+ };
3504
+ /**
3505
+ * Starts the throttled streaming for a message.
3506
+ * Text will be dispatched at a readable pace.
3507
+ */
3508
+ MCPChat.prototype.startStreamThrottle = function (messageId) {
3509
+ var _this = this;
3510
+ this.streamBuffer = "";
3511
+ this.streamingMessageIdForThrottle = messageId;
3512
+ // Clear any existing timer and visibility handler
3513
+ if (this.streamThrottleTimer) {
3514
+ clearInterval(this.streamThrottleTimer);
3515
+ }
3516
+ if (this.visibilityHandler) {
3517
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
3518
+ }
3519
+ // Start interval to dispatch buffered text
3520
+ this.streamThrottleTimer = setInterval(function () {
3521
+ if (_this.streamBuffer.length > 0 && _this.streamingMessageIdForThrottle) {
3522
+ var charsToSend = Math.min(STREAM_CHARS_PER_TICK, _this.streamBuffer.length);
3523
+ var textToDispatch = _this.streamBuffer.slice(0, charsToSend);
3524
+ _this.streamBuffer = _this.streamBuffer.slice(charsToSend);
3525
+ _this.dispatchStreamChunk(_this.streamingMessageIdForThrottle, textToDispatch);
3526
+ }
3527
+ }, STREAM_TICK_INTERVAL_MS);
3528
+ // Handle tab visibility changes - flush buffer when tab becomes visible
3529
+ this.visibilityHandler = function () {
3530
+ if (document.visibilityState === "visible") {
3531
+ log("[Visibility] Tab became visible, buffer length: ".concat(_this.streamBuffer.length, ", messageId: ").concat(_this.streamingMessageIdForThrottle));
3532
+ if (_this.streamBuffer.length > 0 && _this.streamingMessageIdForThrottle) {
3533
+ // Dispatch all buffered text immediately when tab becomes visible
3534
+ log("[Visibility] Flushing ".concat(_this.streamBuffer.length, " chars to UI"));
3535
+ _this.dispatchStreamChunk(_this.streamingMessageIdForThrottle, _this.streamBuffer);
3536
+ _this.streamBuffer = "";
3537
+ }
3538
+ }
3539
+ else {
3540
+ log("[Visibility] Tab hidden");
3541
+ }
3542
+ };
3543
+ document.addEventListener("visibilitychange", this.visibilityHandler);
3544
+ };
3545
+ /**
3546
+ * Adds text to the stream buffer for throttled dispatch.
3547
+ */
3548
+ MCPChat.prototype.bufferStreamText = function (text) {
3549
+ this.streamBuffer += text;
3550
+ };
3551
+ /**
3552
+ * Flushes any remaining buffered text and stops the throttle timer.
3553
+ * Returns a promise that resolves when all buffered text has been dispatched.
3554
+ */
3555
+ MCPChat.prototype.flushStreamBuffer = function () {
3556
+ return __awaiter$1(this, void 0, void 0, function () {
3557
+ var waitCount, maxWait;
3558
+ return __generator$1(this, function (_a) {
3559
+ switch (_a.label) {
3560
+ case 0:
3561
+ if (!(this.streamBuffer.length > 0 && this.streamingMessageIdForThrottle)) return [3 /*break*/, 5];
3562
+ if (!(document.visibilityState === "hidden")) return [3 /*break*/, 1];
3563
+ log("[flushStreamBuffer] Tab hidden, dispatching remaining ".concat(this.streamBuffer.length, " chars immediately"));
3564
+ this.dispatchStreamChunk(this.streamingMessageIdForThrottle, this.streamBuffer);
3565
+ this.streamBuffer = "";
3566
+ return [3 /*break*/, 5];
3567
+ case 1:
3568
+ waitCount = 0;
3569
+ maxWait = 100;
3570
+ _a.label = 2;
3571
+ case 2:
3572
+ if (!(this.streamBuffer.length > 0 && waitCount < maxWait)) return [3 /*break*/, 4];
3573
+ return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, STREAM_TICK_INTERVAL_MS); })];
3574
+ case 3:
3575
+ _a.sent();
3576
+ waitCount++;
3577
+ return [3 /*break*/, 2];
3578
+ case 4:
3579
+ // If still has content after timeout, flush it
3580
+ if (this.streamBuffer.length > 0 && this.streamingMessageIdForThrottle) {
3581
+ log("[flushStreamBuffer] Timeout waiting for buffer, dispatching remaining ".concat(this.streamBuffer.length, " chars"));
3582
+ this.dispatchStreamChunk(this.streamingMessageIdForThrottle, this.streamBuffer);
3583
+ this.streamBuffer = "";
3584
+ }
3585
+ _a.label = 5;
3586
+ case 5:
3587
+ // Stop the throttle timer
3588
+ if (this.streamThrottleTimer) {
3589
+ clearInterval(this.streamThrottleTimer);
3590
+ this.streamThrottleTimer = undefined;
3591
+ }
3592
+ if (this.visibilityHandler) {
3593
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
3594
+ this.visibilityHandler = undefined;
3595
+ }
3596
+ this.streamingMessageIdForThrottle = undefined;
3597
+ return [2 /*return*/];
3598
+ }
3599
+ });
3600
+ });
3601
+ };
3602
+ /**
3603
+ * Immediately stops throttling and clears the buffer (used on abort/error).
3604
+ */
3605
+ MCPChat.prototype.stopStreamThrottle = function () {
3606
+ if (this.streamThrottleTimer) {
3607
+ clearInterval(this.streamThrottleTimer);
3608
+ this.streamThrottleTimer = undefined;
3609
+ }
3610
+ if (this.visibilityHandler) {
3611
+ document.removeEventListener("visibilitychange", this.visibilityHandler);
3612
+ this.visibilityHandler = undefined;
3613
+ }
3614
+ this.streamBuffer = "";
3615
+ this.streamingMessageIdForThrottle = undefined;
3616
+ };
3617
+ MCPChat.prototype.sendOfflineMsg = function (_, cb) {
3618
+ cb();
3619
+ };
3620
+ MCPChat.prototype.sendChatMsg = function (message, cb) {
3621
+ return __awaiter$1(this, void 0, void 0, function () {
3622
+ return __generator$1(this, function (_a) {
3623
+ return [2 /*return*/, this.sendChatMsgRequest({
3624
+ msg: message,
3625
+ timestamp: new Date().getTime(),
3626
+ agent: false,
3627
+ user: undefined,
3628
+ type: "msg",
3629
+ }, cb)];
3630
+ });
3631
+ });
3632
+ };
3633
+ MCPChat.prototype.bargeOut = function (_) {
3634
+ return __awaiter$1(this, void 0, void 0, function () {
3635
+ return __generator$1(this, function (_a) {
3636
+ throw new Error("bargeOut is not supported in MCP mode");
3637
+ });
3638
+ });
3639
+ };
3640
+ MCPChat.prototype.bargeIn = function (_agentName, __) {
3641
+ return __awaiter$1(this, void 0, void 0, function () {
3642
+ return __generator$1(this, function (_a) {
3643
+ throw new Error("bargeIn is not supported in MCP mode");
3644
+ });
3645
+ });
3646
+ };
3647
+ /**
3648
+ * Ensures a nick has the "agent:" prefix required for agent message detection.
3649
+ */
3650
+ MCPChat.prototype.ensureAgentNick = function (nick) {
3651
+ if (!nick)
3652
+ return "agent:robot";
3653
+ if (nick.startsWith("agent:"))
3654
+ return nick;
3655
+ return "agent:".concat(nick);
3656
+ };
3657
+ MCPChat.prototype.getBot = function (user) {
3658
+ var _a;
3659
+ var bot = (_a = this.options) === null || _a === void 0 ? void 0 : _a.bot;
3660
+ if (!user) {
3661
+ // Ensure bot nick has agent: prefix and mark as AI
3662
+ var defaultBot = bot || { nick: "agent:robot", displayName: "Assistant" };
3663
+ return __assign(__assign({}, defaultBot), { nick: this.ensureAgentNick(defaultBot.nick), isAI: true });
3664
+ }
3665
+ if (user.displayName && user.nick && user.avatarPath) {
3666
+ return __assign(__assign({}, user), { nick: this.ensureAgentNick(user.nick), isAI: true });
3667
+ }
3668
+ return __assign(__assign({}, user), { nick: this.ensureAgentNick(user.nick || (bot === null || bot === void 0 ? void 0 : bot.nick)), displayName: user.displayName || (bot === null || bot === void 0 ? void 0 : bot.displayName) || "Assistant", avatarPath: user.avatarPath || (bot === null || bot === void 0 ? void 0 : bot.avatarPath), isAI: true });
3669
+ };
3670
+ MCPChat.prototype.sendChatMsgRequest = function (serviceRequest, cb) {
3671
+ return __awaiter$1(this, void 0, void 0, function () {
3672
+ var error_3;
3673
+ return __generator$1(this, function (_a) {
3674
+ switch (_a.label) {
3675
+ case 0:
3676
+ _a.trys.push([0, 2, , 3]);
3677
+ return [4 /*yield*/, this.postMessage(serviceRequest)];
3678
+ case 1:
3679
+ _a.sent();
3680
+ cb();
3681
+ return [3 /*break*/, 3];
3682
+ case 2:
3683
+ error_3 = _a.sent();
3684
+ cb(error_3);
3685
+ return [3 /*break*/, 3];
3686
+ case 3: return [2 /*return*/];
3687
+ }
3688
+ });
3689
+ });
3690
+ };
3691
+ MCPChat.prototype.postMessage = function (message) {
3692
+ return __awaiter$1(this, void 0, void 0, function () {
3693
+ var trimmedText, timeout, result, retryConfig, messageText, success, attempt, isLastAttempt, config, error_4, statusCode, errorMessage, statusCode_1, errorMessage, nextConfig, nextConfig;
3694
+ var _a, _b, _c;
3695
+ return __generator$1(this, function (_d) {
3696
+ switch (_d.label) {
3697
+ case 0:
3698
+ trimmedText = ((_b = (_a = message.msg) === null || _a === void 0 ? void 0 : _a.text) === null || _b === void 0 ? void 0 : _b.trim()) || "";
3699
+ if (!trimmedText) {
3700
+ log("Ignoring empty message");
3701
+ return [2 /*return*/];
3702
+ }
3703
+ if (!(this.isInitializingSession && this.sessionInitPromise)) return [3 /*break*/, 2];
3704
+ log("Waiting for session initialization to complete before sending message...");
3705
+ timeout = new Promise(function (resolve) {
3706
+ return setTimeout(function () { return resolve("timeout"); }, 10000);
3707
+ });
3708
+ return [4 /*yield*/, Promise.race([this.sessionInitPromise, timeout])];
3709
+ case 1:
3710
+ result = _d.sent();
3711
+ if (result === "timeout" || this.isInitializingSession) {
3712
+ err("Session initialization timed out");
3713
+ this.sendFailureMessage(0, 0, "Chat is not ready. Please try again.");
3714
+ return [2 /*return*/];
3715
+ }
3716
+ _d.label = 2;
3717
+ case 2:
3718
+ retryConfig = this.getRetryConfig();
3719
+ messageText = ((_c = message.msg) === null || _c === void 0 ? void 0 : _c.text) || "";
3720
+ success = false;
3721
+ attempt = 0;
3722
+ _d.label = 3;
3723
+ case 3:
3724
+ if (!(attempt < retryConfig.length)) return [3 /*break*/, 14];
3725
+ isLastAttempt = attempt === retryConfig.length - 1;
3726
+ config = retryConfig[attempt];
3727
+ log("MCP attempt ".concat(attempt + 1, "/").concat(retryConfig.length, " for message: ").concat(messageText));
3728
+ // Start typing indicator
3729
+ this.typing();
3730
+ _d.label = 4;
3731
+ case 4:
3732
+ _d.trys.push([4, 6, , 13]);
3733
+ return [4 /*yield*/, this.attemptSSERequest(message)];
3734
+ case 5:
3735
+ _d.sent();
3736
+ success = true;
3737
+ return [3 /*break*/, 14]; // Success - exit retry loop
3738
+ case 6:
3739
+ error_4 = _d.sent();
3740
+ this.stopTyping();
3741
+ statusCode = error_4 === null || error_4 === void 0 ? void 0 : error_4.statusCode;
3742
+ err("MCP attempt ".concat(attempt + 1, " failed: ").concat(error_4, ", statusCode: ").concat(statusCode));
3743
+ log("[postMessage] Error details:", { error: error_4, statusCode: statusCode, messageText: messageText, sessionId: this._sessionId });
3744
+ // Don't retry on 4xx client errors - these won't succeed on retry
3745
+ if (statusCode && statusCode >= 400 && statusCode < 500) {
3746
+ log("Client error ".concat(statusCode, ", not retrying"));
3747
+ errorMessage = this.getErrorMessage(error_4, statusCode);
3748
+ this.sendFailureMessage(0, 0, errorMessage);
3749
+ return [2 /*return*/];
3750
+ }
3751
+ // Set offline status
3752
+ this.setConnectionStatus("offline");
3753
+ if (!isLastAttempt) return [3 /*break*/, 7];
3754
+ statusCode_1 = error_4 === null || error_4 === void 0 ? void 0 : error_4.statusCode;
3755
+ errorMessage = config.text || this.getErrorMessage(error_4, statusCode_1);
3756
+ this.sendFailureMessage(0, 0, errorMessage);
3757
+ return [3 /*break*/, 12];
3758
+ case 7:
3759
+ if (!(attempt > 0 || config.text)) return [3 /*break*/, 10];
3760
+ nextConfig = retryConfig[attempt + 1];
3761
+ if (!(nextConfig && nextConfig.delay > 0)) return [3 /*break*/, 9];
3762
+ this.sendFailureMessage(nextConfig.retry, nextConfig.delay, nextConfig.text);
3763
+ // Wait for the delay before retrying
3764
+ return [4 /*yield*/, this.delay(nextConfig.delay)];
3765
+ case 8:
3766
+ // Wait for the delay before retrying
3767
+ _d.sent();
3768
+ _d.label = 9;
3769
+ case 9: return [3 /*break*/, 12];
3770
+ case 10:
3771
+ nextConfig = retryConfig[attempt + 1];
3772
+ if (!(nextConfig && nextConfig.delay > 0)) return [3 /*break*/, 12];
3773
+ return [4 /*yield*/, this.delay(nextConfig.delay)];
3774
+ case 11:
3775
+ _d.sent();
3776
+ _d.label = 12;
3777
+ case 12: return [3 /*break*/, 13];
3778
+ case 13:
3779
+ attempt++;
3780
+ return [3 /*break*/, 3];
3781
+ case 14:
3782
+ if (!success) {
3783
+ log("All MCP retry attempts exhausted");
3784
+ }
3785
+ return [2 /*return*/];
3786
+ }
3787
+ });
3788
+ });
3789
+ };
3790
+ /**
3791
+ * Attempts a single SSE request. Throws on failure.
3792
+ */
3793
+ MCPChat.prototype.attemptSSERequest = function (message) {
3794
+ return __awaiter$1(this, void 0, void 0, function () {
3795
+ var messageText;
3796
+ var _a;
3797
+ return __generator$1(this, function (_b) {
3798
+ messageText = ((_a = message.msg) === null || _a === void 0 ? void 0 : _a.text) || "";
3799
+ log("[attemptSSERequest] Sending message: \"".concat(messageText, "\", userId: ").concat(this._userId, ", sessionId: ").concat(this._sessionId));
3800
+ return [2 /*return*/, this.performSSERequest(this.buildRequestPayload({ message: messageText }))];
3801
+ });
3802
+ });
3803
+ };
3804
+ /**
3805
+ * Performs an SSE request with the given body.
3806
+ * Used for both new session initialization and regular messages.
3807
+ */
3808
+ MCPChat.prototype.performSSERequest = function (body) {
3809
+ return __awaiter$1(this, void 0, void 0, function () {
3810
+ var endpoint, messageId, textChunks, hasError, httpStatusCode, sseError;
3811
+ var _this = this;
3812
+ return __generator$1(this, function (_a) {
3813
+ endpoint = this.getEndpoint();
3814
+ log("SSE request to ".concat(endpoint, ": ").concat(JSON.stringify(body)));
3815
+ // Cancel any ongoing stream
3816
+ if (this.abortController) {
3817
+ this.abortController.abort();
3818
+ this.abortController = undefined;
3819
+ }
3820
+ this.abortController = new AbortController();
3821
+ messageId = uuid_1();
3822
+ this.currentMessageId = messageId;
3823
+ textChunks = [];
3824
+ hasError = false;
3825
+ return [2 /*return*/, new Promise(function (resolve, reject) {
3826
+ // WARNING: Do not log headers object - it contains sensitive auth tokens
3827
+ cjs.fetchEventSource(endpoint, {
3828
+ method: "POST",
3829
+ headers: __assign({ "Content-Type": "application/json" }, ((_this.config.mode || "homeowner") === "business_owner" && _this.config.authToken
3830
+ ? { Authorization: "Bearer ".concat(_this.config.authToken) }
3831
+ : {})),
3832
+ body: JSON.stringify(body),
3833
+ signal: _this.abortController.signal,
3834
+ onopen: function (response) { return __awaiter$1(_this, void 0, void 0, function () {
3835
+ var error;
3836
+ return __generator$1(this, function (_a) {
3837
+ httpStatusCode = response.status;
3838
+ if (!response.ok) {
3839
+ error = new Error("HTTP error! status: ".concat(response.status));
3840
+ error.statusCode = response.status;
3841
+ throw error;
3842
+ }
3843
+ log("SSE connection opened");
3844
+ // Connection successful - ensure we're marked as online
3845
+ this.setConnectionStatus("online");
3846
+ return [2 /*return*/];
3847
+ });
3848
+ }); },
3849
+ onmessage: function (event) {
3850
+ log("SSE event: ".concat(event.event, ", data: ").concat(event.data));
3851
+ var eventType = event.event || "message";
3852
+ var data = {};
3853
+ try {
3854
+ data = JSON.parse(event.data);
3855
+ }
3856
+ catch (e) {
3857
+ log("Failed to parse SSE data: ".concat(e));
3858
+ return;
3859
+ }
3860
+ switch (eventType) {
3861
+ case "connected":
3862
+ // Connection established
3863
+ log("[SSE] Connected event received, messageId: ".concat(messageId, ", isReturningUser: ").concat(data.isReturningUser));
3864
+ // Store identity from server response
3865
+ if (data.userId || data.sessionId) {
3866
+ if (data.userId) {
3867
+ _this._userId = data.userId;
3868
+ }
3869
+ if (data.sessionId) {
3870
+ _this._sessionId = data.sessionId;
3871
+ _this.dispatch(setSessionId(_this._sessionId));
3872
+ }
3873
+ // Persist to localStorage for session continuity
3874
+ storeIdentity(data.userId, data.sessionId);
3875
+ log("[SSE] Identity from connected - userId: ".concat(data.userId, ", sessionId: ").concat(data.sessionId));
3876
+ }
3877
+ // Always start streaming - server sends greeting for both new and returning users
3878
+ // (resumeSession requests always get a personalized greeting)
3879
+ _this.currentToolCalls = [];
3880
+ _this.stopTyping();
3881
+ _this.dispatchStreamStart(messageId);
3882
+ _this.startStreamThrottle(messageId);
3883
+ break;
3884
+ case "session_expired":
3885
+ // Session no longer exists on server - need to start fresh
3886
+ log("[SSE] Session expired: ".concat(data.reason || "Session not found"));
3887
+ _this._sessionId = "";
3888
+ // Clear stored session but keep userId for returning user identification
3889
+ clearStoredSession();
3890
+ _this.stopTyping();
3891
+ _this.stopStreamThrottle();
3892
+ // Reset validation flag before starting new session
3893
+ // (ensures connected handler will dispatch stream for greeting)
3894
+ _this.isValidatingSession = false;
3895
+ // Start a new session automatically
3896
+ _this.initializeNewSession();
3897
+ resolve();
3898
+ break;
3899
+ case "text":
3900
+ if (data.text) {
3901
+ log("[SSE] Text chunk received (".concat(data.text.length, " chars), total chunks: ").concat(textChunks.length + 1));
3902
+ textChunks.push(data.text);
3903
+ // Buffer text for throttled dispatch
3904
+ _this.bufferStreamText(data.text);
3905
+ }
3906
+ break;
3907
+ case "tool_start":
3908
+ log("Tool execution started: ".concat(data.toolName, ", toolCallId: ").concat(data.toolCallId, ", displayName: ").concat(data.displayName, ", label: ").concat(data.label, ", hidden: ").concat(data.hidden));
3909
+ if (data.toolName) {
3910
+ var toolCall = {
3911
+ name: data.toolName,
3912
+ toolCallId: data.toolCallId,
3913
+ displayName: data.displayName,
3914
+ label: data.label,
3915
+ hidden: data.hidden,
3916
+ input: data.toolInput,
3917
+ startTime: Date.now(),
3918
+ isExecuting: true,
3919
+ };
3920
+ _this.currentToolCalls.push(toolCall);
3921
+ // Always dispatch tool start for user-friendly progress display
3922
+ _this.dispatchToolStart({
3923
+ messageId: messageId,
3924
+ toolName: data.toolName,
3925
+ toolCallId: data.toolCallId,
3926
+ displayName: data.displayName,
3927
+ label: data.label,
3928
+ hidden: data.hidden,
3929
+ toolInput: data.toolInput,
3930
+ });
3931
+ }
3932
+ break;
3933
+ case "tool_end":
3934
+ log("Tool execution ended: ".concat(data.toolName, ", toolCallId: ").concat(data.toolCallId, ", displayName: ").concat(data.displayName, ", label: ").concat(data.label, ", hidden: ").concat(data.hidden));
3935
+ if (data.toolName) {
3936
+ // Find the matching tool call and update it
3937
+ // Match by toolCallId if available, otherwise fall back to name + isExecuting
3938
+ var toolCall = _this.currentToolCalls.find(function (tc) {
3939
+ return data.toolCallId
3940
+ ? tc.toolCallId === data.toolCallId
3941
+ : tc.name === data.toolName && tc.isExecuting;
3942
+ });
3943
+ if (toolCall) {
3944
+ toolCall.result = data.toolResult;
3945
+ toolCall.error = data.toolError;
3946
+ toolCall.label = data.label; // Update with completion label
3947
+ toolCall.hidden = data.hidden; // Update hidden status
3948
+ toolCall.endTime = Date.now();
3949
+ toolCall.isExecuting = false;
3950
+ }
3951
+ // Always dispatch tool end for user-friendly progress display
3952
+ _this.dispatchToolEnd({
3953
+ messageId: messageId,
3954
+ toolName: data.toolName,
3955
+ toolCallId: data.toolCallId,
3956
+ displayName: data.displayName,
3957
+ label: data.label,
3958
+ hidden: data.hidden,
3959
+ toolResult: data.toolResult,
3960
+ toolError: data.toolError,
3961
+ });
3962
+ }
3963
+ break;
3964
+ case "done":
3965
+ _this.stopTyping();
3966
+ if (data.response) {
3967
+ // Update session ID if provided and persist to localStorage
3968
+ if (data.response.sessionId) {
3969
+ _this._sessionId = data.response.sessionId;
3970
+ _this.dispatch(setSessionId(_this._sessionId));
3971
+ storeIdentity(undefined, data.response.sessionId);
3972
+ }
3973
+ // Wait for buffer to flush, then finalize
3974
+ var accumulatedText = textChunks.join("");
3975
+ log("[SSE] Done event received. Total chunks: ".concat(textChunks.length, ", accumulated text length: ").concat(accumulatedText.length));
3976
+ log("[SSE] First 100 chars of accumulated: ".concat(accumulatedText.substring(0, 100)));
3977
+ // Map suggestions to options (chips) format
3978
+ var suggestions = data.response.suggestions;
3979
+ var options = suggestions === null || suggestions === void 0 ? void 0 : suggestions.map(function (s) { return ({
3980
+ label: s.title,
3981
+ actionUrl: s.url || "",
3982
+ }); });
3983
+ if (options === null || options === void 0 ? void 0 : options.length) {
3984
+ log("[SSE] Suggestions: ".concat(options.length, " items"));
3985
+ }
3986
+ // Map sources for reference links
3987
+ var sources = data.response.sources;
3988
+ if (sources === null || sources === void 0 ? void 0 : sources.length) {
3989
+ log("[SSE] Sources: ".concat(sources.length, " items"));
3990
+ }
3991
+ var finalMessage_1 = {
3992
+ text: accumulatedText || data.response.response || "",
3993
+ options: options,
3994
+ sources: sources,
3995
+ };
3996
+ // Capture tool calls before flushing (debug mode)
3997
+ var toolCalls_1 = _this.config.debugMode ? __spreadArray$1([], _this.currentToolCalls, true) : undefined;
3998
+ _this.flushStreamBuffer().then(function () {
3999
+ _this.dispatchStreamEnd(messageId, finalMessage_1, toolCalls_1);
4000
+ _this.currentToolCalls = []; // Clear after dispatch
4001
+ resolve();
4002
+ });
4003
+ }
4004
+ else {
4005
+ _this.stopStreamThrottle();
4006
+ resolve();
4007
+ }
4008
+ break;
4009
+ case "error":
4010
+ hasError = true;
4011
+ _this.stopTyping();
4012
+ _this.stopStreamThrottle();
4013
+ err("SSE error: ".concat(data.error));
4014
+ // Server-side errors should not retry - reject immediately with the error
4015
+ reject(new Error(data.error || "Server error during processing"));
4016
+ break;
4017
+ }
4018
+ },
4019
+ onerror: function (error) {
4020
+ // Only handle error if this is still the current message
4021
+ if (_this.currentMessageId === messageId && !hasError) {
4022
+ hasError = true;
4023
+ _this.stopStreamThrottle();
4024
+ sseError = error instanceof Error ? error : new Error(String(error));
4025
+ // Get status code if available
4026
+ var statusCode = (error === null || error === void 0 ? void 0 : error.statusCode) || httpStatusCode;
4027
+ if (statusCode) {
4028
+ sseError.statusCode = statusCode;
4029
+ }
4030
+ err("SSE connection error: ".concat(error));
4031
+ }
4032
+ // Throw to stop fetchEventSource from retrying
4033
+ throw error;
4034
+ },
4035
+ }).catch(function (error) {
4036
+ // Handle errors that occur before/outside the SSE connection
4037
+ _this.stopStreamThrottle();
4038
+ if (!hasError && _this.currentMessageId === messageId) {
4039
+ var statusCode = (error === null || error === void 0 ? void 0 : error.statusCode) || httpStatusCode;
4040
+ var wrappedError = error instanceof Error ? error : new Error(String(error));
4041
+ if (statusCode) {
4042
+ wrappedError.statusCode = statusCode;
4043
+ }
4044
+ reject(wrappedError);
4045
+ }
4046
+ else if (sseError) {
4047
+ reject(sseError);
4048
+ }
4049
+ else {
4050
+ reject(error);
4051
+ }
4052
+ });
4053
+ })];
4054
+ });
4055
+ });
4056
+ };
4057
+ MCPChat.prototype.sendTyping = function () { };
4058
+ MCPChat.prototype.setVisitorInfo = function (visitorInfo, sessionId, cb) {
4059
+ this.visitorInfo = visitorInfo;
4060
+ this._attributes = __assign({}, this.visitorInfo.attributes);
4061
+ // do not set currentUrl if localhost
4062
+ var href = new URL(window.location.href);
4063
+ if (href === null || href === void 0 ? void 0 : href.host.toLowerCase().startsWith("localhost")) {
4064
+ this._attributes.isLocal = true;
4065
+ }
4066
+ else {
4067
+ this._attributes.currentUrl = window.location.href;
4068
+ }
4069
+ this._accessToken = this.visitorInfo.accessToken;
4070
+ // This is for the bot
4071
+ this.userJoined(this.getBot(undefined));
4072
+ // Show typing indicator after bot joins if we're still waiting for initial greeting
4073
+ if (this.isInitializingSession) {
4074
+ this.typing();
4075
+ }
4076
+ this.startSession(sessionId);
4077
+ cb();
4078
+ };
4079
+ MCPChat.prototype.sendChatRating = function () { };
4080
+ MCPChat.prototype.sendFile = function (_, cb) {
4081
+ cb(new Error("File upload not supported in MCP mode"));
4082
+ };
4083
+ MCPChat.prototype.markAsRead = function () { };
4084
+ MCPChat.prototype.flush = function () { };
4085
+ MCPChat.prototype.dispose = function () {
4086
+ this.stopStreamThrottle();
4087
+ if (this.abortController) {
4088
+ this.abortController.abort();
4089
+ this.abortController = undefined;
4090
+ }
4091
+ };
4092
+ MCPChat.prototype.sleep = function () {
4093
+ this.stopStreamThrottle();
4094
+ if (this.abortController) {
4095
+ this.abortController.abort();
4096
+ this.abortController = undefined;
4097
+ }
4098
+ };
4099
+ MCPChat.prototype.wakeup = function () { };
4100
+ MCPChat.prototype.startSession = function (sessionId) {
4101
+ if (this.visitorInfo.visitorId) {
4102
+ this._userId = "".concat(this.visitorInfo.visitorId);
4103
+ }
4104
+ else if (this.visitorInfo.email) {
4105
+ this._userId = "mcp-widget-user-".concat(this.visitorInfo.email);
4106
+ }
4107
+ else {
4108
+ this._userId = "mcp-widget-user-".concat(uuid_1());
4109
+ }
4110
+ // Session ID priority:
4111
+ // 1. If explicitly provided via setVisitorInfo, use it
4112
+ // 2. If empty string provided, generate a new session ID
4113
+ // 3. If not provided (undefined) and we have an existing session, keep it
4114
+ if (sessionId) {
4115
+ // Explicit session ID provided - use it
4116
+ this._sessionId = sessionId;
4117
+ log("Using provided session id: ".concat(this._sessionId));
4118
+ }
4119
+ else if (sessionId === "") {
4120
+ // Empty string explicitly passed - generate new session
4121
+ this._sessionId = "mcp-widget-session-".concat(uuid_1());
4122
+ this.dispatch(setSessionId(this._sessionId));
4123
+ log("Using generated session id: ".concat(this._sessionId));
4124
+ }
4125
+ else if (!this._sessionId && this.config.sessionId) {
4126
+ // No existing session and config has one - use config
4127
+ this._sessionId = this.config.sessionId;
4128
+ log("Using config session id: ".concat(this._sessionId));
4129
+ }
4130
+ else if (!this._sessionId) {
4131
+ // No session ID at all - generate one
4132
+ this._sessionId = "mcp-widget-session-".concat(uuid_1());
4133
+ this.dispatch(setSessionId(this._sessionId));
4134
+ log("Using generated session id: ".concat(this._sessionId));
4135
+ }
4136
+ else {
4137
+ log("Keeping existing session id: ".concat(this._sessionId));
4138
+ }
4139
+ this.isNewSession = true;
4140
+ };
4141
+ Object.defineProperty(MCPChat.prototype, "userId", {
4142
+ get: function () {
4143
+ return this._userId;
4144
+ },
4145
+ enumerable: false,
4146
+ configurable: true
4147
+ });
4148
+ Object.defineProperty(MCPChat.prototype, "sessionId", {
4149
+ get: function () {
4150
+ return this._sessionId;
4151
+ },
4152
+ enumerable: false,
4153
+ configurable: true
4154
+ });
4155
+ return MCPChat;
4156
+ }());
4157
+
4158
+ /**
4159
+ * Sends a POST to your STENTOR based server.
4160
+ *
4161
+ * @param data
4162
+ * @param url
4163
+ * @param key
4164
+ * @param signal
4165
+ * @returns
4166
+ */
4167
+ function postMessageToStentor(data, url, key, signal) {
4168
+ return __awaiter$1(this, void 0, void 0, function () {
4169
+ var body, response;
4170
+ return __generator$1(this, function (_a) {
4171
+ switch (_a.label) {
4172
+ case 0:
4173
+ body = JSON.stringify(data);
4174
+ log("URL: ".concat(url));
4175
+ log("BODY: ".concat(body));
4176
+ return [4 /*yield*/, fetch(url, {
4177
+ method: "POST",
4178
+ headers: {
4179
+ "Content-Type": "application/json",
4180
+ "Authorization": "Bearer ".concat(key),
4181
+ },
4182
+ body: body,
4183
+ mode: "cors",
4184
+ signal: signal
4185
+ })];
4186
+ case 1:
4187
+ response = _a.sent();
4188
+ if (!response.ok) {
4189
+ throw new Error("Status ".concat(response.status, ", Text: ").concat(response.statusText));
4190
+ }
4191
+ return [2 /*return*/, response.json()];
4192
+ }
4193
+ });
4194
+ });
4195
+ }
4196
+
4197
+ function convertFromListDisplay(list) {
4198
+ return {
4199
+ type: list.type,
4200
+ title: list.title,
4201
+ items: list.items.map(function (item) {
4202
+ var _a, _b;
4203
+ var responseItem = {
4204
+ title: item.title,
4205
+ subTitle: item.description,
4206
+ token: item.token,
4207
+ url: item.url,
4208
+ hideUrl: item.hideUrl,
4209
+ imageUrl: (_a = item.image) === null || _a === void 0 ? void 0 : _a.url,
4210
+ imageActionUrl: (_b = item.image) === null || _b === void 0 ? void 0 : _b.imageActionUrl
4211
+ };
4212
+ // TODO: Remove any when the buttons are defined on the list (ListButton - title + openUrlAction)
4213
+ var itemButtons = item.buttons;
4214
+ if (itemButtons && itemButtons.length > 0) {
4215
+ responseItem.buttons = itemButtons.map(function (button) { return ({
4216
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
4217
+ actionUrl: button.openUrlAction,
4218
+ label: button.title
4219
+ }); });
4220
+ }
4221
+ return responseItem;
4222
+ })
4223
+ };
4224
+ }
4225
+ function convertToListDisplay(list) {
4226
+ return {
4227
+ type: list.type,
4228
+ title: list.title,
4229
+ items: (list.items || []).map(function (item) {
4230
+ var responseItem = {
4231
+ title: item.title,
4232
+ description: item.subTitle,
4233
+ token: item.token,
4234
+ url: item.url,
4235
+ hideUrl: item.hideUrl,
4236
+ image: {
4237
+ url: item.imageUrl,
4238
+ imageActionUrl: item.imageActionUrl,
4239
+ accessibilityText: ""
4240
+ }
4241
+ };
4242
+ // TODO: Remove any when the buttons are defined on the list (ListButton - title + openUrlAction)
4243
+ var itemButtons = item.buttons;
4244
+ if (itemButtons && itemButtons.length > 0) {
4245
+ responseItem.buttons = itemButtons.map(function (button) { return ({
4246
+ openUrlAction: button.actionUrl,
4247
+ title: button.label
4248
+ }); });
4249
+ }
4250
+ return responseItem;
4251
+ })
4252
+ };
4253
+ }
4254
+ function convertFromCardDisplay(card) {
4255
+ return {
4256
+ content: card.content,
4257
+ imageUrl: card.smallImageUrl,
4258
+ title: card.title,
4259
+ imageActionUrl: card === null || card === void 0 ? void 0 : card.imageActionUrl,
4260
+ buttons: card.buttons ? card.buttons.map(function (button) { return ({
4261
+ actionUrl: button.openUrlAction,
4262
+ label: button.title
4263
+ }); }) : undefined
4264
+ };
4265
+ }
4266
+ function getOutput(value) {
4267
+ if (value) {
4268
+ if (typeof value === "string") {
4269
+ return {
4270
+ displayText: value
4271
+ };
4272
+ }
4273
+ else {
4274
+ return value;
4275
+ }
4276
+ }
4277
+ return undefined;
4278
+ }
4279
+ /**
4280
+ * Converts a Stentor Response to a ChatMessageRequest
4281
+ *
4282
+ * @param botResponse
4283
+ * @param now
4284
+ * @returns
4285
+ */
4286
+ function responseToMessage(botResponse, now) {
4287
+ var _a, _b, _c, _d, _e;
4288
+ if (now === void 0) { now = new Date().getTime(); }
4289
+ var responseMessage;
4290
+ if (!botResponse) {
4291
+ return responseMessage;
4292
+ }
4293
+ var text;
4294
+ var html;
4295
+ var endSession;
4296
+ var outputSpeech = getOutput(botResponse.outputSpeech);
4297
+ var reprompt = getOutput(botResponse.reprompt);
4298
+ if (outputSpeech) {
4299
+ text = outputSpeech.displayText;
4300
+ html = outputSpeech.html;
4301
+ }
4302
+ if (botResponse.system === "TRANSFER_CALL") {
4303
+ responseMessage = {
4304
+ type: "handOff",
4305
+ timestamp: now,
4306
+ handoffMessage: text,
4307
+ handoffTarget: (_a = botResponse === null || botResponse === void 0 ? void 0 : botResponse.data) === null || _a === void 0 ? void 0 : _a.transferPhoneNumber,
4308
+ endSession: false,
4309
+ user: undefined
4310
+ };
4311
+ }
4312
+ else if ((_b = botResponse.system) === null || _b === void 0 ? void 0 : _b.startsWith("PERMISSION_")) {
4313
+ responseMessage = getPermissionResponse(botResponse, now);
4314
+ }
4315
+ else {
4316
+ endSession = !reprompt || !(reprompt.displayText || reprompt.ssml);
4317
+ responseMessage = {
4318
+ type: "msg",
4319
+ timestamp: now,
4320
+ msg: {
4321
+ displays: botResponse.displays,
4322
+ context: (_d = (_c = botResponse.context) === null || _c === void 0 ? void 0 : _c.active) === null || _d === void 0 ? void 0 : _d.map(function (ctx) { return ctx.name; })
4323
+ },
4324
+ endSession: endSession,
4325
+ user: undefined
4326
+ };
4327
+ if (text && !html) {
4328
+ responseMessage.msg = __assign(__assign({}, responseMessage.msg), { text: text });
4329
+ }
4330
+ if (html) {
4331
+ responseMessage.msg = __assign(__assign({}, responseMessage.msg), { html: html });
4332
+ }
4333
+ if ((_e = outputSpeech === null || outputSpeech === void 0 ? void 0 : outputSpeech.suggestions) === null || _e === void 0 ? void 0 : _e.length) {
4334
+ responseMessage.msg.options = outputSpeech.suggestions.map(function (suggestion) {
4335
+ if (typeof suggestion === "string") {
4336
+ // Simple chips (strings)
4337
+ return suggestion;
4338
+ }
4339
+ else {
4340
+ // "call out" chips
4341
+ return {
4342
+ label: suggestion.title,
4343
+ actionUrl: suggestion.url
4344
+ };
4345
+ }
4346
+ });
4347
+ }
4348
+ }
4349
+ return responseMessage;
4350
+ }
4351
+ function getPermissionRequestType(type) {
4352
+ switch (type) {
4353
+ case "PERMISSION_EMAIL":
4354
+ return "EMAIL";
4355
+ case "PERMISSION_LOCATION_PRECISE":
4356
+ return "LOCATION_PRECISE";
4357
+ default:
4358
+ throw new Error("Unsupported permission: ".concat(type));
4359
+ }
4360
+ }
4361
+ function getPermissionResponse(botResponse, now) {
4362
+ var _a;
4363
+ var type = getPermissionRequestType(botResponse.system);
4364
+ var outputSpeech = getOutput(botResponse.outputSpeech);
4365
+ var permissionPrimerAccepted = botResponse.data.permissionPrimerAccepted;
4366
+ var permissionDenied = botResponse.data.permissionDenied;
4367
+ return {
4368
+ type: "permissionRequest",
4369
+ timestamp: now,
4370
+ msg: {
4371
+ text: (_a = outputSpeech === null || outputSpeech === void 0 ? void 0 : outputSpeech.displayText) !== null && _a !== void 0 ? _a : "".concat(botResponse.data.permissionRequestTTSContext),
4372
+ permissionRequest: {
4373
+ time: now,
4374
+ type: type,
4375
+ approve: typeof permissionPrimerAccepted === "object" ? responseToMessage({
4376
+ outputSpeech: permissionPrimerAccepted
4377
+ }).msg : undefined,
4378
+ deny: typeof permissionDenied === "object" ? responseToMessage({
4379
+ outputSpeech: permissionDenied
4380
+ }).msg : undefined
4381
+ }
4382
+ },
4383
+ endSession: false,
4384
+ user: undefined //todo: set
4385
+ };
4386
+ }
4387
+
2881
4388
  var PERMISSION_QUESTION_EXPIRATION_MS$1 = 300000; // 5 minutes
2882
4389
  // interface UserLeaveMessage {
2883
4390
  // readonly user: ChatUserInfo;
@@ -8664,6 +10171,7 @@ var StentorServerChat = /** @class */ (function () {
8664
10171
  }());
8665
10172
 
8666
10173
  function createChatServerCore(config, options) {
10174
+ var _a, _b, _c, _d, _e;
8667
10175
  switch (config.type) {
8668
10176
  case "direct":
8669
10177
  return new StentorDirectChat({
@@ -8679,6 +10187,15 @@ function createChatServerCore(config, options) {
8679
10187
  return new StentorRouterChat({
8680
10188
  url: config.serverUrl,
8681
10189
  }, options);
10190
+ case "mcp":
10191
+ return new MCPChat({
10192
+ serverUrl: config.serverUrl,
10193
+ mode: (_a = config.mcp) === null || _a === void 0 ? void 0 : _a.mode,
10194
+ authToken: (_b = config.mcp) === null || _b === void 0 ? void 0 : _b.authToken,
10195
+ debugMode: (_c = config.mcp) === null || _c === void 0 ? void 0 : _c.debugMode,
10196
+ pageContextOverride: (_d = config.mcp) === null || _d === void 0 ? void 0 : _d.pageContextOverride,
10197
+ showAiBadge: (_e = config.mcp) === null || _e === void 0 ? void 0 : _e.showAiBadge,
10198
+ }, options);
8682
10199
  case "local":
8683
10200
  return new StentorLocalChat();
8684
10201
  default:
@@ -8832,6 +10349,79 @@ var DrawerBars = function (props) {
8832
10349
  return (jsx("button", { className: "drawer-bars", tabIndex: props.tabIndex ? Number(props.tabIndex) : 0, "aria-label": "open menu", "aria-hidden": false, onClick: props.onToggle, children: getBars() }));
8833
10350
  };
8834
10351
 
10352
+ /**
10353
+ * Type guard for ChatMsgDetail.
10354
+ * Use this to safely narrow ChatDetail to ChatMsgDetail.
10355
+ */
10356
+ function isChatMsgDetail(chat) {
10357
+ return chat.type === "chat.msg";
10358
+ }
10359
+
10360
+ /**
10361
+ * Formats a suggestion chip for export
10362
+ */
10363
+ function formatSuggestion(option) {
10364
+ if (isChatServerActionLink(option)) {
10365
+ return option.actionUrl ? "[".concat(option.label, "](").concat(option.actionUrl, ")") : option.label;
10366
+ }
10367
+ return option;
10368
+ }
10369
+ /**
10370
+ * Formats chat messages for export
10371
+ */
10372
+ function formatConversation(chats) {
10373
+ return chats
10374
+ .filter(isChatMsgDetail)
10375
+ .map(function (chat) {
10376
+ var _a, _b, _c;
10377
+ var isVisitor = (_a = chat.user.nick) === null || _a === void 0 ? void 0 : _a.startsWith("visitor:");
10378
+ var role = isVisitor ? "User" : "Assistant";
10379
+ var text = ((_b = chat.msg) === null || _b === void 0 ? void 0 : _b.text) || "";
10380
+ var result = "".concat(role, ": ").concat(text);
10381
+ // Add suggestion chips if present
10382
+ var options = (_c = chat.msg) === null || _c === void 0 ? void 0 : _c.options;
10383
+ if (options && options.length > 0) {
10384
+ var suggestions = options.map(formatSuggestion).join(", ");
10385
+ result += "\nSuggestions: ".concat(suggestions);
10386
+ }
10387
+ return result;
10388
+ })
10389
+ .join("\n");
10390
+ }
10391
+ var ExportButton = function (props) {
10392
+ var chats = useSelector(function (state) { return state.chats; });
10393
+ var handleClick = function () { return __awaiter$1(void 0, void 0, void 0, function () {
10394
+ var conversation, textarea;
10395
+ return __generator$1(this, function (_b) {
10396
+ switch (_b.label) {
10397
+ case 0:
10398
+ conversation = formatConversation(chats);
10399
+ _b.label = 1;
10400
+ case 1:
10401
+ _b.trys.push([1, 3, , 4]);
10402
+ return [4 /*yield*/, navigator.clipboard.writeText(conversation)];
10403
+ case 2:
10404
+ _b.sent();
10405
+ return [3 /*break*/, 4];
10406
+ case 3:
10407
+ _b.sent();
10408
+ // Fallback for older browsers using deprecated execCommand
10409
+ // Note: execCommand is deprecated and may be removed in future browsers
10410
+ console.warn("[ExportButton] Using deprecated execCommand fallback for clipboard copy");
10411
+ textarea = document.createElement("textarea");
10412
+ textarea.value = conversation;
10413
+ document.body.appendChild(textarea);
10414
+ textarea.select();
10415
+ document.execCommand("copy");
10416
+ document.body.removeChild(textarea);
10417
+ return [3 /*break*/, 4];
10418
+ case 4: return [2 /*return*/];
10419
+ }
10420
+ });
10421
+ }); };
10422
+ return (jsx("div", { id: "xapp-widget-export", "aria-label": "export conversation", "aria-hidden": false, tabIndex: props.tabIndex ? Number(props.tabIndex) : 0, className: "export-button", onClick: handleClick }));
10423
+ };
10424
+
8835
10425
  var MenuButton = function (props) {
8836
10426
  return (jsx("div", { id: "xapp-widget-menu", "aria-label": "open menu", "aria-hidden": false, tabIndex: props.tabIndex ? Number(props.tabIndex) : 0, className: "menu-button", onClick: props.onClick }));
8837
10427
  };
@@ -8975,7 +10565,7 @@ var closeButtonAriaLabel = "To close widget click on close icon in top right sid
8975
10565
  var ChatHeader = function (props) {
8976
10566
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
8977
10567
  var innerDispatch = useChatDispatch();
8978
- var menuConfig = props.menuConfig, onSubmit = props.onSubmit;
10568
+ var menuConfig = props.menuConfig, onSubmit = props.onSubmit, debugMode = props.debugMode;
8979
10569
  var _r = useState(false), drawerOpen = _r[0], setDrawerState = _r[1]; // false initially
8980
10570
  var menuPosition = (menuConfig === null || menuConfig === void 0 ? void 0 : menuConfig.menuButtonLocation) || "FOOTER";
8981
10571
  var showMenuLeft = menuPosition === "HEADER_LEFT";
@@ -9014,7 +10604,7 @@ var ChatHeader = function (props) {
9014
10604
  ? "status-text-positionLeftNoAvatar"
9015
10605
  : "status-text-positionLeft", "\n ").concat(((_d = props.config) === null || _d === void 0 ? void 0 : _d.alignTextCenter)
9016
10606
  ? "status-text-positionCenter"
9017
- : "", " \n "), children: [jsx("span", { className: "status-text-title", children: getStatusText(props.accountStatus, (_e = props.config) === null || _e === void 0 ? void 0 : _e.status) }), ((_g = (_f = props.config) === null || _f === void 0 ? void 0 : _f.subtitle) === null || _g === void 0 ? void 0 : _g.enabled) && (jsx("span", { className: "status-text-subtitle", children: renderSubtitleText((_j = (_h = props.config) === null || _h === void 0 ? void 0 : _h.subtitle) === null || _j === void 0 ? void 0 : _j.text) }))] }), jsxs(ButtonGroup, { children: [hasRightMenu && (jsx(MenuButton, { onClick: toggleDrawer, tabIndex: menuButtonTabIndex })), props.canRefresh && (jsx(RefreshButton, { onClick: props.refreshOnClick, tabIndex: (_l = (_k = props.config) === null || _k === void 0 ? void 0 : _k.actions) === null || _l === void 0 ? void 0 : _l.refreshTabIndex, showInLeft: false, showInRight: false })), props.canMinimize && (jsx(MinimizeButton, { onClick: props.minimizeOnClick, tabIndex: (_o = (_m = props.config) === null || _m === void 0 ? void 0 : _m.actions) === null || _o === void 0 ? void 0 : _o.minimizeTabIndex, showInRight: false })), props.canCancel && (jsx(CancelButton, { onClick: props.cancelOnClick, tabIndex: (_q = (_p = props.config) === null || _p === void 0 ? void 0 : _p.actions) === null || _q === void 0 ? void 0 : _q.cancelTabIndex }))] })] }), drawerOpen ? (jsx("div", { className: "xa-chat-menu-container", children: jsx(ChatMenu, { openFrom: showMenuRight ? "right" : "left", opened: drawerOpen, tabIndex: menuItemsTabIndex, onItemClick: handleMenuItem, items: menuItems }) })) : (jsx(Fragment, {}))] }));
10607
+ : "", " \n "), children: [jsx("span", { className: "status-text-title", children: getStatusText(props.accountStatus, (_e = props.config) === null || _e === void 0 ? void 0 : _e.status) }), ((_g = (_f = props.config) === null || _f === void 0 ? void 0 : _f.subtitle) === null || _g === void 0 ? void 0 : _g.enabled) && (jsx("span", { className: "status-text-subtitle", children: renderSubtitleText((_j = (_h = props.config) === null || _h === void 0 ? void 0 : _h.subtitle) === null || _j === void 0 ? void 0 : _j.text) }))] }), jsxs(ButtonGroup, { children: [hasRightMenu && (jsx(MenuButton, { onClick: toggleDrawer, tabIndex: menuButtonTabIndex })), debugMode && jsx(ExportButton, {}), props.canRefresh && (jsx(RefreshButton, { onClick: props.refreshOnClick, tabIndex: (_l = (_k = props.config) === null || _k === void 0 ? void 0 : _k.actions) === null || _l === void 0 ? void 0 : _l.refreshTabIndex, showInLeft: false, showInRight: false })), props.canMinimize && (jsx(MinimizeButton, { onClick: props.minimizeOnClick, tabIndex: (_o = (_m = props.config) === null || _m === void 0 ? void 0 : _m.actions) === null || _o === void 0 ? void 0 : _o.minimizeTabIndex, showInRight: false })), props.canCancel && (jsx(CancelButton, { onClick: props.cancelOnClick, tabIndex: (_q = (_p = props.config) === null || _p === void 0 ? void 0 : _p.actions) === null || _q === void 0 ? void 0 : _q.cancelTabIndex }))] })] }), drawerOpen ? (jsx("div", { className: "xa-chat-menu-container", children: jsx(ChatMenu, { openFrom: showMenuRight ? "right" : "left", opened: drawerOpen, tabIndex: menuItemsTabIndex, onItemClick: handleMenuItem, items: menuItems }) })) : (jsx(Fragment, {}))] }));
9018
10608
  };
9019
10609
 
9020
10610
  var UnknownMessage = function () { return jsx(Fragment, {}); };
@@ -9028,7 +10618,8 @@ var ChatMessagePart = function (props) {
9028
10618
  var containerClass = "xappw-chat-msg-part" +
9029
10619
  (position === "below" ? " xappw-chat-msg-part--avatar-below" : "") +
9030
10620
  (position === "bottom" ? " xappw-chat-msg-part--avatar-bottom" : "") +
9031
- (props.fullWidth ? " xappw-chat-msg-part--full-width" : "");
10621
+ (props.fullWidth ? " xappw-chat-msg-part--full-width" : "") +
10622
+ (props.isStreaming ? " xappw-chat-msg-part--streaming" : "");
9032
10623
  var user = props.user, hideUserInfo = props.hideUserInfo;
9033
10624
  // Hide user info if hideUserInfo is true and position is "bottom"
9034
10625
  var shouldHideUserInfo = hideUserInfo && position === "bottom";
@@ -9526,12 +11117,169 @@ var ChatPermissionMessage = function (props) {
9526
11117
  return (jsxs("div", { className: "chat-msg", children: [jsx("span", { className: "message-sr-only", children: "at " + props.time + (agentMessage ? " the bot said" : " the user said") }), jsxs("div", { className: "buttons-container", children: [jsx(ActionButton, { label: allowLabel, addClass: "button", onClick: handleAllow }), jsx(ActionButton, { label: denyLabel, addClass: "button", onClick: handleDeny })] })] }));
9527
11118
  };
9528
11119
 
11120
+ var CopyButton = function (_a) {
11121
+ var text = _a.text;
11122
+ var _b = useState(false), copied = _b[0], setCopied = _b[1];
11123
+ var handleCopy = function (e) { return __awaiter$1(void 0, void 0, void 0, function () {
11124
+ var textarea;
11125
+ return __generator$1(this, function (_b) {
11126
+ switch (_b.label) {
11127
+ case 0:
11128
+ e.stopPropagation();
11129
+ _b.label = 1;
11130
+ case 1:
11131
+ _b.trys.push([1, 3, , 4]);
11132
+ return [4 /*yield*/, navigator.clipboard.writeText(text)];
11133
+ case 2:
11134
+ _b.sent();
11135
+ setCopied(true);
11136
+ setTimeout(function () { return setCopied(false); }, 1500);
11137
+ return [3 /*break*/, 4];
11138
+ case 3:
11139
+ _b.sent();
11140
+ textarea = document.createElement("textarea");
11141
+ textarea.value = text;
11142
+ document.body.appendChild(textarea);
11143
+ textarea.select();
11144
+ document.execCommand("copy");
11145
+ document.body.removeChild(textarea);
11146
+ setCopied(true);
11147
+ setTimeout(function () { return setCopied(false); }, 1500);
11148
+ return [3 /*break*/, 4];
11149
+ case 4: return [2 /*return*/];
11150
+ }
11151
+ });
11152
+ }); };
11153
+ return (jsx("button", { className: "tool-call-item__copy-btn", onClick: handleCopy, title: "Copy to clipboard", children: copied ? "✓" : "⧉" }));
11154
+ };
11155
+ /**
11156
+ * Gets the display text for a tool call, using fallback chain:
11157
+ * label -> displayName -> toolName -> "Working..."
11158
+ */
11159
+ var getDisplayLabel = function (toolCall) {
11160
+ var _a, _b, _c;
11161
+ return (_c = (_b = (_a = toolCall.label) !== null && _a !== void 0 ? _a : toolCall.displayName) !== null && _b !== void 0 ? _b : toolCall.name) !== null && _c !== void 0 ? _c : "Working...";
11162
+ };
11163
+ /**
11164
+ * User-friendly tool progress item (non-debug mode)
11165
+ * Shows just the label with a spinner or checkmark
11166
+ */
11167
+ var ToolProgressItem = function (_a) {
11168
+ var toolCall = _a.toolCall;
11169
+ var label = getDisplayLabel(toolCall);
11170
+ return (jsxs("div", { className: "tool-progress-item ".concat(toolCall.isExecuting ? "tool-progress-item--executing" : "", " ").concat(toolCall.error ? "tool-progress-item--error" : ""), children: [jsx("span", { className: "tool-progress-item__icon", children: toolCall.isExecuting ? (jsx("span", { className: "tool-progress-item__spinner", "aria-label": "executing" })) : toolCall.error ? (jsx("span", { className: "tool-progress-item__status tool-progress-item__status--error", children: "!" })) : (jsx("span", { className: "tool-progress-item__status tool-progress-item__status--success", children: "\u2713" })) }), jsx("span", { className: "tool-progress-item__label", children: label })] }));
11171
+ };
11172
+ /**
11173
+ * Debug mode tool call item with expandable details
11174
+ * Shows label, tool name, and expandable input/output
11175
+ */
11176
+ var ToolCallItem = function (_a) {
11177
+ var toolCall = _a.toolCall;
11178
+ var _b = useState(false), isExpanded = _b[0], setIsExpanded = _b[1];
11179
+ var toggleExpanded = function () { return setIsExpanded(!isExpanded); };
11180
+ var formatJson = function (data) {
11181
+ if (data === undefined || data === null)
11182
+ return "";
11183
+ try {
11184
+ // If it's a string, try to parse it as JSON first (server may send stringified JSON)
11185
+ if (typeof data === "string") {
11186
+ try {
11187
+ var parsed = JSON.parse(data);
11188
+ return JSON.stringify(parsed, null, 2);
11189
+ }
11190
+ catch (_a) {
11191
+ // Not valid JSON, return as-is
11192
+ return data;
11193
+ }
11194
+ }
11195
+ return JSON.stringify(data, null, 2);
11196
+ }
11197
+ catch (_b) {
11198
+ return String(data);
11199
+ }
11200
+ };
11201
+ var label = getDisplayLabel(toolCall);
11202
+ var duration = toolCall.endTime
11203
+ ? "".concat(((toolCall.endTime - toolCall.startTime) / 1000).toFixed(2), "s")
11204
+ : null;
11205
+ var hasInput = toolCall.input !== undefined && toolCall.input !== null;
11206
+ var hasResult = toolCall.result !== undefined && toolCall.result !== null;
11207
+ var hasError = !!toolCall.error;
11208
+ return (jsxs("div", { className: "tool-call-item ".concat(toolCall.isExecuting ? "tool-call-item--executing" : ""), children: [jsxs("button", { className: "tool-call-item__header", onClick: toggleExpanded, "aria-expanded": isExpanded, children: [jsx("span", { className: "tool-call-item__icon", children: toolCall.isExecuting ? (jsx("span", { className: "tool-call-item__spinner", "aria-label": "executing" })) : toolCall.error ? (jsx("span", { className: "tool-call-item__status tool-call-item__status--error", children: "!" })) : (jsx("span", { className: "tool-call-item__status tool-call-item__status--success", children: "\u2713" })) }), jsxs("span", { className: "tool-call-item__info", children: [jsx("span", { className: "tool-call-item__label", children: label }), jsx("span", { className: "tool-call-item__name", children: toolCall.name })] }), duration && jsx("span", { className: "tool-call-item__duration", children: duration }), jsx("span", { className: "tool-call-item__chevron ".concat(isExpanded ? "tool-call-item__chevron--expanded" : ""), children: "\u25BE" })] }), isExpanded && (jsxs("div", { className: "tool-call-item__content", children: [hasInput && (jsxs("div", { className: "tool-call-item__section", children: [jsxs("div", { className: "tool-call-item__section-header", children: [jsx("span", { className: "tool-call-item__section-label", children: "Input" }), jsx(CopyButton, { text: formatJson(toolCall.input) })] }), jsx("pre", { className: "tool-call-item__code", children: formatJson(toolCall.input) })] })), hasResult && (jsxs("div", { className: "tool-call-item__section", children: [jsxs("div", { className: "tool-call-item__section-header", children: [jsx("span", { className: "tool-call-item__section-label", children: "Output" }), jsx(CopyButton, { text: formatJson(toolCall.result) })] }), jsx("pre", { className: "tool-call-item__code", children: formatJson(toolCall.result) })] })), hasError && (jsxs("div", { className: "tool-call-item__section", children: [jsxs("div", { className: "tool-call-item__section-header", children: [jsx("span", { className: "tool-call-item__section-label tool-call-item__section-label--error", children: "Error" }), jsx(CopyButton, { text: toolCall.error || "" })] }), jsx("pre", { className: "tool-call-item__code tool-call-item__code--error", children: toolCall.error })] })), !hasInput && !hasResult && !hasError && (jsx("div", { className: "tool-call-item__empty", children: "No data available" }))] }))] }));
11209
+ };
11210
+ var ToolCallDisplay = function (_a) {
11211
+ var toolCalls = _a.toolCalls, _b = _a.debugMode, debugMode = _b === void 0 ? false : _b;
11212
+ if (!toolCalls || toolCalls.length === 0) {
11213
+ return null;
11214
+ }
11215
+ // Debug mode: show all tools with full expandable details
11216
+ if (debugMode) {
11217
+ return (jsxs("div", { className: "tool-call-display", children: [jsxs("div", { className: "tool-call-display__header", children: [jsx("span", { className: "tool-call-display__icon", children: "\u2699" }), jsxs("span", { className: "tool-call-display__title", children: ["Tool Calls (", toolCalls.length, ")"] })] }), jsx("div", { className: "tool-call-display__list", children: toolCalls.map(function (toolCall, index) { return (jsx(ToolCallItem, { toolCall: toolCall }, "".concat(toolCall.name, "-").concat(toolCall.startTime, "-").concat(index))); }) })] }));
11218
+ }
11219
+ // Normal mode: filter out hidden tools and show user-friendly progress
11220
+ var visibleToolCalls = toolCalls.filter(function (tc) { return !tc.hidden; });
11221
+ if (visibleToolCalls.length === 0) {
11222
+ return null;
11223
+ }
11224
+ return (jsx("div", { className: "tool-progress-display", children: visibleToolCalls.map(function (toolCall, index) { return (jsx(ToolProgressItem, { toolCall: toolCall }, "".concat(toolCall.name, "-").concat(toolCall.startTime, "-").concat(index))); }) }));
11225
+ };
11226
+
11227
+ /**
11228
+ * Parses basic markdown to HTML.
11229
+ * Supports: bold, italic, links, headers, and unordered lists.
11230
+ */
11231
+ function parseMarkdown(text) {
11232
+ if (!text)
11233
+ return "";
11234
+ var html = text
11235
+ // Escape HTML entities first
11236
+ .replace(/&/g, "&amp;")
11237
+ .replace(/</g, "&lt;")
11238
+ .replace(/>/g, "&gt;")
11239
+ // Headers (must be at start of line)
11240
+ .replace(/^### (.+)$/gm, "<h4>$1</h4>")
11241
+ .replace(/^## (.+)$/gm, "<h3>$1</h3>")
11242
+ .replace(/^# (.+)$/gm, "<h2>$1</h2>")
11243
+ // Bold (** or __)
11244
+ .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
11245
+ .replace(/__(.+?)__/g, "<strong>$1</strong>")
11246
+ // Italic (* or _) - must come after bold
11247
+ .replace(/\*([^*]+?)\*/g, "<em>$1</em>")
11248
+ .replace(/_([^_]+?)_/g, "<em>$1</em>")
11249
+ // Links [text](url)
11250
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
11251
+ // Unordered lists (- or *)
11252
+ .replace(/^[-*] (.+)$/gm, "<li>$1</li>")
11253
+ // Line breaks
11254
+ .replace(/\n/g, "<br>");
11255
+ // Wrap consecutive <li> elements in <ul>
11256
+ html = html.replace(/(<li>.*?<\/li>)(<br>)?/g, "$1");
11257
+ html = html.replace(/(<li>.*?<\/li>)+/g, "<ul>$&</ul>");
11258
+ // Clean up <br> inside <ul>
11259
+ html = html.replace(/<ul>(.*?)<\/ul>/g, function (match) {
11260
+ return match.replace(/<br>/g, "");
11261
+ });
11262
+ return html;
11263
+ }
9529
11264
  var ChatTextMessage = function (props) {
11265
+ var _a;
9530
11266
  var message = props.message;
9531
11267
  var date = new Date(message.timestamp);
9532
11268
  var time = date.getHours() + ":" + date.getMinutes();
9533
- var agentMessage = isAgent(props.message.user.nick);
9534
- return (jsx("div", { className: "chat-msg", children: jsx("div", { className: "chat-text-container", children: jsxs(ChatMessageBubble, { owner: agentMessage ? "others" : "mine", hasTail: agentMessage && !props.sibling, children: [jsx("span", { className: "message-sr-only", children: "at " + time + (agentMessage ? " the bot said" : " the user said") }), jsx("span", { children: message.msg.text })] }) }) }));
11269
+ var agentMessage = isAgent((_a = props.message.user) === null || _a === void 0 ? void 0 : _a.nick);
11270
+ var isStreaming = message.isStreaming;
11271
+ // Parse markdown for agent messages
11272
+ var parsedHtml = useMemo(function () {
11273
+ if (agentMessage && message.msg.text) {
11274
+ return parseMarkdown(message.msg.text);
11275
+ }
11276
+ return null;
11277
+ }, [agentMessage, message.msg.text]);
11278
+ // No tail for streaming messages (or messages that were streamed)
11279
+ var wasStreamed = message.wasStreamed;
11280
+ var showTail = agentMessage && !props.sibling && !isStreaming && !wasStreamed;
11281
+ var hasToolCalls = props.toolCalls && props.toolCalls.length > 0;
11282
+ return (jsxs("div", { className: "chat-msg".concat(isStreaming ? " chat-msg--streaming" : ""), children: [hasToolCalls && (jsx(ToolCallDisplay, { toolCalls: props.toolCalls, debugMode: props.debugMode })), jsx("div", { className: "chat-text-container", children: jsxs(ChatMessageBubble, { owner: agentMessage ? "others" : "mine", hasTail: showTail, children: [jsx("span", { className: "message-sr-only", children: "at " + time + (agentMessage ? (isStreaming ? " the bot is typing" : " the bot said") : " the user said") }), parsedHtml ? (jsx("span", { className: "chat-msg__content", dangerouslySetInnerHTML: { __html: parsedHtml } })) : (jsx("span", { className: "chat-msg__content", children: message.msg.text })), isStreaming && jsx("span", { className: "streaming-cursor", "aria-hidden": "true" })] }) })] }));
9535
11283
  };
9536
11284
 
9537
11285
  var ChatScheduleWidget = function (props) {
@@ -9545,6 +11293,24 @@ var ChatScheduleWidget = function (props) {
9545
11293
  return (jsx("div", { className: "chat-schedule-button-container", children: jsxs("button", { className: "chat-schedule-button", onClick: handleClick, children: [jsx("i", { className: "fa fa-lg fa-calendar" }), jsx("span", { children: display.label || "Schedule Now!" })] }) }));
9546
11294
  };
9547
11295
 
11296
+ /**
11297
+ * Displays source links below a chat message.
11298
+ * Designed to be compact and unobtrusive, unlike suggestion chips.
11299
+ */
11300
+ var SourceLinks = function (props) {
11301
+ var sources = props.sources, _a = props.prefix, prefix = _a === void 0 ? "Sources:" : _a, onSourceClick = props.onSourceClick;
11302
+ if (!sources || sources.length === 0) {
11303
+ return null;
11304
+ }
11305
+ var handleClick = function (source, e) {
11306
+ if (onSourceClick) {
11307
+ e.preventDefault();
11308
+ onSourceClick(source);
11309
+ }
11310
+ };
11311
+ return (jsxs("div", { className: "source-links", children: [prefix && jsx("span", { className: "source-links__prefix", children: prefix }), jsx("span", { className: "source-links__list", children: sources.map(function (source, index) { return (jsxs("span", { className: "source-links__item", children: [jsx("a", { href: source.url, target: source.newTab !== false ? "_blank" : "_self", rel: source.newTab !== false ? "noopener noreferrer" : undefined, className: "source-links__link", onClick: function (e) { return handleClick(source, e); }, title: source.url, children: source.title }), index < sources.length - 1 && (jsx("span", { className: "source-links__separator", children: "\u00B7" }))] }, index)); }) })] }));
11312
+ };
11313
+
9548
11314
  function getClassName(msg) {
9549
11315
  return isAgent(msg.user.nick) ? "agent" : "visitor";
9550
11316
  }
@@ -9556,7 +11322,7 @@ var avaKeys = ["text", "html", "card", "list"];
9556
11322
  * @returns
9557
11323
  */
9558
11324
  var ChatMessage = function (props) {
9559
- var _a;
11325
+ var _a, _b, _c;
9560
11326
  var middleware = props.messageMiddleware || StandardMiddlewares;
9561
11327
  var chatConfig = useContext(ChatConfigContext);
9562
11328
  // console.log(`########### chatConfig: ${JSON.stringify(chatConfig, null, 2)}`);
@@ -9566,7 +11332,7 @@ var ChatMessage = function (props) {
9566
11332
  var agentInfo = (_a = props.agents) === null || _a === void 0 ? void 0 : _a[props.message.user.nick];
9567
11333
  var hideUserInfo = (agentInfo === null || agentInfo === void 0 ? void 0 : agentInfo.hideUserInfo) || false;
9568
11334
  function renderByType() {
9569
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
11335
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
9570
11336
  var msg = props.message.msg;
9571
11337
  switch (props.message.type) {
9572
11338
  // TODO: props actually requires it to be "chat.msg". Fix prop typing?
@@ -9574,27 +11340,42 @@ var ChatMessage = function (props) {
9574
11340
  // Here is the deal. If we have text (output speech), then text - card - list - options
9575
11341
  // OR card OR list only. Avatar with text bubble.
9576
11342
  var avaKey = avaKeys.find(function (key) { return !!msg[key]; });
9577
- return (jsxs(Fragment, { children: [msg.text &&
9578
- jsx(ChatMessagePart, { showAvatar: avaKey === "text", user: user, avatarPosition: (_c = (_b = (_a = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _a === void 0 ? void 0 : _a.theme) === null || _b === void 0 ? void 0 : _b.messages) === null || _c === void 0 ? void 0 : _c.avatarPosition, hideUserInfo: hideUserInfo, children: jsx(ChatTextMessage, { message: props.message, sibling: props.sibling }) }), msg.html &&
9579
- jsx(ChatMessagePart, { showAvatar: avaKey === "html", user: user, avatarPosition: (_f = (_e = (_d = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _d === void 0 ? void 0 : _d.theme) === null || _e === void 0 ? void 0 : _e.messages) === null || _f === void 0 ? void 0 : _f.avatarPosition, hideUserInfo: hideUserInfo, children: jsx(ChatMarkdownMessage, { message: props.message, sibling: props.sibling, onOpenUrl: (_g = props.middlewareContext) === null || _g === void 0 ? void 0 : _g.openUrl }) }), msg.displays && middleware && msg.displays.map(function (display, index) {
11343
+ var isStreaming_1 = props.message.isStreaming;
11344
+ var wasStreamed = props.message.wasStreamed;
11345
+ // Tool calls - show progress while tools execute (before text arrives)
11346
+ var toolCalls = props.message.toolCalls;
11347
+ var hasToolCalls = toolCalls && toolCalls.length > 0;
11348
+ var debugMode = (_d = (_c = (_b = (_a = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _a === void 0 ? void 0 : _a.connection) === null || _b === void 0 ? void 0 : _b.mcp) === null || _c === void 0 ? void 0 : _c.debugMode) !== null && _d !== void 0 ? _d : false;
11349
+ // Show tool progress with avatar when no text yet, or above text when text exists
11350
+ var showToolProgressWithAvatar = hasToolCalls && !msg.text;
11351
+ return (jsxs(Fragment, { children: [showToolProgressWithAvatar && (jsx(ChatMessagePart, { showAvatar: true, user: user, avatarPosition: (_g = (_f = (_e = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _e === void 0 ? void 0 : _e.theme) === null || _f === void 0 ? void 0 : _f.messages) === null || _g === void 0 ? void 0 : _g.avatarPosition, hideUserInfo: hideUserInfo, isStreaming: true, children: jsx("div", { className: "chat-msg", children: jsx(ToolCallDisplay, { toolCalls: toolCalls, debugMode: debugMode }) }) })), msg.text && (jsx(ChatMessagePart, { showAvatar: avaKey === "text", user: user, avatarPosition: (_k = (_j = (_h = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _h === void 0 ? void 0 : _h.theme) === null || _j === void 0 ? void 0 : _j.messages) === null || _k === void 0 ? void 0 : _k.avatarPosition, hideUserInfo: hideUserInfo, isStreaming: isStreaming_1 || wasStreamed, children: jsx(ChatTextMessage, { message: props.message, sibling: props.sibling, user: user, toolCalls: hasToolCalls ? toolCalls : undefined, debugMode: debugMode }) })), msg.html &&
11352
+ jsx(ChatMessagePart, { showAvatar: avaKey === "html", user: user, avatarPosition: (_o = (_m = (_l = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _l === void 0 ? void 0 : _l.theme) === null || _m === void 0 ? void 0 : _m.messages) === null || _o === void 0 ? void 0 : _o.avatarPosition, hideUserInfo: hideUserInfo, children: jsx(ChatMarkdownMessage, { message: props.message, sibling: props.sibling, onOpenUrl: (_p = props.middlewareContext) === null || _p === void 0 ? void 0 : _p.openUrl }) }), msg.displays && middleware && msg.displays.map(function (display, index) {
9580
11353
  if (display.type === "ScheduleButton") {
9581
11354
  return (jsx(ChatScheduleWidget, { minimizeOnClick: props.minimizeOnClick, display: display }));
9582
11355
  }
9583
11356
  var Middleware = middleware;
9584
11357
  return (jsx(Middleware, { msg: display, ctx: props.middlewareContext }, index));
9585
11358
  }), msg.permissionRequest && ctx &&
9586
- jsx(ChatMessagePart, { showAvatar: avaKey === "permissionRequest", user: user, avatarPosition: (_k = (_j = (_h = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _h === void 0 ? void 0 : _h.theme) === null || _j === void 0 ? void 0 : _j.messages) === null || _k === void 0 ? void 0 : _k.avatarPosition, hideUserInfo: hideUserInfo, children: jsx(ChatPermissionMessage, { message: props.message, sibling: props.sibling, ctx: ctx }) })] }));
11359
+ jsx(ChatMessagePart, { showAvatar: avaKey === "permissionRequest", user: user, avatarPosition: (_s = (_r = (_q = chatConfig === null || chatConfig === void 0 ? void 0 : chatConfig.env) === null || _q === void 0 ? void 0 : _q.theme) === null || _r === void 0 ? void 0 : _r.messages) === null || _s === void 0 ? void 0 : _s.avatarPosition, hideUserInfo: hideUserInfo, children: jsx(ChatPermissionMessage, { message: props.message, sibling: props.sibling, ctx: ctx }) })] }));
9587
11360
  }
9588
11361
  return (jsx(Fragment, {}));
9589
11362
  }
9590
- function renderTimestamp() {
11363
+ function renderTimestampAndSources() {
11364
+ var _a;
9591
11365
  var timestamp = props.message.timestamp;
9592
11366
  var ts = new Date(timestamp);
9593
11367
  var timeAgo = getTimeAgo(ts);
9594
- return (jsx("div", { className: "chat-msg-timestamp ".concat(isAgent(props.message.user.nick) ? "agent" : "visitor"), children: jsx("span", { children: timeAgo }) }));
9595
- }
11368
+ var sources = (_a = props.message.msg) === null || _a === void 0 ? void 0 : _a.sources;
11369
+ var hasSources = sources && sources.length > 0;
11370
+ var isAgentMessage = isAgent(props.message.user.nick);
11371
+ return (jsxs("div", { className: "chat-msg-footer ".concat(isAgentMessage ? "agent" : "visitor"), children: [jsx("span", { className: "chat-msg-timestamp", children: timeAgo }), hasSources && (jsx(SourceLinks, { sources: sources.map(function (s) { return ({ title: s.title, url: s.url, newTab: s.newTab }); }) }))] }));
11372
+ }
11373
+ // Don't show timestamp/sources while streaming or if message has no content yet
11374
+ var isStreaming = props.message.isStreaming;
11375
+ var hasContent = !!(((_b = props.message.msg) === null || _b === void 0 ? void 0 : _b.text) || ((_c = props.message.msg) === null || _c === void 0 ? void 0 : _c.html));
11376
+ var showFooter = !isStreaming && hasContent;
9596
11377
  // empty
9597
- return (jsx("div", { className: "chat-msg-container-wrapper ".concat(isAgent(props.message.user.nick) ? "agent" : "visitor", " ").concat(props.sibling ? "sibling" : ""), children: jsxs("div", { className: "chat-msg-container ".concat(getClassName(props.message)), children: [renderByType(), renderTimestamp()] }) }));
11378
+ return (jsx("div", { className: "chat-msg-container-wrapper ".concat(isAgent(props.message.user.nick) ? "agent" : "visitor", " ").concat(props.sibling ? "sibling" : ""), children: jsxs("div", { className: "chat-msg-container ".concat(getClassName(props.message)), children: [renderByType(), showFooter && renderTimestampAndSources()] }) }));
9598
11379
  };
9599
11380
 
9600
11381
  /**
@@ -33546,7 +35327,7 @@ var ChatWidgetConnected = function (props) {
33546
35327
  * Exported for use by StaticChatWidgetContainer to avoid infinite loops.
33547
35328
  */
33548
35329
  var ChatWidgetUI = function (props) {
33549
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9;
35330
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14;
33550
35331
  var innerDispatch = useChatDispatch();
33551
35332
  var dispatch = useChatServerDispatch();
33552
35333
  // From Redux
@@ -33576,12 +35357,12 @@ var ChatWidgetUI = function (props) {
33576
35357
  chatState.visuals = {};
33577
35358
  }
33578
35359
  // Our state - pull from storage
33579
- var _10 = useState((!canMinimize && !canCancel) ||
35360
+ var _15 = useState((!canMinimize && !canCancel) ||
33580
35361
  // !!get("visible") ||
33581
35362
  chatState.visuals.visible ||
33582
35363
  (((_m = props.config) === null || _m === void 0 ? void 0 : _m.autoOpenOnWidth) &&
33583
- window.matchMedia("(min-width: ".concat((_o = props.config) === null || _o === void 0 ? void 0 : _o.autoOpenOnWidth, ")")).matches)), visible = _10[0], setVisibleState = _10[1];
33584
- var _11 = useState(false); _11[0]; var setTypingState = _11[1]; // false initially - state kept for potential external observers
35364
+ window.matchMedia("(min-width: ".concat((_o = props.config) === null || _o === void 0 ? void 0 : _o.autoOpenOnWidth, ")")).matches)), visible = _15[0], setVisibleState = _15[1];
35365
+ var _16 = useState(false); _16[0]; var setTypingState = _16[1]; // false initially - state kept for potential external observers
33585
35366
  // Ref to track typing state for use in timeout callbacks
33586
35367
  var typingRef = useRef(false);
33587
35368
  // Timeout ref for debouncing "stop typing" events
@@ -33627,7 +35408,7 @@ var ChatWidgetUI = function (props) {
33627
35408
  };
33628
35409
  // eslint-disable-next-line react-hooks/exhaustive-deps
33629
35410
  }, []);
33630
- var _12 = useState(!document.hidden), isTabVisible = _12[0], setIsTabVisible = _12[1];
35411
+ var _17 = useState(!document.hidden), isTabVisible = _17[0], setIsTabVisible = _17[1];
33631
35412
  useEffect(function () {
33632
35413
  var handleVisibilityChange = function () {
33633
35414
  setIsTabVisible(!document.hidden);
@@ -33770,7 +35551,16 @@ var ChatWidgetUI = function (props) {
33770
35551
  dispatch(sendFile(file));
33771
35552
  }
33772
35553
  function getVisibilityClass() {
33773
- return visible ? "visible" : "";
35554
+ var _a;
35555
+ if (visible) {
35556
+ return "visible";
35557
+ }
35558
+ // Skip hide animation on initial page load when widget was already closed
35559
+ // This prevents the "flash" of the close animation running on mount
35560
+ if (!((_a = chatState.visuals) === null || _a === void 0 ? void 0 : _a.hasInteracted)) {
35561
+ return "widget-container--initial-hidden";
35562
+ }
35563
+ return "";
33774
35564
  }
33775
35565
  function openRestartConfirmationModal() {
33776
35566
  // Interesting, this call the modalRef of the restart modal
@@ -33830,8 +35620,8 @@ var ChatWidgetUI = function (props) {
33830
35620
  }));
33831
35621
  }
33832
35622
  // Action Bar state and handlers
33833
- var _13 = useState(false), formModalOpen = _13[0], setFormModalOpen = _13[1];
33834
- var _14 = useState(null), activeFormConfig = _14[0], setActiveFormConfig = _14[1];
35623
+ var _18 = useState(false), formModalOpen = _18[0], setFormModalOpen = _18[1];
35624
+ var _19 = useState(null), activeFormConfig = _19[0], setActiveFormConfig = _19[1];
33835
35625
  var handleFormButtonClick = useCallback(function (formButton) {
33836
35626
  // If form-widget is configured, use its openForm API
33837
35627
  // The form-widget script should already be pre-loaded
@@ -33945,7 +35735,9 @@ var ChatWidgetUI = function (props) {
33945
35735
  avatarPath: config.avatarUrl,
33946
35736
  display_name: "Agent",
33947
35737
  };
33948
- return (jsxs(Fragment, { children: [jsxs("div", { className: "widget-container ".concat(modeClass, " ").concat(getVisibilityClass()).concat(actionBarEnabled ? " widget-container--with-action-bar" : ""), children: [jsx(WidgetStylesheet, { theme: config === null || config === void 0 ? void 0 : config.theme }), jsx(ChatHeader, { accountStatus: chatState.accountStatus, refreshOnClick: handleRestartClick, minimizeOnClick: handleMinimizeClick, cancelOnClick: handleCancelClick, agent: widgetAgent, canRefresh: canRefresh, canMinimize: canMinimize, canCancel: canCancel, config: config === null || config === void 0 ? void 0 : config.header, menuConfig: config.menu, onSubmit: handleOnSubmit }), jsx(MessageList, { visible: visible, queuePosition: chatState.queuePosition, isChatting: chatState.isChatting, isOffline: isOffline, messages: messages, agents: chatState.agents, agent: config === null || config === void 0 ? void 0 : config.agent, lastRatingRequestTimestamp: chatState.lastRatingRequestTimestamp, hasRating: chatState.hasRating, visitorId: chatState.visitorId, hasWsButton: !!chatState.wsButton, messageMiddleware: props.messageMiddleware, textTypingStatusEnabled: (_x = (_w = props.config) === null || _w === void 0 ? void 0 : _w.typingStatus) === null || _x === void 0 ? void 0 : _x.textTypingStatusEnabled, disableAutoScroll: props.disableAutoScroll, onSend: handleSendMessage, onWrite: handleWriteMessage, onOpenUrl: handleOpenUrl, minimizeOnClick: handleMinimizeClick }), jsx("div", { className: "xa-spinner-container ".concat(visible && connectionStatus === "pending" ? "visible" : ""), children: jsx("div", { className: "xa-spinner" }) }), connectionStatus === "offline" && jsx(ServerOffline, {}), chatState.wsButton && visible && (jsx(WsButton, { button: chatState.wsButton, onPress: handleWsButtonPress })), jsx(ChatFooter, { isAdmin: config === null || config === void 0 ? void 0 : config.isAdmin, isChatting: chatState.isChatting, placeholder: (_y = config === null || config === void 0 ? void 0 : config.input) === null || _y === void 0 ? void 0 : _y.placeholder, sendButtonIcon: (_0 = (_z = config === null || config === void 0 ? void 0 : config.footer) === null || _z === void 0 ? void 0 : _z.sendButton) === null || _0 === void 0 ? void 0 : _0.icon, sendButtonIconHover: (_2 = (_1 = config === null || config === void 0 ? void 0 : config.footer) === null || _1 === void 0 ? void 0 : _1.sendButton) === null || _2 === void 0 ? void 0 : _2.iconHover, sendButtonIconDisabled: (_4 = (_3 = config === null || config === void 0 ? void 0 : config.footer) === null || _3 === void 0 ? void 0 : _3.sendButton) === null || _4 === void 0 ? void 0 : _4.iconDisabled, visible: visible, hasWsButton: !!chatState.wsButton, menuConfig: (_5 = props.config) === null || _5 === void 0 ? void 0 : _5.menu, footerConfig: (_6 = props.config) === null || _6 === void 0 ? void 0 : _6.footer, inputConfig: (_7 = props.config) === null || _7 === void 0 ? void 0 : _7.input, disabled: previewMode, onChange: handleOnChange, onSubmit: handleOnSubmit, onFileUpload: handleFileUpload }), jsx("div", { className: "restartModal", ref: modalRef, onClick: handleRestartModalCloseClick, children: jsx(ModalContent, { onClose: handleRestartModalCloseClick, onReset: handleReset }) })] }), actionBarEnabled && config.actionBar ? (jsxs(Fragment, { children: [jsx(ActionBar, { config: config.actionBar, visible: visible, chatDisabled: config.disabled, onChatClick: chatButtonOnClick, onChatMinimize: handleMinimizeClick, onFormClick: handleFormButtonClick }), formModalOpen && activeFormConfig && (jsx(FormModal, { config: activeFormConfig, widgetEnv: config, onClose: handleFormModalClose }))] })) : (jsx(ChatButton, { addClass: getVisibilityClass(), onClick: chatButtonOnClick, config: config === null || config === void 0 ? void 0 : config.cta, imageUrl: (_8 = config === null || config === void 0 ? void 0 : config.chatButton) === null || _8 === void 0 ? void 0 : _8.imageUrl, visible: visible, hasInteracted: (_9 = chatState.visuals) === null || _9 === void 0 ? void 0 : _9.hasInteracted, onCtaDismiss: handleCtaDismiss })), jsx(ErrorOverlay, { enableErrorOverlay: config === null || config === void 0 ? void 0 : config.enableErrorOverlay })] }));
35738
+ return (jsxs(Fragment, { children: [jsxs("div", { className: "widget-container ".concat(modeClass, " ").concat(getVisibilityClass()).concat(actionBarEnabled ? " widget-container--with-action-bar" : ""), children: [jsx(WidgetStylesheet, { theme: config === null || config === void 0 ? void 0 : config.theme }), jsx(ChatHeader, { accountStatus: chatState.accountStatus, refreshOnClick: handleRestartClick, minimizeOnClick: handleMinimizeClick, cancelOnClick: handleCancelClick, agent: widgetAgent, canRefresh: canRefresh, canMinimize: canMinimize, canCancel: canCancel, config: config === null || config === void 0 ? void 0 : config.header, menuConfig: config.menu, debugMode: (_y = (_x = (_w = props.config) === null || _w === void 0 ? void 0 : _w.connection) === null || _x === void 0 ? void 0 : _x.mcp) === null || _y === void 0 ? void 0 : _y.debugMode, onSubmit: handleOnSubmit }), jsx(MessageList, { visible: visible, queuePosition: chatState.queuePosition, isChatting: chatState.isChatting, isOffline: isOffline, messages: messages, agents: chatState.agents, agent: config === null || config === void 0 ? void 0 : config.agent, lastRatingRequestTimestamp: chatState.lastRatingRequestTimestamp, hasRating: chatState.hasRating, visitorId: chatState.visitorId, hasWsButton: !!chatState.wsButton, messageMiddleware: props.messageMiddleware, textTypingStatusEnabled: (_0 = (_z = props.config) === null || _z === void 0 ? void 0 : _z.typingStatus) === null || _0 === void 0 ? void 0 : _0.textTypingStatusEnabled, disableAutoScroll: props.disableAutoScroll, onSend: handleSendMessage, onWrite: handleWriteMessage, onOpenUrl: handleOpenUrl, minimizeOnClick: handleMinimizeClick }), jsx("div", { className: "xa-spinner-container ".concat(visible && connectionStatus === "pending" ? "visible" : ""), children: jsx("div", { className: "xa-spinner" }) }), connectionStatus === "offline" && jsx(ServerOffline, {}), chatState.wsButton && visible && (jsx(WsButton, { button: chatState.wsButton, onPress: handleWsButtonPress })), jsx(ChatFooter, { isAdmin: config === null || config === void 0 ? void 0 : config.isAdmin, isChatting: chatState.isChatting, placeholder: (_1 = config === null || config === void 0 ? void 0 : config.input) === null || _1 === void 0 ? void 0 : _1.placeholder, sendButtonIcon: (_3 = (_2 = config === null || config === void 0 ? void 0 : config.footer) === null || _2 === void 0 ? void 0 : _2.sendButton) === null || _3 === void 0 ? void 0 : _3.icon, sendButtonIconHover: (_5 = (_4 = config === null || config === void 0 ? void 0 : config.footer) === null || _4 === void 0 ? void 0 : _4.sendButton) === null || _5 === void 0 ? void 0 : _5.iconHover, sendButtonIconDisabled: (_7 = (_6 = config === null || config === void 0 ? void 0 : config.footer) === null || _6 === void 0 ? void 0 : _6.sendButton) === null || _7 === void 0 ? void 0 : _7.iconDisabled, visible: visible, hasWsButton: !!chatState.wsButton, menuConfig: (_8 = props.config) === null || _8 === void 0 ? void 0 : _8.menu, footerConfig: (_9 = props.config) === null || _9 === void 0 ? void 0 : _9.footer, inputConfig: (_10 = props.config) === null || _10 === void 0 ? void 0 : _10.input, disabled: previewMode, onChange: handleOnChange, onSubmit: handleOnSubmit, onFileUpload: handleFileUpload }), jsx("div", { className: "restartModal", ref: modalRef, onClick: handleRestartModalCloseClick, children: jsx(ModalContent, { onClose: handleRestartModalCloseClick, onReset: handleReset }) })] }), actionBarEnabled && config.actionBar ? (jsxs(Fragment, { children: [jsx(ActionBar, { config: __assign(__assign({}, config.actionBar), {
35739
+ // Use actionBar.cta if set, otherwise fall back to widget-level cta
35740
+ cta: (_11 = config.actionBar.cta) !== null && _11 !== void 0 ? _11 : config.cta }), visible: visible, chatDisabled: config.disabled, hasUserInteracted: (_12 = chatState.visuals) === null || _12 === void 0 ? void 0 : _12.hasInteracted, onChatClick: chatButtonOnClick, onChatMinimize: handleMinimizeClick, onFormClick: handleFormButtonClick, onCtaDismiss: handleCtaDismiss }), formModalOpen && activeFormConfig && (jsx(FormModal, { config: activeFormConfig, widgetEnv: config, onClose: handleFormModalClose }))] })) : (jsx(ChatButton, { addClass: visible ? "visible" : "", onClick: chatButtonOnClick, config: config === null || config === void 0 ? void 0 : config.cta, imageUrl: (_13 = config === null || config === void 0 ? void 0 : config.chatButton) === null || _13 === void 0 ? void 0 : _13.imageUrl, visible: visible, hasInteracted: (_14 = chatState.visuals) === null || _14 === void 0 ? void 0 : _14.hasInteracted, onCtaDismiss: handleCtaDismiss })), jsx(ErrorOverlay, { enableErrorOverlay: config === null || config === void 0 ? void 0 : config.enableErrorOverlay })] }));
33949
35741
  };
33950
35742
  /**
33951
35743
  * Top-level wrapper that dispatches between preview mode and connected mode.
@@ -34127,6 +35919,7 @@ function memberLeave(state, detail) {
34127
35919
  }
34128
35920
 
34129
35921
  function resetReducer(state) {
35922
+ var _a;
34130
35923
  if (state === void 0) { state = DEFAULT_STATE; }
34131
35924
  var defaultState = createDefaultState({
34132
35925
  accessToken: state.accessToken,
@@ -34136,6 +35929,8 @@ function resetReducer(state) {
34136
35929
  });
34137
35930
  // If we have an active connection, preserve status to avoid showing offline during reconnect
34138
35931
  var wasOnline = state.connection.connectionStatus === 'online';
35932
+ // Preserve opened state so widget doesn't close on refresh
35933
+ var wasOpened = (_a = state.visuals) === null || _a === void 0 ? void 0 : _a.opened;
34139
35934
  return __assign(__assign({}, defaultState), { connection: __assign(__assign({}, defaultState.connection), { greetingRequested: false,
34140
35935
  // Generate new nonce to trigger server recreation and start fresh session
34141
35936
  nonce: uuid_1(),
@@ -34143,8 +35938,11 @@ function resetReducer(state) {
34143
35938
  connectionStatus: wasOnline ? 'online' : defaultState.connection.connectionStatus }),
34144
35939
  // Preserve accountStatus if we were online to avoid showing offline message during reconnect
34145
35940
  accountStatus: wasOnline ? 'online' : defaultState.accountStatus, visitor: state.visitor, visitorId: state.visitorId,
34146
- // Explicitly reset visuals to clear hasInteracted flag for widget refresh
34147
- visuals: {} });
35941
+ // Reset visuals but preserve opened state so widget stays open during refresh
35942
+ visuals: {
35943
+ opened: wasOpened,
35944
+ hasInteracted: false
35945
+ } });
34148
35946
  }
34149
35947
 
34150
35948
  // Type guard for ChatSystemMessageDetail
@@ -34160,7 +35958,7 @@ function appendMessageToState(state, msg) {
34160
35958
  }
34161
35959
  function update(state, action) {
34162
35960
  var _a, _b, _c, _d;
34163
- var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
35961
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
34164
35962
  if (state === void 0) { state = DEFAULT_STATE; }
34165
35963
  log("action", action);
34166
35964
  if (action.type === "reset") {
@@ -34268,6 +36066,121 @@ function update(state, action) {
34268
36066
  case "chat.typing":
34269
36067
  var agent = state.agents[action.detail.user.nick];
34270
36068
  return __assign(__assign({}, state), { lastTimestamp: (_v = action.detail) === null || _v === void 0 ? void 0 : _v.timestamp, agents: __assign(__assign({}, state.agents), (_d = {}, _d[action.detail.user.nick] = __assign(__assign({}, agent), { typing: action.detail.typing }), _d)) });
36069
+ case "chat.stream.start":
36070
+ // Add placeholder message with streaming state
36071
+ var streamingMsg = {
36072
+ type: "chat.msg",
36073
+ user: action.detail.user,
36074
+ timestamp: action.detail.timestamp,
36075
+ msg: {
36076
+ text: "",
36077
+ },
36078
+ isStreaming: true,
36079
+ };
36080
+ return __assign(__assign({}, newState), { chats: __spreadArray$1(__spreadArray$1([], newState.chats, true), [streamingMsg], false), streamingMessageId: action.detail.messageId });
36081
+ case "chat.stream.chunk": {
36082
+ // Find the streaming message by ID and append text
36083
+ var chunkDetail = action.detail;
36084
+ if (state.streamingMessageId === chunkDetail.messageId) {
36085
+ // Find the streaming message by ID (not by index - other messages could be inserted)
36086
+ var streamingIndex_1 = state.chats.findIndex(function (chat) { return isChatMsgDetail(chat) && chat.isStreaming; });
36087
+ if (streamingIndex_1 >= 0) {
36088
+ var chunkText_1 = chunkDetail.text;
36089
+ return __assign(__assign({}, state), { lastTimestamp: chunkDetail === null || chunkDetail === void 0 ? void 0 : chunkDetail.timestamp, chats: state.chats.map(function (chat, index) {
36090
+ var _a;
36091
+ if (index === streamingIndex_1 && isChatMsgDetail(chat)) {
36092
+ return __assign(__assign({}, chat), { msg: __assign(__assign({}, chat.msg), { text: (((_a = chat.msg) === null || _a === void 0 ? void 0 : _a.text) || "") + chunkText_1 }) });
36093
+ }
36094
+ return chat;
36095
+ }) });
36096
+ }
36097
+ }
36098
+ return state;
36099
+ }
36100
+ case "chat.stream.tool_start": {
36101
+ // Add tool call to the streaming message (in-progress state)
36102
+ log("Tool execution started: ".concat(action.detail.toolName));
36103
+ var toolStartDetail_1 = action.detail;
36104
+ if (state.streamingMessageId === toolStartDetail_1.messageId) {
36105
+ // Find the streaming message by ID (not by index - other messages could be inserted)
36106
+ var streamingIndex_2 = state.chats.findIndex(function (chat) { return isChatMsgDetail(chat) && chat.isStreaming; });
36107
+ if (streamingIndex_2 >= 0) {
36108
+ return __assign(__assign({}, state), { lastTimestamp: toolStartDetail_1.timestamp, chats: state.chats.map(function (chat, index) {
36109
+ if (index === streamingIndex_2 && isChatMsgDetail(chat)) {
36110
+ var existingToolCalls = chat.toolCalls || [];
36111
+ return __assign(__assign({}, chat), { toolCalls: __spreadArray$1(__spreadArray$1([], existingToolCalls, true), [
36112
+ {
36113
+ name: toolStartDetail_1.toolName,
36114
+ toolCallId: toolStartDetail_1.toolCallId,
36115
+ displayName: toolStartDetail_1.displayName,
36116
+ label: toolStartDetail_1.label,
36117
+ hidden: toolStartDetail_1.hidden,
36118
+ input: toolStartDetail_1.toolInput,
36119
+ startTime: toolStartDetail_1.timestamp,
36120
+ isExecuting: true,
36121
+ },
36122
+ ], false) });
36123
+ }
36124
+ return chat;
36125
+ }) });
36126
+ }
36127
+ }
36128
+ return state;
36129
+ }
36130
+ case "chat.stream.tool_end": {
36131
+ // Update tool call with result in the streaming message
36132
+ log("Tool execution ended: ".concat(action.detail.toolName));
36133
+ var toolEndDetail_1 = action.detail;
36134
+ if (state.streamingMessageId === toolEndDetail_1.messageId) {
36135
+ // Find the streaming message by ID (not by index - other messages could be inserted)
36136
+ var streamingIndex_3 = state.chats.findIndex(function (chat) { return isChatMsgDetail(chat) && chat.isStreaming; });
36137
+ if (streamingIndex_3 >= 0) {
36138
+ return __assign(__assign({}, state), { lastTimestamp: toolEndDetail_1.timestamp, chats: state.chats.map(function (chat, index) {
36139
+ var _a;
36140
+ if (index === streamingIndex_3 && isChatMsgDetail(chat)) {
36141
+ var toolCalls = (_a = chat.toolCalls) === null || _a === void 0 ? void 0 : _a.map(function (tc) {
36142
+ var _a;
36143
+ // Match by toolCallId if available, otherwise fall back to name + isExecuting
36144
+ var isMatch = toolEndDetail_1.toolCallId
36145
+ ? tc.toolCallId === toolEndDetail_1.toolCallId
36146
+ : tc.name === toolEndDetail_1.toolName && tc.isExecuting;
36147
+ if (isMatch) {
36148
+ return __assign(__assign({}, tc), { displayName: toolEndDetail_1.displayName || tc.displayName, label: toolEndDetail_1.label, hidden: (_a = toolEndDetail_1.hidden) !== null && _a !== void 0 ? _a : tc.hidden, result: toolEndDetail_1.toolResult, error: toolEndDetail_1.toolError, endTime: toolEndDetail_1.timestamp, isExecuting: false });
36149
+ }
36150
+ return tc;
36151
+ });
36152
+ return __assign(__assign({}, chat), { toolCalls: toolCalls });
36153
+ }
36154
+ return chat;
36155
+ }) });
36156
+ }
36157
+ }
36158
+ return state;
36159
+ }
36160
+ case "chat.stream.end": {
36161
+ // Finalize the streaming message
36162
+ var endDetail = action.detail;
36163
+ if (state.streamingMessageId === endDetail.messageId) {
36164
+ // Find the streaming message by ID (not by index - other messages could be inserted)
36165
+ var streamingIndex_4 = state.chats.findIndex(function (chat) { return isChatMsgDetail(chat) && chat.isStreaming; });
36166
+ var endStreamingChat = streamingIndex_4 >= 0 ? state.chats[streamingIndex_4] : undefined;
36167
+ // Verify it's the right message using type guard
36168
+ if (streamingIndex_4 >= 0 && endStreamingChat && isChatMsgDetail(endStreamingChat)) {
36169
+ var finalMsg_1 = endDetail.msg;
36170
+ // Preserve tool calls from either the action or the existing message
36171
+ var toolCalls_1 = endDetail.toolCalls || endStreamingChat.toolCalls;
36172
+ // Update chips from message options (same as chat.msg handler)
36173
+ var chips = ((_w = finalMsg_1 === null || finalMsg_1 === void 0 ? void 0 : finalMsg_1.options) === null || _w === void 0 ? void 0 : _w.length) ? finalMsg_1.options : [];
36174
+ return __assign(__assign({}, state), { lastTimestamp: endDetail === null || endDetail === void 0 ? void 0 : endDetail.timestamp, streamingMessageId: undefined, chips: chips, chats: state.chats.map(function (chat, index) {
36175
+ if (index === streamingIndex_4 && isChatMsgDetail(chat)) {
36176
+ return __assign(__assign({}, chat), { msg: finalMsg_1, isStreaming: false, wasStreamed: true, toolCalls: toolCalls_1 });
36177
+ }
36178
+ return chat;
36179
+ }) });
36180
+ }
36181
+ }
36182
+ return state;
36183
+ }
34271
36184
  default:
34272
36185
  return state;
34273
36186
  }