@cleartrip/talos-use-chat-controller 1.5.0 → 1.6.0-beta-260708-2.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.
Files changed (37) hide show
  1. package/dist/ChatDispatcherProvider.d.ts +2 -2
  2. package/dist/ChatDispatcherProvider.d.ts.map +1 -1
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/services/index.d.ts +3 -3
  6. package/dist/services/index.d.ts.map +1 -1
  7. package/dist/services/type.d.ts +17 -6
  8. package/dist/services/type.d.ts.map +1 -1
  9. package/dist/stream/WidgetStore.d.ts +15 -0
  10. package/dist/stream/WidgetStore.d.ts.map +1 -0
  11. package/dist/stream/index.d.ts +4 -0
  12. package/dist/stream/index.d.ts.map +1 -0
  13. package/dist/stream/parser.d.ts +4 -0
  14. package/dist/stream/parser.d.ts.map +1 -0
  15. package/dist/talos-use-chat-controller.browser.cjs.js +1 -1
  16. package/dist/talos-use-chat-controller.browser.cjs.js.map +1 -1
  17. package/dist/talos-use-chat-controller.browser.esm.js +1 -1
  18. package/dist/talos-use-chat-controller.browser.esm.js.map +1 -1
  19. package/dist/talos-use-chat-controller.cjs.js +480 -164
  20. package/dist/talos-use-chat-controller.cjs.js.map +1 -1
  21. package/dist/talos-use-chat-controller.esm.js +484 -169
  22. package/dist/talos-use-chat-controller.esm.js.map +1 -1
  23. package/dist/talos-use-chat-controller.umd.js +483 -167
  24. package/dist/talos-use-chat-controller.umd.js.map +1 -1
  25. package/dist/type.d.ts +35 -3
  26. package/dist/type.d.ts.map +1 -1
  27. package/dist/useChatAction.d.ts +3 -0
  28. package/dist/useChatAction.d.ts.map +1 -1
  29. package/dist/useChatController.d.ts +4 -1
  30. package/dist/useChatController.d.ts.map +1 -1
  31. package/dist/useChatTransport.d.ts +24 -0
  32. package/dist/useChatTransport.d.ts.map +1 -0
  33. package/dist/useContextSummary.d.ts +13 -0
  34. package/dist/useContextSummary.d.ts.map +1 -0
  35. package/dist/util.d.ts +3 -1
  36. package/dist/util.d.ts.map +1 -1
  37. package/package.json +6 -6
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('uuid'), require('@cleartrip/talos-use-chat'), require('@cleartrip/talos-general-utils'), require('@cleartrip/talos-widget-types'), require('@cleartrip/talos-network')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'uuid', '@cleartrip/talos-use-chat', '@cleartrip/talos-general-utils', '@cleartrip/talos-widget-types', '@cleartrip/talos-network'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TalosUseChatController = {}, global.React, global.uuid, global.talosUseChat, global.talosGeneralUtils, global.talosWidgetTypes, global.talosNetwork));
5
- })(this, (function (exports, require$$0, uuid, talosUseChat, talosGeneralUtils, talosWidgetTypes, talosNetwork) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('uuid'), require('@cleartrip/talos-general-utils'), require('@cleartrip/talos-widget-types'), require('@cleartrip/talos-network'), require('@cleartrip/talos-use-chat')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'uuid', '@cleartrip/talos-general-utils', '@cleartrip/talos-widget-types', '@cleartrip/talos-network', '@cleartrip/talos-use-chat'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TalosUseChatController = {}, global.React, global.uuid, global.talosGeneralUtils, global.talosWidgetTypes, global.talosNetwork, global.talosUseChat));
5
+ })(this, (function (exports, require$$0, uuid, talosGeneralUtils, talosWidgetTypes, talosNetwork, talosUseChat) { 'use strict';
6
6
 
7
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
 
@@ -180,22 +180,21 @@
180
180
  var ChatService = (function () {
181
181
  function ChatService(network) {
182
182
  var _a = network !== null && network !== void 0 ? network : {}, headers = _a.headers, body = _a.body, domain = _a.domain;
183
- this.headers = (headers !== null && headers !== void 0 ? headers : {});
183
+ this.headers = __assign(__assign({}, headers), talosGeneralUtils.getSessionIdHeader());
184
184
  this.basePayload = body !== null && body !== void 0 ? body : {};
185
185
  this.domain = domain || '';
186
186
  }
187
- ChatService.prototype.fetchChatId = function () {
187
+ ChatService.prototype.fetchChatId = function (forceNewChat) {
188
+ if (forceNewChat === void 0) { forceNewChat = false; }
188
189
  return __awaiter(this, void 0, void 0, function () {
189
- var referenceId, mergedPayload, mergedHeaders, response;
190
- return __generator(this, function (_a) {
191
- switch (_a.label) {
190
+ var _a, _b, referenceId, _c, pageId, mergedPayload, mergedHeaders, response;
191
+ return __generator(this, function (_d) {
192
+ switch (_d.label) {
192
193
  case 0:
193
- referenceId = this.basePayload.referenceId;
194
- mergedPayload = {
195
- payload: {
194
+ _a = this.basePayload, _b = _a.referenceId, referenceId = _b === void 0 ? "" : _b, _c = _a.pageId, pageId = _c === void 0 ? "" : _c;
195
+ mergedPayload = __assign(__assign({ payload: {
196
196
  tripId: referenceId,
197
- }
198
- };
197
+ } }, (pageId && { pageId: pageId })), { init: forceNewChat });
199
198
  mergedHeaders = __assign({}, this.headers);
200
199
  return [4, talosNetwork.baseFetch({
201
200
  url: API_ENDPOINTS.GET_CHAT_ID,
@@ -205,7 +204,7 @@
205
204
  domain: this.domain,
206
205
  })];
207
206
  case 1:
208
- response = _a.sent();
207
+ response = _d.sent();
209
208
  return [2, response];
210
209
  }
211
210
  });
@@ -356,7 +355,7 @@
356
355
  }());
357
356
 
358
357
  var useChatAction = function (props) {
359
- var sendMessage = props.sendMessage, getPreviousChatById = props.getPreviousChatById, handleCreateNewChat = props.handleCreateNewChat, handleBackButtonClick = props.handleBackButtonClick, handleShowNativeActions = props.handleShowNativeActions, retryUpload = props.retryUpload, retryMessage = props.retryMessage, handleRetryFromError = props.handleRetryFromError, getPreviousChats = props.getPreviousChats, handleFeedbackSubmission = props.handleFeedbackSubmission, triggerTracking = props.triggerTracking, handleCloseCurrentChat = props.handleCloseCurrentChat, handleThumbsDownFeedback = props.handleThumbsDownFeedback, baseTrackingData = props.baseTrackingData;
358
+ var sendMessage = props.sendMessage, getPreviousChatById = props.getPreviousChatById, handleCreateNewChat = props.handleCreateNewChat, handleBackButtonClick = props.handleBackButtonClick, handleShowNativeActions = props.handleShowNativeActions, retryUpload = props.retryUpload, retryMessage = props.retryMessage, handleRetryFromError = props.handleRetryFromError, getPreviousChats = props.getPreviousChats, handleFeedbackSubmission = props.handleFeedbackSubmission, triggerTracking = props.triggerTracking, handleCloseCurrentChat = props.handleCloseCurrentChat, handleThumbsDownFeedback = props.handleThumbsDownFeedback, handleOpenChatbot = props.handleOpenChatbot, handleCloseChatbot = props.handleCloseChatbot, baseTrackingData = props.baseTrackingData, customDispatcher = props.dispatcher;
360
359
  var dispatch = function (action) { return __awaiter(void 0, void 0, void 0, function () {
361
360
  var type, _a, _b, message, rest, id, subType, _c, isNativeActionsEnabled, messageId, messageId, _d, eventName, eventData, mergedEventData, _e, isFeedbackSubmitted, messageId, chatId, feedbackValue, feedbackValue;
362
361
  return __generator(this, function (_f) {
@@ -378,24 +377,26 @@
378
377
  case talosWidgetTypes.ActionType.SET_IS_FEEDBACK_SUBMITTED: return [3, 15];
379
378
  case talosWidgetTypes.ActionType.HANDLE_THUMBS_DOWN_FEEDBACK: return [3, 16];
380
379
  case talosWidgetTypes.ActionType.CLOSE_CURRENT_CHAT: return [3, 17];
380
+ case talosWidgetTypes.ActionType.OPEN_CHATBOT: return [3, 18];
381
+ case talosWidgetTypes.ActionType.CLOSE_CHATBOT: return [3, 19];
381
382
  }
382
- return [3, 18];
383
+ return [3, 20];
383
384
  case 1:
384
385
  _b = action.payload, message = _b.message, rest = __rest(_b, ["message"]);
385
386
  return [4, sendMessage(message, rest)];
386
387
  case 2:
387
388
  _f.sent();
388
- return [3, 19];
389
+ return [3, 23];
389
390
  case 3:
390
391
  id = action.payload.id;
391
392
  return [4, getPreviousChatById(id)];
392
393
  case 4:
393
394
  _f.sent();
394
- return [3, 19];
395
+ return [3, 23];
395
396
  case 5:
396
397
  {
397
398
  handleCreateNewChat();
398
- return [3, 19];
399
+ return [3, 23];
399
400
  }
400
401
  case 6:
401
402
  {
@@ -403,66 +404,80 @@
403
404
  if (subType === talosWidgetTypes.NavigateSubType.BACK) {
404
405
  handleBackButtonClick();
405
406
  }
406
- return [3, 19];
407
+ return [3, 23];
407
408
  }
408
409
  case 7:
409
410
  {
410
411
  _c = action.payload.isNativeActionsEnabled, isNativeActionsEnabled = _c === void 0 ? true : _c;
411
412
  handleShowNativeActions(isNativeActionsEnabled);
412
- return [3, 19];
413
+ return [3, 23];
413
414
  }
414
415
  case 8:
415
416
  messageId = action.payload.messageId;
416
417
  return [4, retryUpload(messageId)];
417
418
  case 9:
418
419
  _f.sent();
419
- return [3, 19];
420
+ return [3, 23];
420
421
  case 10:
421
422
  messageId = action.payload.messageId;
422
423
  return [4, retryMessage(messageId)];
423
424
  case 11:
424
425
  _f.sent();
425
- return [3, 19];
426
+ return [3, 23];
426
427
  case 12:
427
428
  {
428
429
  handleRetryFromError();
429
- return [3, 19];
430
+ return [3, 23];
430
431
  }
431
432
  case 13:
432
433
  {
433
434
  getPreviousChats();
434
- return [3, 19];
435
+ return [3, 23];
435
436
  }
436
437
  case 14:
437
438
  {
438
439
  _d = action.payload, eventName = _d.eventName, eventData = _d.eventData;
439
440
  mergedEventData = __assign(__assign({}, baseTrackingData), eventData);
440
441
  triggerTracking === null || triggerTracking === void 0 ? void 0 : triggerTracking({ eventName: eventName, eventData: mergedEventData });
441
- return [3, 19];
442
+ return [3, 23];
442
443
  }
443
444
  case 15:
444
445
  {
445
446
  _e = action.payload, isFeedbackSubmitted = _e.isFeedbackSubmitted, messageId = _e.messageId, chatId = _e.chatId, feedbackValue = _e.feedbackValue;
446
447
  handleFeedbackSubmission(chatId, messageId, isFeedbackSubmitted, feedbackValue);
447
- return [3, 19];
448
+ return [3, 23];
448
449
  }
449
450
  case 16:
450
451
  {
451
452
  feedbackValue = action.payload.feedbackValue;
452
453
  handleThumbsDownFeedback(feedbackValue);
453
- return [3, 19];
454
+ return [3, 23];
454
455
  }
455
456
  case 17:
456
457
  {
457
458
  handleCloseCurrentChat();
458
- return [3, 19];
459
+ return [3, 23];
459
460
  }
460
461
  case 18:
461
462
  {
462
- console.warn("[useChatAction] Unhandled action type: ".concat(type));
463
+ handleOpenChatbot();
464
+ return [3, 23];
465
+ }
466
+ case 19:
467
+ {
468
+ handleCloseChatbot();
469
+ return [3, 23];
463
470
  }
464
- _f.label = 19;
465
- case 19: return [2];
471
+ case 20:
472
+ if (!customDispatcher) return [3, 22];
473
+ return [4, customDispatcher(action)];
474
+ case 21:
475
+ _f.sent();
476
+ return [3, 23];
477
+ case 22:
478
+ console.warn("[useChatAction] Unhandled action type: ".concat(type));
479
+ _f.label = 23;
480
+ case 23: return [2];
466
481
  }
467
482
  });
468
483
  }); };
@@ -496,6 +511,11 @@
496
511
  ConversationMessageRole["BOT"] = "BOT";
497
512
  })(exports.ConversationMessageRole || (exports.ConversationMessageRole = {}));
498
513
 
514
+ exports.ChatCapability = void 0;
515
+ (function (ChatCapability) {
516
+ ChatCapability["CONVERSATIONAL"] = "conversational";
517
+ ChatCapability["SEARCH"] = "search";
518
+ })(exports.ChatCapability || (exports.ChatCapability = {}));
499
519
  exports.ChatStatus = void 0;
500
520
  (function (ChatStatus) {
501
521
  ChatStatus["ON_GOING"] = "ON_GOING";
@@ -613,6 +633,267 @@
613
633
  var getTurnSequence = function (messages, type) {
614
634
  return messages.filter(function (m) { return m.type === type; }).length;
615
635
  };
636
+ var indexPluginsByType = function (plugins) {
637
+ if (plugins === void 0) { plugins = []; }
638
+ var byType = new Map();
639
+ for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
640
+ var plugin = plugins_1[_i];
641
+ if (byType.has(plugin.type)) {
642
+ console.warn("[talos] Duplicate plugin type \"".concat(plugin.type, "\". Only one plugin per type is allowed; ignoring the extra one."));
643
+ continue;
644
+ }
645
+ byType.set(plugin.type, plugin);
646
+ }
647
+ return byType;
648
+ };
649
+ var getPluginDispatcher = function (pluginsByType) {
650
+ var _a;
651
+ var plugin = pluginsByType.get(talosWidgetTypes.Plugins.DISPATCHER);
652
+ return (_a = plugin === null || plugin === void 0 ? void 0 : plugin.dispatcher) !== null && _a !== void 0 ? _a : undefined;
653
+ };
654
+
655
+ var useContextSummary = function (_a) {
656
+ var chatService = _a.chatService;
657
+ var _b = require$$0.useState(false), isContextSummaryLoading = _b[0], setIsContextSummaryLoading = _b[1];
658
+ var _c = require$$0.useState(null), contextSummary = _c[0], setContextSummary = _c[1];
659
+ var _d = require$$0.useState(null), contextSummaryError = _d[0], setContextSummaryError = _d[1];
660
+ var fetchContextSummary = require$$0.useCallback(function (sessionId) { return __awaiter(void 0, void 0, void 0, function () {
661
+ var payload, response;
662
+ return __generator(this, function (_a) {
663
+ switch (_a.label) {
664
+ case 0:
665
+ _a.trys.push([0, 2, 3, 4]);
666
+ setContextSummaryError(false);
667
+ setIsContextSummaryLoading(true);
668
+ payload = buildBotPayload({ kind: exports.BotMessageKind.INIT }, sessionId);
669
+ return [4, chatService.getBotResponse(payload)];
670
+ case 1:
671
+ response = _a.sent();
672
+ setContextSummary(response);
673
+ return [3, 4];
674
+ case 2:
675
+ _a.sent();
676
+ setContextSummaryError(true);
677
+ return [3, 4];
678
+ case 3:
679
+ setIsContextSummaryLoading(false);
680
+ return [7];
681
+ case 4: return [2];
682
+ }
683
+ });
684
+ }); }, [chatService]);
685
+ return {
686
+ isContextSummaryLoading: isContextSummaryLoading,
687
+ contextSummary: contextSummary,
688
+ contextSummaryError: contextSummaryError,
689
+ fetchContextSummary: fetchContextSummary,
690
+ };
691
+ };
692
+
693
+ var replaceMerge = function (current, incoming) { return (__assign(__assign({}, current), { data: __assign(__assign({}, current.data), incoming) })); };
694
+ var defaultResolver = function () { return replaceMerge; };
695
+ var withStreamMeta = function (w, streamId, isStreaming) {
696
+ var _a;
697
+ return (__assign(__assign({}, w), { metaData: __assign(__assign({}, ((_a = w.metaData) !== null && _a !== void 0 ? _a : {})), { streamId: streamId, isStreaming: isStreaming }) }));
698
+ };
699
+ var WidgetStore = (function () {
700
+ function WidgetStore(mergeFor) {
701
+ if (mergeFor === void 0) { mergeFor = defaultResolver; }
702
+ this.mergeFor = mergeFor;
703
+ this.order = [];
704
+ this.byId = new Map();
705
+ this.autoKey = 0;
706
+ }
707
+ WidgetStore.prototype.reset = function () {
708
+ this.order = [];
709
+ this.byId = new Map();
710
+ this.autoKey = 0;
711
+ };
712
+ WidgetStore.prototype.apply = function (op) {
713
+ if (op.kind === talosWidgetTypes.StreamKind.STANDALONE) {
714
+ this.push("w-".concat(this.autoKey++), op.widget);
715
+ return;
716
+ }
717
+ if (op.kind === talosWidgetTypes.StreamKind.CHUNK) {
718
+ var current = this.byId.get(op.streamId);
719
+ if (!current) {
720
+ this.push(op.streamId, withStreamMeta(op.widget, op.streamId, true));
721
+ }
722
+ else {
723
+ this.push(op.streamId, this.mergeFor(current.type)(current, op.widget.data));
724
+ }
725
+ return;
726
+ }
727
+ var w = this.byId.get(op.streamId);
728
+ if (w)
729
+ this.push(op.streamId, withStreamMeta(w, op.streamId, false));
730
+ };
731
+ WidgetStore.prototype.closeOpenStreams = function () {
732
+ var _this = this;
733
+ this.order.forEach(function (key) {
734
+ var _a, _b;
735
+ var w = _this.byId.get(key);
736
+ if ((_a = w === null || w === void 0 ? void 0 : w.metaData) === null || _a === void 0 ? void 0 : _a.isStreaming) {
737
+ _this.push(key, withStreamMeta(w, (_b = w.metaData.streamId) !== null && _b !== void 0 ? _b : key, false));
738
+ }
739
+ });
740
+ };
741
+ WidgetStore.prototype.toArray = function () {
742
+ var _this = this;
743
+ return this.order
744
+ .map(function (key) { return _this.byId.get(key); })
745
+ .filter(function (w) { return Boolean(w); });
746
+ };
747
+ WidgetStore.prototype.push = function (key, widget) {
748
+ if (!this.byId.has(key))
749
+ this.order.push(key);
750
+ this.byId.set(key, widget);
751
+ };
752
+ return WidgetStore;
753
+ }());
754
+
755
+ var initialParserState = function () { return ({ openStreamId: null }); };
756
+ function frameToOp(frame, state) {
757
+ if ("signal" in frame) {
758
+ if (frame.signal === talosWidgetTypes.Signal.START) {
759
+ state.openStreamId = frame.streamId;
760
+ return null;
761
+ }
762
+ state.openStreamId = null;
763
+ return { kind: talosWidgetTypes.StreamKind.CLOSE, streamId: frame.streamId };
764
+ }
765
+ return state.openStreamId
766
+ ? { kind: talosWidgetTypes.StreamKind.CHUNK, streamId: state.openStreamId, widget: frame }
767
+ : { kind: talosWidgetTypes.StreamKind.STANDALONE, widget: frame };
768
+ }
769
+
770
+ var isLandingFrame = function (frame) {
771
+ return typeof frame === "object" &&
772
+ frame !== null &&
773
+ !("signal" in frame) &&
774
+ !("type" in frame) &&
775
+ ("heading" in frame || "suggestions" in frame);
776
+ };
777
+ var scheduleOncePerFrame = function (fn) {
778
+ var scheduled = false;
779
+ var schedule = typeof requestAnimationFrame !== "undefined"
780
+ ? requestAnimationFrame
781
+ : function (cb) { return setTimeout(cb, 16); };
782
+ return function () {
783
+ if (scheduled)
784
+ return;
785
+ scheduled = true;
786
+ schedule(function () {
787
+ scheduled = false;
788
+ fn();
789
+ });
790
+ };
791
+ };
792
+ var useChatTransport = function (props) {
793
+ var _a = props.protocol, protocol = _a === void 0 ? talosWidgetTypes.Protocol.DEFAULT : _a, network = props.network, chatService = props.chatService, resolveMerge = props.resolveMerge, buildBody = props.buildBody;
794
+ var _b = talosUseChat.useChat({ network: network, buildBody: buildBody }), chat = _b.chat, status = _b.status, chatSend = _b.send, stop = _b.stop;
795
+ var storeRef = require$$0.useRef();
796
+ if (!storeRef.current)
797
+ storeRef.current = new WidgetStore(resolveMerge);
798
+ var stateRef = require$$0.useRef(initialParserState());
799
+ var sinkRef = require$$0.useRef(null);
800
+ var flushRef = require$$0.useRef();
801
+ if (!flushRef.current) {
802
+ flushRef.current = scheduleOncePerFrame(function () {
803
+ if (sinkRef.current)
804
+ sinkRef.current.update(storeRef.current.toArray());
805
+ });
806
+ }
807
+ require$$0.useEffect(function () {
808
+ var store = storeRef.current;
809
+ var onChunk = function (_a) {
810
+ var _b, _c;
811
+ var chunk = _a.chunk;
812
+ if (!sinkRef.current)
813
+ return;
814
+ var envelope;
815
+ try {
816
+ envelope = JSON.parse(chunk);
817
+ }
818
+ catch (_d) {
819
+ return;
820
+ }
821
+ var frame = envelope === null || envelope === void 0 ? void 0 : envelope.data;
822
+ if (!frame)
823
+ return;
824
+ if (isLandingFrame(frame)) {
825
+ (_c = (_b = sinkRef.current).onLanding) === null || _c === void 0 ? void 0 : _c.call(_b, frame);
826
+ return;
827
+ }
828
+ var op = frameToOp(frame, stateRef.current);
829
+ if (op)
830
+ store.apply(op);
831
+ flushRef.current();
832
+ };
833
+ var onComplete = function () {
834
+ var sink = sinkRef.current;
835
+ if (!sink)
836
+ return;
837
+ store.closeOpenStreams();
838
+ sink.update(store.toArray());
839
+ sink.done();
840
+ sinkRef.current = null;
841
+ };
842
+ var onError = function (_a) {
843
+ var error = _a.error;
844
+ var sink = sinkRef.current;
845
+ if (!sink)
846
+ return;
847
+ store.closeOpenStreams();
848
+ sink.error(error);
849
+ sinkRef.current = null;
850
+ };
851
+ var offChunk = chat.on(talosUseChat.ChatEventName.CHUNK, onChunk);
852
+ var offComplete = chat.on(talosUseChat.ChatEventName.COMPLETE, onComplete);
853
+ var offError = chat.on(talosUseChat.ChatEventName.ERROR, onError);
854
+ return function () {
855
+ offChunk();
856
+ offComplete();
857
+ offError();
858
+ };
859
+ }, [chat]);
860
+ var send = require$$0.useCallback(function (payload, sink) { return __awaiter(void 0, void 0, void 0, function () {
861
+ var res, _a, _b, chunks, _c, metadata, error_1;
862
+ var _d;
863
+ return __generator(this, function (_e) {
864
+ switch (_e.label) {
865
+ case 0:
866
+ if (protocol === talosWidgetTypes.Protocol.STREAMED) {
867
+ storeRef.current.reset();
868
+ stateRef.current = initialParserState();
869
+ sinkRef.current = sink;
870
+ chatSend(payload);
871
+ return [2];
872
+ }
873
+ _e.label = 1;
874
+ case 1:
875
+ _e.trys.push([1, 3, , 4]);
876
+ return [4, chatService.getBotResponse(payload)];
877
+ case 2:
878
+ res = _e.sent();
879
+ _a = (_d = res === null || res === void 0 ? void 0 : res.data) !== null && _d !== void 0 ? _d : {}, _b = _a.chunks, chunks = _b === void 0 ? [] : _b, _c = _a.metadata, metadata = _c === void 0 ? {} : _c;
880
+ sink.update(chunks);
881
+ sink.done(metadata);
882
+ return [3, 4];
883
+ case 3:
884
+ error_1 = _e.sent();
885
+ sink.error(error_1);
886
+ return [3, 4];
887
+ case 4: return [2];
888
+ }
889
+ });
890
+ }); }, [protocol, chatSend, chatService]);
891
+ var abort = require$$0.useCallback(function () {
892
+ stop();
893
+ sinkRef.current = null;
894
+ }, [stop]);
895
+ return { chat: chat, status: status, send: send, abort: abort };
896
+ };
616
897
 
617
898
  var BOT_ERROR_RESPONSE = function (errorId, retryPayload) {
618
899
  return {
@@ -663,21 +944,30 @@
663
944
  var ANIMATION_DURATION = 300;
664
945
 
665
946
  var useChatController = function (config) {
666
- var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData;
667
- var _a = talosUseChat.useChat(config), chat = _a.chat, status = _a.status, baseSendMessage = _a.sendMessage, stop = _a.stop;
947
+ var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData, plugins = config.plugins, _a = config.capability; _a === void 0 ? exports.ChatCapability.CONVERSATIONAL : _a; var open = config.open, onOpenChatbot = config.onOpenChatbot, onCloseChatbot = config.onCloseChatbot, protocol = config.protocol, resolveMerge = config.resolveMerge, buildBody = config.buildBody;
668
948
  var chatService = require$$0.useMemo(function () { return new ChatService(network); }, [network]);
669
- var _b = require$$0.useState({}), messages = _b[0], setMessages = _b[1];
670
- var _c = require$$0.useState(false), isInitialLoading = _c[0], setIsInitialLoading = _c[1];
671
- var _d = require$$0.useState(false), isReplyLoading = _d[0], setIsReplyLoading = _d[1];
672
- var _e = require$$0.useState([]), chatStack = _e[0], setChatStack = _e[1];
673
- var _f = require$$0.useState(null), previousChats = _f[0], setPreviousChats = _f[1];
674
- var _g = require$$0.useState(false), previousChatLoading = _g[0], setPreviousChatLoading = _g[1];
675
- var _h = require$$0.useState(null), previousChatError = _h[0], setPreviousChatError = _h[1];
676
- var _j = require$$0.useState(false), showNativeActions = _j[0], setShowNativeActions = _j[1];
677
- var _k = require$$0.useState(false), isNewChat = _k[0], setIsNewChat = _k[1];
949
+ var defaultBuildBody = require$$0.useCallback(function (payload) {
950
+ var _a;
951
+ return (__assign(__assign({}, payload), { payload: __assign(__assign({}, payload.payload), ((_a = network === null || network === void 0 ? void 0 : network.body) !== null && _a !== void 0 ? _a : {})) }));
952
+ }, [network]);
953
+ var pluginsByType = require$$0.useMemo(function () { return indexPluginsByType(plugins); }, [plugins]);
954
+ var dispatcher = require$$0.useMemo(function () { return getPluginDispatcher(pluginsByType); }, [pluginsByType]);
955
+ var _b = useChatTransport({ protocol: protocol, network: network, chatService: chatService, resolveMerge: resolveMerge, buildBody: buildBody !== null && buildBody !== void 0 ? buildBody : defaultBuildBody }), chat = _b.chat, status = _b.status, transportSend = _b.send, stop = _b.abort;
956
+ var _c = require$$0.useState({}), messages = _c[0], setMessages = _c[1];
957
+ var _d = require$$0.useState(false), isInitialLoading = _d[0], setIsInitialLoading = _d[1];
958
+ var _e = require$$0.useState(false), isReplyLoading = _e[0], setIsReplyLoading = _e[1];
959
+ var _f = require$$0.useState([]), chatStack = _f[0], setChatStack = _f[1];
960
+ var _g = require$$0.useState(null), previousChats = _g[0], setPreviousChats = _g[1];
961
+ var _h = require$$0.useState(false), previousChatLoading = _h[0], setPreviousChatLoading = _h[1];
962
+ var _j = require$$0.useState(null), previousChatError = _j[0], setPreviousChatError = _j[1];
963
+ var _k = require$$0.useState(false), showNativeActions = _k[0], setShowNativeActions = _k[1];
964
+ var _l = require$$0.useState(false), isNewChat = _l[0], setIsNewChat = _l[1];
965
+ var _m = useContextSummary({ chatService: chatService }), isContextSummaryLoading = _m.isContextSummaryLoading, contextSummary = _m.contextSummary, contextSummaryError = _m.contextSummaryError, fetchContextSummary = _m.fetchContextSummary;
678
966
  var presentedRef = require$$0.useRef(new Map());
679
967
  var screenRefs = require$$0.useRef([]);
680
968
  var timeoutRef = require$$0.useRef(null);
969
+ var summaryEnabledRef = require$$0.useRef(false);
970
+ var summaryFetchedRef = require$$0.useRef(false);
681
971
  var hasPresented = require$$0.useCallback(function (cid, id) {
682
972
  var _a, _b;
683
973
  return (_b = (_a = presentedRef.current.get(cid)) === null || _a === void 0 ? void 0 : _a.has(id)) !== null && _b !== void 0 ? _b : false;
@@ -702,82 +992,90 @@
702
992
  var _a;
703
993
  return ((_a = chatStack[chatStack.length - 1]) === null || _a === void 0 ? void 0 : _a.id) || "";
704
994
  }, [chatStack]);
995
+ var patchMessageChunks = function (chatId, messageId, widgets) {
996
+ setMessages(function (prev) {
997
+ var _a;
998
+ var chat = prev[chatId];
999
+ if (!chat)
1000
+ return prev;
1001
+ return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? __assign(__assign({}, m), { chunks: widgets }) : m); }) }), _a));
1002
+ });
1003
+ };
705
1004
  var handleBotMessage = function (variant, chatId) {
1005
+ var _a, _b;
706
1006
  if (chatId === void 0) { chatId = currentChatId; }
707
- return __awaiter(void 0, void 0, void 0, function () {
708
- var isInit, responseStatus, handedOffToAgent, turnSequence, payload, response, _a, _b, _c, chunks_1, _d, metadata, messageId_1, errorId_1;
709
- var _e, _f, _g;
710
- return __generator(this, function (_h) {
711
- switch (_h.label) {
712
- case 0:
713
- isInit = variant.kind === exports.BotMessageKind.INIT;
714
- handedOffToAgent = false;
715
- turnSequence = getTurnSequence((_f = (_e = messages[chatId]) === null || _e === void 0 ? void 0 : _e.messages) !== null && _f !== void 0 ? _f : [], "BOT_MESSAGE") + 1;
716
- _h.label = 1;
717
- case 1:
718
- _h.trys.push([1, 3, 4, 5]);
719
- if (!isInit) {
720
- setIsReplyLoading(true);
721
- }
722
- payload = buildBotPayload(variant, chatId);
723
- return [4, chatService.getBotResponse(payload)];
724
- case 2:
725
- response = _h.sent();
726
- _a = response.data, _b = _a === void 0 ? {} : _a, _c = _b.chunks, chunks_1 = _c === void 0 ? [] : _c, _d = _b.metadata, metadata = _d === void 0 ? {} : _d;
727
- responseStatus = 'success';
728
- handedOffToAgent = (_g = metadata.handedOffToAgent) !== null && _g !== void 0 ? _g : false;
729
- messageId_1 = uuid.v4();
730
- if (isInit)
731
- seedPresented(chatId, [messageId_1]);
732
- setMessages(function (prev) {
733
- var _a;
734
- var _b, _c;
735
- return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
736
- {
737
- id: messageId_1,
738
- type: "BOT_MESSAGE",
739
- chunks: __spreadArray([], chunks_1, true),
740
- metaData: { createdAt: talosGeneralUtils.formatISOTime(new Date().toISOString()), messageId: messageId_1 },
741
- },
742
- ], false), status: exports.ChatStatus.ON_GOING }), _a)));
743
- });
744
- return [3, 5];
745
- case 3:
746
- _h.sent();
747
- errorId_1 = uuid.v4();
748
- setMessages(function (prev) {
749
- var _a;
750
- var _b, _c;
751
- return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [BOT_ERROR_RESPONSE(errorId_1, variant)], false) }), _a)));
752
- });
753
- responseStatus = 'failed';
754
- return [3, 5];
755
- case 4:
756
- if (!isInit) {
757
- setIsReplyLoading(false);
758
- if (handedOffToAgent) {
759
- dispatch({
760
- type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
761
- payload: {
762
- eventName: "u_ai_chat_agent_handoff",
763
- eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
764
- },
765
- });
766
- }
767
- else {
768
- dispatch({
769
- type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
770
- payload: {
771
- eventName: "u_ai_chat_bot_response",
772
- eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
773
- },
774
- });
775
- }
776
- }
777
- return [7];
778
- case 5: return [2];
779
- }
780
- });
1007
+ var isInit = variant.kind === exports.BotMessageKind.INIT;
1008
+ var turnSequence = getTurnSequence((_b = (_a = messages[chatId]) === null || _a === void 0 ? void 0 : _a.messages) !== null && _b !== void 0 ? _b : [], "BOT_MESSAGE") + 1;
1009
+ var messageId = uuid.v4();
1010
+ if (!isInit)
1011
+ setIsReplyLoading(true);
1012
+ if (isInit)
1013
+ seedPresented(chatId, [messageId]);
1014
+ setMessages(function (prev) {
1015
+ var _a;
1016
+ var _b, _c;
1017
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
1018
+ {
1019
+ id: messageId,
1020
+ type: "BOT_MESSAGE",
1021
+ chunks: [],
1022
+ metaData: { createdAt: talosGeneralUtils.formatISOTime(new Date().toISOString()), messageId: messageId },
1023
+ },
1024
+ ], false), status: exports.ChatStatus.ON_GOING }), _a)));
1025
+ });
1026
+ var trackResult = function (responseStatus, handedOffToAgent) {
1027
+ if (isInit)
1028
+ return;
1029
+ setIsReplyLoading(false);
1030
+ if (handedOffToAgent) {
1031
+ dispatch({
1032
+ type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
1033
+ payload: {
1034
+ eventName: "u_ai_chat_agent_handoff",
1035
+ eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
1036
+ },
1037
+ });
1038
+ }
1039
+ else {
1040
+ dispatch({
1041
+ type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
1042
+ payload: {
1043
+ eventName: "u_ai_chat_bot_response",
1044
+ eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
1045
+ },
1046
+ });
1047
+ }
1048
+ };
1049
+ return new Promise(function (resolve) {
1050
+ var sink = {
1051
+ update: function (widgets) { return patchMessageChunks(chatId, messageId, widgets); },
1052
+ onLanding: function (content) {
1053
+ if (!isInit)
1054
+ return;
1055
+ setMessages(function (prev) {
1056
+ var _a;
1057
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { landingContent: content, messages: [] }), _a)));
1058
+ });
1059
+ },
1060
+ done: function (metadata) {
1061
+ var _a;
1062
+ trackResult("success", (_a = metadata === null || metadata === void 0 ? void 0 : metadata.handedOffToAgent) !== null && _a !== void 0 ? _a : false);
1063
+ resolve();
1064
+ },
1065
+ error: function () {
1066
+ setMessages(function (prev) {
1067
+ var _a;
1068
+ var chat = prev[chatId];
1069
+ if (!chat)
1070
+ return prev;
1071
+ var errorMsg = BOT_ERROR_RESPONSE(messageId, variant);
1072
+ return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? errorMsg : m); }) }), _a));
1073
+ });
1074
+ trackResult("failed", false);
1075
+ resolve();
1076
+ },
1077
+ };
1078
+ transportSend(buildBotPayload(variant, chatId), sink);
781
1079
  });
782
1080
  };
783
1081
  var handleRetryMessage = function (messageId) { return __awaiter(void 0, void 0, void 0, function () {
@@ -821,56 +1119,61 @@
821
1119
  }
822
1120
  });
823
1121
  }); };
824
- var seedInitialChat = function () { return __awaiter(void 0, void 0, void 0, function () {
825
- var response, latestSessionId, newChat;
826
- return __generator(this, function (_a) {
827
- switch (_a.label) {
828
- case 0:
829
- _a.trys.push([0, 6, 7, 8]);
830
- setIsInitialLoading(true);
831
- return [4, chatService.fetchChatId()];
832
- case 1:
833
- response = _a.sent();
834
- latestSessionId = response.data.latestSessionId;
835
- newChat = talosGeneralUtils.isEmpty(latestSessionId);
836
- setIsNewChat(newChat);
837
- if (newChat) {
838
- latestSessionId = uuid.v4();
839
- }
840
- setChatStack([{ type: exports.ChatPageType.CHAT, id: latestSessionId }]);
841
- if (!newChat) return [3, 3];
842
- return [4, handleBotMessage({ kind: exports.BotMessageKind.INIT }, latestSessionId)];
843
- case 2:
844
- _a.sent();
845
- return [3, 5];
846
- case 3: return [4, handleConversationFetch(latestSessionId)];
847
- case 4:
848
- _a.sent();
849
- _a.label = 5;
850
- case 5: return [3, 8];
851
- case 6:
852
- _a.sent();
853
- setChatStack([{ type: exports.ChatPageType.CHAT_ERROR, retry: { kind: exports.ChatErrorKind.INITIAL } }]);
854
- return [3, 8];
855
- case 7:
856
- setIsInitialLoading(false);
857
- return [7];
858
- case 8: return [2];
859
- }
1122
+ var seedInitialChat = function (forceNewChat) {
1123
+ if (forceNewChat === void 0) { forceNewChat = false; }
1124
+ return __awaiter(void 0, void 0, void 0, function () {
1125
+ var response, _a, latestSessionId, _b, summaryEnabled, newChat;
1126
+ return __generator(this, function (_c) {
1127
+ switch (_c.label) {
1128
+ case 0:
1129
+ _c.trys.push([0, 6, , 7]);
1130
+ setIsInitialLoading(true);
1131
+ return [4, chatService.fetchChatId(forceNewChat)];
1132
+ case 1:
1133
+ response = _c.sent();
1134
+ _a = response.data, latestSessionId = _a.latestSessionId, _b = _a.summaryEnabled, summaryEnabled = _b === void 0 ? false : _b;
1135
+ newChat = talosGeneralUtils.isEmpty(latestSessionId);
1136
+ setIsNewChat(newChat);
1137
+ summaryEnabledRef.current = !newChat && summaryEnabled;
1138
+ if (newChat) {
1139
+ latestSessionId = uuid.v4();
1140
+ }
1141
+ setChatStack([{ type: exports.ChatPageType.CHAT, id: latestSessionId }]);
1142
+ if (!newChat) return [3, 3];
1143
+ return [4, handleBotMessage({ kind: exports.BotMessageKind.INIT }, latestSessionId)];
1144
+ case 2:
1145
+ _c.sent();
1146
+ setIsInitialLoading(false);
1147
+ return [3, 5];
1148
+ case 3: return [4, handleConversationFetch(latestSessionId)];
1149
+ case 4:
1150
+ _c.sent();
1151
+ setIsInitialLoading(false);
1152
+ _c.label = 5;
1153
+ case 5: return [3, 7];
1154
+ case 6:
1155
+ _c.sent();
1156
+ setChatStack([{ type: exports.ChatPageType.CHAT_ERROR, retry: { kind: exports.ChatErrorKind.INITIAL } }]);
1157
+ setIsInitialLoading(false);
1158
+ return [3, 7];
1159
+ case 7: return [2];
1160
+ }
1161
+ });
860
1162
  });
861
- }); };
1163
+ };
862
1164
  require$$0.useEffect(function () {
863
1165
  seedInitialChat();
864
1166
  }, []);
865
- var handleChunk = require$$0.useCallback(function (_a) {
866
- _a.chunk; _a.chatId;
867
- }, []);
868
1167
  require$$0.useEffect(function () {
869
- var removeChunkListener = chat.on(talosUseChat.ChatEventName.CHUNK, handleChunk);
870
- return function () {
871
- removeChunkListener();
872
- };
873
- }, [chat, handleChunk]);
1168
+ if (!open) {
1169
+ summaryFetchedRef.current = false;
1170
+ return;
1171
+ }
1172
+ if (summaryFetchedRef.current || isInitialLoading || !currentChatId || isNewChat || !summaryEnabledRef.current)
1173
+ return;
1174
+ summaryFetchedRef.current = true;
1175
+ fetchContextSummary(currentChatId);
1176
+ }, [open, isInitialLoading, currentChatId, isNewChat, fetchContextSummary]);
874
1177
  var pushUserMessage = function (message) {
875
1178
  var userMessageWidget = formUserMessageWidget({ message: message });
876
1179
  var id = uuid.v4();
@@ -907,7 +1210,7 @@
907
1210
  }
908
1211
  return [2];
909
1212
  });
910
- }); }, [baseSendMessage, pushUserMessage]);
1213
+ }); }, [pushUserMessage]);
911
1214
  var resetPreviousChats = function () {
912
1215
  setPreviousChatError(false);
913
1216
  setPreviousChats(null);
@@ -957,7 +1260,7 @@
957
1260
  var handleCreateNewChat = function () {
958
1261
  clearChatStack();
959
1262
  clearMessages();
960
- seedInitialChat();
1263
+ seedInitialChat(true);
961
1264
  setShowNativeActions(false);
962
1265
  dispatch({
963
1266
  type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
@@ -1200,6 +1503,12 @@
1200
1503
  return (__assign(__assign({}, prev), (_a = {}, _a[currentChatId] = __assign(__assign({}, prev[currentChatId]), { status: exports.ChatStatus.CLOSED }), _a)));
1201
1504
  });
1202
1505
  };
1506
+ var handleOpenChatbot = function () {
1507
+ onOpenChatbot === null || onOpenChatbot === void 0 ? void 0 : onOpenChatbot();
1508
+ };
1509
+ var handleCloseChatbot = function () {
1510
+ onCloseChatbot === null || onCloseChatbot === void 0 ? void 0 : onCloseChatbot();
1511
+ };
1203
1512
  var handleThumbsDownFeedback = function (feedbackValue) {
1204
1513
  var _a, _b;
1205
1514
  var turnSequence = getTurnSequence((_b = (_a = messages[currentChatId]) === null || _a === void 0 ? void 0 : _a.messages) !== null && _b !== void 0 ? _b : [], "USER_MESSAGE");
@@ -1218,7 +1527,7 @@
1218
1527
  }
1219
1528
  };
1220
1529
  }, []);
1221
- var _l = useChatAction({
1530
+ var _o = useChatAction({
1222
1531
  retryUpload: retryUpload,
1223
1532
  retryMessage: handleRetryMessage,
1224
1533
  sendMessage: sendMessage,
@@ -1232,8 +1541,11 @@
1232
1541
  triggerTracking: triggerTracking,
1233
1542
  handleCloseCurrentChat: handleCloseCurrentChat,
1234
1543
  handleThumbsDownFeedback: handleThumbsDownFeedback,
1544
+ handleOpenChatbot: handleOpenChatbot,
1545
+ handleCloseChatbot: handleCloseChatbot,
1235
1546
  baseTrackingData: baseTrackingData,
1236
- }), dispatch = _l.dispatch, dispatchAll = _l.dispatchAll;
1547
+ dispatcher: dispatcher,
1548
+ }), dispatch = _o.dispatch, dispatchAll = _o.dispatchAll;
1237
1549
  return {
1238
1550
  currentChatId: currentChatId,
1239
1551
  chat: chat,
@@ -1245,6 +1557,9 @@
1245
1557
  isInitialLoading: isInitialLoading,
1246
1558
  isReplyLoading: isReplyLoading,
1247
1559
  isNewChat: isNewChat,
1560
+ isContextSummaryLoading: isContextSummaryLoading,
1561
+ contextSummary: contextSummary,
1562
+ contextSummaryError: contextSummaryError,
1248
1563
  screenRefs: screenRefs,
1249
1564
  showNativeActions: showNativeActions,
1250
1565
  chatService: chatService,
@@ -1387,6 +1702,7 @@
1387
1702
  exports.useChatContext = useChatContext;
1388
1703
  exports.useChatController = useChatController;
1389
1704
  exports.useChatNetwork = useChatNetwork;
1705
+ exports.useContextSummary = useContextSummary;
1390
1706
  exports.useDispatch = useDispatch;
1391
1707
  exports.useDispatchAll = useDispatchAll;
1392
1708
  exports.usePresentation = usePresentation;