kooby 1.0.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.
@@ -0,0 +1,883 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+ var s2 = require('@react-spectrum/s2');
5
+ var Copy = require('@react-spectrum/s2/icons/Copy');
6
+ var OpenIn = require('@react-spectrum/s2/icons/OpenIn');
7
+ var Refresh = require('@react-spectrum/s2/icons/Refresh');
8
+ var ThumbDown = require('@react-spectrum/s2/icons/ThumbDown');
9
+ var ThumbUp = require('@react-spectrum/s2/icons/ThumbUp');
10
+ var Markdown = require('markdown-to-jsx');
11
+
12
+ function _arrayLikeToArray(r, a) {
13
+ (null == a || a > r.length) && (a = r.length);
14
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
15
+ return n;
16
+ }
17
+ function _arrayWithHoles(r) {
18
+ if (Array.isArray(r)) return r;
19
+ }
20
+ function _arrayWithoutHoles(r) {
21
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
22
+ }
23
+ function _assertThisInitialized(e) {
24
+ if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
25
+ return e;
26
+ }
27
+ function _callSuper(t, o, e) {
28
+ return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
29
+ }
30
+ function _classCallCheck(a, n) {
31
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
32
+ }
33
+ function _defineProperties(e, r) {
34
+ for (var t = 0; t < r.length; t++) {
35
+ var o = r[t];
36
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
37
+ }
38
+ }
39
+ function _createClass(e, r, t) {
40
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
41
+ writable: false
42
+ }), e;
43
+ }
44
+ function _defineProperty(e, r, t) {
45
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
46
+ value: t,
47
+ enumerable: true,
48
+ configurable: true,
49
+ writable: true
50
+ }) : e[r] = t, e;
51
+ }
52
+ function _getPrototypeOf(t) {
53
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
54
+ return t.__proto__ || Object.getPrototypeOf(t);
55
+ }, _getPrototypeOf(t);
56
+ }
57
+ function _inherits(t, e) {
58
+ if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
59
+ t.prototype = Object.create(e && e.prototype, {
60
+ constructor: {
61
+ value: t,
62
+ writable: true,
63
+ configurable: true
64
+ }
65
+ }), Object.defineProperty(t, "prototype", {
66
+ writable: false
67
+ }), e && _setPrototypeOf(t, e);
68
+ }
69
+ function _isNativeReflectConstruct() {
70
+ try {
71
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
72
+ } catch (t) {}
73
+ return (_isNativeReflectConstruct = function () {
74
+ return !!t;
75
+ })();
76
+ }
77
+ function _iterableToArray(r) {
78
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
79
+ }
80
+ function _iterableToArrayLimit(r, l) {
81
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
82
+ if (null != t) {
83
+ var e,
84
+ n,
85
+ i,
86
+ u,
87
+ a = [],
88
+ f = true,
89
+ o = false;
90
+ try {
91
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
92
+ } catch (r) {
93
+ o = true, n = r;
94
+ } finally {
95
+ try {
96
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
97
+ } finally {
98
+ if (o) throw n;
99
+ }
100
+ }
101
+ return a;
102
+ }
103
+ }
104
+ function _nonIterableRest() {
105
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
106
+ }
107
+ function _nonIterableSpread() {
108
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
109
+ }
110
+ function ownKeys(e, r) {
111
+ var t = Object.keys(e);
112
+ if (Object.getOwnPropertySymbols) {
113
+ var o = Object.getOwnPropertySymbols(e);
114
+ r && (o = o.filter(function (r) {
115
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
116
+ })), t.push.apply(t, o);
117
+ }
118
+ return t;
119
+ }
120
+ function _objectSpread2(e) {
121
+ for (var r = 1; r < arguments.length; r++) {
122
+ var t = null != arguments[r] ? arguments[r] : {};
123
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
124
+ _defineProperty(e, r, t[r]);
125
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
126
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
127
+ });
128
+ }
129
+ return e;
130
+ }
131
+ function _objectWithoutProperties(e, t) {
132
+ if (null == e) return {};
133
+ var o,
134
+ r,
135
+ i = _objectWithoutPropertiesLoose(e, t);
136
+ if (Object.getOwnPropertySymbols) {
137
+ var n = Object.getOwnPropertySymbols(e);
138
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
139
+ }
140
+ return i;
141
+ }
142
+ function _objectWithoutPropertiesLoose(r, e) {
143
+ if (null == r) return {};
144
+ var t = {};
145
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
146
+ if (-1 !== e.indexOf(n)) continue;
147
+ t[n] = r[n];
148
+ }
149
+ return t;
150
+ }
151
+ function _possibleConstructorReturn(t, e) {
152
+ if (e && ("object" == typeof e || "function" == typeof e)) return e;
153
+ if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
154
+ return _assertThisInitialized(t);
155
+ }
156
+ function _setPrototypeOf(t, e) {
157
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
158
+ return t.__proto__ = e, t;
159
+ }, _setPrototypeOf(t, e);
160
+ }
161
+ function _slicedToArray(r, e) {
162
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
163
+ }
164
+ function _toConsumableArray(r) {
165
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
166
+ }
167
+ function _toPrimitive(t, r) {
168
+ if ("object" != typeof t || !t) return t;
169
+ var e = t[Symbol.toPrimitive];
170
+ if (void 0 !== e) {
171
+ var i = e.call(t, r);
172
+ if ("object" != typeof i) return i;
173
+ throw new TypeError("@@toPrimitive must return a primitive value.");
174
+ }
175
+ return ("string" === r ? String : Number)(t);
176
+ }
177
+ function _toPropertyKey(t) {
178
+ var i = _toPrimitive(t, "string");
179
+ return "symbol" == typeof i ? i : i + "";
180
+ }
181
+ function _unsupportedIterableToArray(r, a) {
182
+ if (r) {
183
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
184
+ var t = {}.toString.call(r).slice(8, -1);
185
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
186
+ }
187
+ }
188
+
189
+ var ChatManagerBase = /*#__PURE__*/function () {
190
+ function ChatManagerBase(_ref) {
191
+ var url = _ref.url,
192
+ onMessage = _ref.onMessage,
193
+ onOpen = _ref.onOpen,
194
+ onClose = _ref.onClose,
195
+ onError = _ref.onError,
196
+ authToken = _ref.authToken;
197
+ _classCallCheck(this, ChatManagerBase);
198
+ if ((this instanceof ChatManagerBase ? this.constructor : void 0) === ChatManagerBase) {
199
+ throw new TypeError("Cannot construct ChatManagerBase instances directly");
200
+ }
201
+ this.url = url;
202
+ this.onMessage = onMessage;
203
+ this.onOpen = onOpen;
204
+ this.onClose = onClose;
205
+ this.onError = onError;
206
+ this.authToken = authToken;
207
+ }
208
+
209
+ // Abstract methods that must be implemented by subclasses
210
+ return _createClass(ChatManagerBase, [{
211
+ key: "connect",
212
+ value: function connect(callback) {
213
+ throw new Error("connect method must be implemented by subclass");
214
+ }
215
+ }, {
216
+ key: "sendMessage",
217
+ value: function sendMessage(message) {
218
+ throw new Error("sendMessage method must be implemented by subclass");
219
+ }
220
+ }, {
221
+ key: "disconnect",
222
+ value: function disconnect() {
223
+ throw new Error("disconnect method must be implemented by subclass");
224
+ }
225
+ }]);
226
+ }();
227
+
228
+ var WSChatManager = /*#__PURE__*/function (_ChatManagerBase) {
229
+ function WSChatManager(_ref) {
230
+ var _this;
231
+ var url = _ref.url,
232
+ onMessage = _ref.onMessage,
233
+ onOpen = _ref.onOpen,
234
+ onClose = _ref.onClose,
235
+ onError = _ref.onError,
236
+ authToken = _ref.authToken;
237
+ _ref.agent;
238
+ _classCallCheck(this, WSChatManager);
239
+ // Format WebSocket URL with optional token
240
+ var wsUrl = url;
241
+ if (authToken) {
242
+ wsUrl += "?token=".concat(authToken);
243
+ }
244
+ _this = _callSuper(this, WSChatManager, [{
245
+ url: wsUrl,
246
+ onMessage: onMessage,
247
+ onOpen: onOpen,
248
+ onClose: onClose,
249
+ onError: onError,
250
+ authToken: authToken
251
+ }]);
252
+ _this.socket = null;
253
+ return _this;
254
+ }
255
+ _inherits(WSChatManager, _ChatManagerBase);
256
+ return _createClass(WSChatManager, [{
257
+ key: "connect",
258
+ value: function connect(cb) {
259
+ var _this2 = this;
260
+ this.socket = new WebSocket(this.url);
261
+
262
+ // Call the on Open and optional callback
263
+ this.socket.onopen = function () {
264
+ _this2.onOpen();
265
+ // Optional callback after connection is established
266
+ if (cb) cb();
267
+ };
268
+ this.socket.onmessage = function (event) {
269
+ var data = JSON.parse(event.data);
270
+ _this2.onMessage(data);
271
+ };
272
+ this.socket.onclose = this.onClose;
273
+ this.socket.onerror = this.onError;
274
+ }
275
+ }, {
276
+ key: "sendMessage",
277
+ value: function sendMessage(message) {
278
+ if (this.socket && this.socket.readyState === WebSocket.OPEN) {
279
+ this.socket.send(JSON.stringify(message));
280
+ } else {
281
+ console.error("WebSocket is not open");
282
+ }
283
+ }
284
+ }, {
285
+ key: "disconnect",
286
+ value: function disconnect() {
287
+ if (this.socket) {
288
+ this.socket.close();
289
+ }
290
+ }
291
+ }]);
292
+ }(ChatManagerBase);
293
+
294
+ var ChatManager = /*#__PURE__*/function () {
295
+ function ChatManager() {
296
+ _classCallCheck(this, ChatManager);
297
+ }
298
+ return _createClass(ChatManager, null, [{
299
+ key: "create",
300
+ value: function create(_ref) {
301
+ var url = _ref.url,
302
+ onMessage = _ref.onMessage,
303
+ onOpen = _ref.onOpen,
304
+ onClose = _ref.onClose,
305
+ onError = _ref.onError,
306
+ authToken = _ref.authToken,
307
+ agent = _ref.agent;
308
+ if (url.startsWith("ws://") || url.startsWith("wss://")) {
309
+ return new WSChatManager({
310
+ url: url,
311
+ onMessage: onMessage,
312
+ onOpen: onOpen,
313
+ onClose: onClose,
314
+ onError: onError,
315
+ authToken: authToken,
316
+ agent: agent
317
+ });
318
+ }
319
+ throw new Error("Kooby expects a WebSocket URL (ws:// or wss://). Got: ".concat(url));
320
+ }
321
+ }]);
322
+ }();
323
+
324
+ function styleInject(css, ref) {
325
+ if (ref === void 0) ref = {};
326
+ var insertAt = ref.insertAt;
327
+ if (typeof document === 'undefined') {
328
+ return;
329
+ }
330
+ var head = document.head || document.getElementsByTagName('head')[0];
331
+ var style = document.createElement('style');
332
+ style.type = 'text/css';
333
+ if (insertAt === 'top') {
334
+ if (head.firstChild) {
335
+ head.insertBefore(style, head.firstChild);
336
+ } else {
337
+ head.appendChild(style);
338
+ }
339
+ } else {
340
+ head.appendChild(style);
341
+ }
342
+ if (style.styleSheet) {
343
+ style.styleSheet.cssText = css;
344
+ } else {
345
+ style.appendChild(document.createTextNode(css));
346
+ }
347
+ }
348
+
349
+ var css_248z = ".kooby {\n width: 100%;\n max-width: 1000px;\n height: 100%;\n max-height: 90vh;\n padding: 30px;\n padding-top: 50px;\n border: 1px solid var(--kooby-border, rgba(0, 0, 0, 0.15));\n border-radius: 10px;\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.08);\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n position: relative;\n color: #000;\n}\n\n.site--app[data-theme=\"dark\"] .kooby,\n[data-color-scheme=\"dark\"] .kooby {\n border: none;\n box-shadow: 0 0 2px rgba(255, 255, 255, 0.12);\n background-color: var(--kooby-panel-bg, rgba(30, 30, 30, 0.95));\n color: #fff;\n}\n\n.kooby-focus {\n width: 100%;\n max-width: 100%;\n}\n\n.kooby-toolbar {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n gap: 4px;\n position: absolute;\n top: 0;\n right: 0;\n padding: 5px;\n box-sizing: border-box;\n}\n\n.kooby-conversation {\n display: flex;\n flex-direction: column;\n gap: 30px;\n flex: 2;\n overflow: scroll;\n\n scrollbar-width: none;\n}\n\n.kooby-conversation::-webkit-scrollbar {\n display: none;\n}\n\n.kooby-text-box {\n flex: 0 0 auto;\n}\n\n.kooby-message {\n display: flex;\n align-items: flex-start;\n width: 100%;\n}\n\n.kooby-message-role {\n min-width: 100px;\n height: 40px;\n padding: 10px;\n border-radius: 5px 0 0 5px;\n display: flex;\n align-items: center;\n /* justify-content: center; */\n}\n\n.kooby-message-role strong {\n color: #000;\n}\n\n[data-color-scheme=\"dark\"] .kooby-message-role strong {\n color: #fff;\n}\n\n.kooby-system {\n background-color: #d3d3d3;\n}\n\n.kooby-assistant {\n background-color: #d3d3d3;\n}\n\n[data-color-scheme=\"dark\"] .kooby-system,\n[data-color-scheme=\"dark\"] .kooby-assistant {\n background-color: #3a3a3a;\n}\n\n.kooby-user {\n background-color: rgb(59, 99, 251);\n}\n\n.kooby-user strong {\n color: white;\n}\n\n[data-color-scheme=\"dark\"] .kooby-user strong {\n color: white;\n}\n\n.kooby-content {\n padding: 10px;\n width: 100%;\n text-align: left;\n color: #000;\n margin-top: 10px;\n}\n\n[data-color-scheme=\"dark\"] .kooby-content {\n color: #fff;\n}\n\n.kooby-content :where(p, li, td, th, span, strong, em, h1, h2, h3, h4, h5, h6) {\n color: inherit;\n}\n\n.kooby .mermaid {\n background-color: white;\n border-radius: 5px;\n padding: 10px;\n margin-top: 10px;\n margin-bottom: 10px;\n}\n\n.kooby-debug {\n position: fixed;\n right: 0;\n top: 0;\n width: 30vw;\n height: 100vh;\n color: #111;\n overflow-y: auto;\n z-index: 1000;\n padding: 30px;\n background-color: white;\n}\n\n[data-color-scheme=\"dark\"] .kooby-debug {\n color: #f5f5f5;\n background-color: var(--kooby-panel-bg, rgba(30, 30, 30));\n}\n\n.kooby-debug pre {\n white-space: pre-wrap;\n}\n\n.kooby-debug-actions {\n display: flex;\n justify-content: flex-end;\n margin-bottom: 10px;\n}\n\n.kooby-debug-actions button {\n font-size: 1rem;\n padding: 4px 8px;\n height: auto;\n min-height: unset;\n}\n\n.kooby-feedback {\n display: flex;\n margin-top: 10px;\n align-items: center;\n gap: 6px;\n}\n\n.qr-code {\n width: 200px;\n}\n\n.qr {\n display: flex;\n flex-direction: column;\n gap: 10px;\n padding-top: 20px;\n padding-bottom: 20px;\n}\n\n.qr code {\n font-size: 12px;\n}\n\n.qr-download {\n width: 200px;\n}\n\n.site--app {\n min-height: 100vh;\n color: #000;\n}\n\n[data-color-scheme=\"dark\"] .site--app {\n color: #fff;\n}\n\n.site--app h1 {\n color: inherit;\n}\n\n.site--app-main {\n max-width: 1200px;\n margin: 0 auto;\n padding: 16px;\n}\n";
350
+ styleInject(css_248z);
351
+
352
+ var _excluded = ["debug", "url", "agent", "token", "children", "metadata", "context", "readOnly", "sendHistory", "apiRef", "expanded"];
353
+ var format = function format(value) {
354
+ if (value) {
355
+ return value.split("_").map(function (word) {
356
+ return word.charAt(0).toUpperCase() + word.slice(1);
357
+ }).join(" ");
358
+ } else {
359
+ return "Kooby";
360
+ }
361
+ };
362
+
363
+ /* Helper: interactive feedback popover (replaces non-interactive tooltip + form) */
364
+
365
+ var FeedbackField = function FeedbackField(_ref) {
366
+ var Icon = _ref.icon,
367
+ title = _ref.title,
368
+ value = _ref.value,
369
+ onValueChange = _ref.onValueChange,
370
+ onCommit = _ref.onCommit;
371
+ var _useState = React.useState(false),
372
+ _useState2 = _slicedToArray(_useState, 2),
373
+ open = _useState2[0],
374
+ setOpen = _useState2[1];
375
+ return /*#__PURE__*/React.createElement(s2.DialogTrigger, {
376
+ isOpen: open,
377
+ onOpenChange: setOpen
378
+ }, /*#__PURE__*/React.createElement(s2.ActionButton, {
379
+ isQuiet: true,
380
+ "aria-label": title
381
+ }, /*#__PURE__*/React.createElement(Icon, null)), /*#__PURE__*/React.createElement(s2.Popover, {
382
+ size: "S"
383
+ }, /*#__PURE__*/React.createElement("div", {
384
+ style: {
385
+ padding: 12
386
+ }
387
+ }, /*#__PURE__*/React.createElement(s2.Heading, null, title), /*#__PURE__*/React.createElement(s2.TextArea, {
388
+ value: value,
389
+ onChange: onValueChange,
390
+ onKeyDown: function onKeyDown(e) {
391
+ if (e.key === "Enter" && !e.shiftKey) {
392
+ e.preventDefault();
393
+ onCommit();
394
+ setOpen(false);
395
+ }
396
+ }
397
+ }))));
398
+ };
399
+
400
+ /* -------------------- Kooby Context -------------------- */
401
+
402
+ var KoobyContext = /*#__PURE__*/React.createContext();
403
+ var useKooby = function useKooby() {
404
+ var context = React.useContext(KoobyContext);
405
+ if (!context) {
406
+ throw new Error("useKooby must be used within a KoobyProvider");
407
+ }
408
+ return context;
409
+ };
410
+
411
+ /* -------------------- Kooby Components -------------------- */
412
+
413
+ var Feedback = function Feedback(_ref2) {
414
+ var responding = _ref2.responding,
415
+ message = _ref2.message,
416
+ index = _ref2.index,
417
+ conversation = _ref2.conversation,
418
+ negative = _ref2.negative,
419
+ positive = _ref2.positive,
420
+ showFeedbackOnAllMessages = _ref2.showFeedbackOnAllMessages,
421
+ loading = _ref2.loading;
422
+ var currentMessage = index === conversation.length - 1;
423
+ var show = false;
424
+ if (currentMessage && !responding && message.role === "assistant") {
425
+ show = true;
426
+ }
427
+ if (!currentMessage && showFeedbackOnAllMessages && message.role === "assistant") {
428
+ show = true;
429
+ }
430
+ var copyMessage = function copyMessage() {
431
+ var messageJson = JSON.stringify(message.content, null, 2);
432
+ navigator.clipboard.writeText(messageJson);
433
+ };
434
+ var _useState3 = React.useState(""),
435
+ _useState4 = _slicedToArray(_useState3, 2),
436
+ positiveFeedback = _useState4[0],
437
+ setPositiveFeedback = _useState4[1];
438
+ var _useState5 = React.useState(""),
439
+ _useState6 = _slicedToArray(_useState5, 2),
440
+ negativeFeedback = _useState6[0],
441
+ setNegativeFeedback = _useState6[1];
442
+ if (loading && currentMessage) {
443
+ return /*#__PURE__*/React.createElement("div", {
444
+ className: "kooby-feedback",
445
+ style: {
446
+ marginTop: "-35px",
447
+ marginLeft: "-40px"
448
+ }
449
+ }, /*#__PURE__*/React.createElement(s2.ProgressCircle, {
450
+ size: "M",
451
+ isIndeterminate: true,
452
+ "aria-label": "Loading",
453
+ staticColor: "white"
454
+ }));
455
+ }
456
+ if (show) {
457
+ return /*#__PURE__*/React.createElement("div", {
458
+ className: "kooby-feedback"
459
+ }, /*#__PURE__*/React.createElement(s2.ActionButton, {
460
+ isQuiet: true,
461
+ "aria-label": "Copy message",
462
+ onPress: copyMessage
463
+ }, /*#__PURE__*/React.createElement(Copy, null)), positive && /*#__PURE__*/React.createElement(FeedbackField, {
464
+ icon: ThumbUp,
465
+ title: positive.label || "Positive Feedback",
466
+ value: positiveFeedback,
467
+ onValueChange: setPositiveFeedback,
468
+ onCommit: function onCommit() {
469
+ return positive.onSubmit({
470
+ feedback: positiveFeedback,
471
+ conversation: conversation,
472
+ message: message.content
473
+ });
474
+ }
475
+ }), negative && /*#__PURE__*/React.createElement(FeedbackField, {
476
+ icon: ThumbDown,
477
+ title: negative.label || "Negative Feedback",
478
+ value: negativeFeedback,
479
+ onValueChange: setNegativeFeedback,
480
+ onCommit: function onCommit() {
481
+ return negative.onSubmit({
482
+ feedback: negativeFeedback,
483
+ conversation: conversation
484
+ });
485
+ }
486
+ }));
487
+ }
488
+ };
489
+ var Content = function Content(_ref3) {
490
+ var mdjsx = _ref3.mdjsx,
491
+ feedback = _ref3.feedback,
492
+ responding = _ref3.responding,
493
+ loading = _ref3.loading,
494
+ index = _ref3.index,
495
+ message = _ref3.message,
496
+ conversation = _ref3.conversation,
497
+ positive = _ref3.positive,
498
+ negative = _ref3.negative,
499
+ showFeedbackOnAllMessages = _ref3.showFeedbackOnAllMessages;
500
+ return /*#__PURE__*/React.createElement("div", {
501
+ style: {
502
+ width: "100%"
503
+ }
504
+ }, /*#__PURE__*/React.createElement("div", {
505
+ className: "kooby-content"
506
+ }, /*#__PURE__*/React.createElement(Markdown, {
507
+ options: mdjsx
508
+ }, message.content)), feedback && /*#__PURE__*/React.createElement(Feedback, {
509
+ responding: responding,
510
+ loading: loading,
511
+ index: index,
512
+ message: message,
513
+ conversation: conversation,
514
+ positive: positive,
515
+ negative: negative,
516
+ showFeedbackOnAllMessages: showFeedbackOnAllMessages
517
+ }));
518
+ };
519
+ var Conversation = function Conversation(_ref4) {
520
+ var mdjsx = _ref4.mdjsx,
521
+ _ref4$feedback = _ref4.feedback,
522
+ feedback = _ref4$feedback === void 0 ? true : _ref4$feedback,
523
+ positive = _ref4.positive,
524
+ negative = _ref4.negative,
525
+ showFeedbackOnAllMessages = _ref4.showFeedbackOnAllMessages;
526
+ var _useKooby = useKooby(),
527
+ conversation = _useKooby.conversation,
528
+ responding = _useKooby.responding,
529
+ loading = _useKooby.loading;
530
+ var conversationEndRef = React.useRef(null);
531
+ React.useEffect(function () {
532
+ if (conversation.length > 0 && conversation[conversation.length - 1].role != "system") {
533
+ var _conversationEndRef$c;
534
+ (_conversationEndRef$c = conversationEndRef.current) === null || _conversationEndRef$c === void 0 || _conversationEndRef$c.scrollIntoView({
535
+ behavior: "smooth"
536
+ });
537
+ }
538
+ }, [conversation]);
539
+ var filteredConvo = conversation.filter(function (message) {
540
+ return message.role !== "system";
541
+ });
542
+ return /*#__PURE__*/React.createElement("div", {
543
+ className: "kooby-conversation"
544
+ }, filteredConvo.map(function (message, index) {
545
+ return /*#__PURE__*/React.createElement("div", {
546
+ key: index,
547
+ className: "kooby-message"
548
+ }, /*#__PURE__*/React.createElement("div", {
549
+ className: "kooby-message-role kooby-".concat(message.role)
550
+ }, /*#__PURE__*/React.createElement("strong", null, message.role === "assistant" || message.role === "system" ? "Kooby" : message.role.charAt(0).toUpperCase() + message.role.slice(1))), /*#__PURE__*/React.createElement(Content, {
551
+ mdjsx: mdjsx,
552
+ feedback: feedback,
553
+ responding: responding,
554
+ loading: loading,
555
+ index: index,
556
+ message: message,
557
+ conversation: filteredConvo,
558
+ positive: positive,
559
+ negative: negative,
560
+ showFeedbackOnAllMessages: showFeedbackOnAllMessages
561
+ }));
562
+ }), /*#__PURE__*/React.createElement("div", {
563
+ ref: conversationEndRef
564
+ }));
565
+ };
566
+ var TextBox = function TextBox() {
567
+ var _useKooby2 = useKooby(),
568
+ isConnected = _useKooby2.isConnected,
569
+ socketManagerRef = _useKooby2.socketManagerRef,
570
+ setConversation = _useKooby2.setConversation,
571
+ context = _useKooby2.context,
572
+ setLoading = _useKooby2.setLoading;
573
+ var _useState7 = React.useState(""),
574
+ _useState8 = _slicedToArray(_useState7, 2),
575
+ input = _useState8[0],
576
+ setInput = _useState8[1];
577
+ var handleSend = React.useCallback(function () {
578
+ if (input.trim()) {
579
+ if (!isConnected && !socketManagerRef.current) {
580
+ console.error("WebSocket is not connected");
581
+ return;
582
+ }
583
+ var send = function send() {
584
+ setConversation(function (prev) {
585
+ return [].concat(_toConsumableArray(prev), [{
586
+ role: "user",
587
+ content: input
588
+ }]);
589
+ });
590
+ try {
591
+ socketManagerRef.current.sendMessage({
592
+ input: input
593
+ });
594
+ socketManagerRef.current.sendMessage({
595
+ complete: true
596
+ });
597
+ setLoading(true);
598
+ } catch (error) {
599
+ console.error("Error sending message:", error);
600
+ }
601
+ setInput("");
602
+ };
603
+ if (!isConnected) {
604
+ socketManagerRef.current.connect(function () {
605
+ send();
606
+ });
607
+ return;
608
+ }
609
+ send();
610
+ }
611
+ }, [input, isConnected, socketManagerRef, setConversation, context]);
612
+ return /*#__PURE__*/React.createElement("div", {
613
+ className: "kooby-text-box"
614
+ }, /*#__PURE__*/React.createElement(s2.TextArea, {
615
+ id: "prompt",
616
+ placeholder: "Ask Me Anything!",
617
+ "aria-label": "Prompt",
618
+ value: input,
619
+ onChange: setInput,
620
+ width: "100%",
621
+ onKeyDown: function onKeyDown(e) {
622
+ if (e.key === "Enter" && !e.shiftKey) {
623
+ e.preventDefault();
624
+ handleSend();
625
+ }
626
+ }
627
+ }));
628
+ };
629
+ var Toolbar = function Toolbar(_ref5) {
630
+ var children = _ref5.children,
631
+ _ref5$expandable = _ref5.expandable,
632
+ expandable = _ref5$expandable === void 0 ? true : _ref5$expandable,
633
+ _ref5$reset = _ref5.reset,
634
+ reset = _ref5$reset === void 0 ? true : _ref5$reset;
635
+ var _useKooby3 = useKooby(),
636
+ agent = _useKooby3.agent,
637
+ conversation = _useKooby3.conversation,
638
+ toggleFocus = _useKooby3.toggleFocus,
639
+ resetConversation = _useKooby3.resetConversation;
640
+ return /*#__PURE__*/React.createElement("div", {
641
+ className: "kooby-toolbar"
642
+ }, children ? children({
643
+ agent: agent,
644
+ conversation: conversation
645
+ }) : null, reset && /*#__PURE__*/React.createElement(s2.ActionButton, {
646
+ "aria-label": "Reset",
647
+ onPress: resetConversation
648
+ }, /*#__PURE__*/React.createElement(Refresh, null)), expandable && /*#__PURE__*/React.createElement(s2.ActionButton, {
649
+ "aria-label": "Expand",
650
+ onPress: toggleFocus
651
+ }, /*#__PURE__*/React.createElement(OpenIn, null)));
652
+ };
653
+ var ConnectionStatus = function ConnectionStatus() {
654
+ var _useKooby4 = useKooby(),
655
+ isConnected = _useKooby4.isConnected;
656
+ if (!isConnected) {
657
+ return (
658
+ /*#__PURE__*/
659
+ // <div >
660
+ React.createElement(s2.InlineAlert, {
661
+ variant: "notice",
662
+ UNSAFE_style: {
663
+ marginBottom: "10px"
664
+ }
665
+ }, /*#__PURE__*/React.createElement(s2.Heading, null, "Disconnected"), /*#__PURE__*/React.createElement(s2.Text, null, "Please continue talking to reconnect."))
666
+ // </div>
667
+ );
668
+ }
669
+ };
670
+
671
+ /* -------------------- Kooby Component -------------------- */
672
+
673
+ var defaultGreetingMessage = function defaultGreetingMessage(agent) {
674
+ return {
675
+ role: "assistant",
676
+ content: "Hello, I'm ".concat(format(agent), "! I'm here to help you with any questions you may have.")
677
+ };
678
+ };
679
+ var initializeConversation = function initializeConversation(_ref6) {
680
+ var agent = _ref6.agent,
681
+ initialConversation = _ref6.initialConversation;
682
+ if (initialConversation && initialConversation.length > 0) {
683
+ return initialConversation;
684
+ }
685
+ return [defaultGreetingMessage(agent)];
686
+ };
687
+ var Kooby = function Kooby(_ref7) {
688
+ var debug = _ref7.debug,
689
+ url = _ref7.url,
690
+ agent = _ref7.agent,
691
+ token = _ref7.token,
692
+ children = _ref7.children,
693
+ _ref7$metadata = _ref7.metadata,
694
+ metadata = _ref7$metadata === void 0 ? {} : _ref7$metadata,
695
+ context = _ref7.context,
696
+ _ref7$readOnly = _ref7.readOnly,
697
+ readOnly = _ref7$readOnly === void 0 ? false : _ref7$readOnly;
698
+ _ref7.sendHistory;
699
+ var apiRef = _ref7.apiRef,
700
+ expanded = _ref7.expanded,
701
+ rest = _objectWithoutProperties(_ref7, _excluded);
702
+ var _useState9 = React.useState(false),
703
+ _useState0 = _slicedToArray(_useState9, 2),
704
+ focus = _useState0[0],
705
+ setFocus = _useState0[1];
706
+ var toggleFocus = function toggleFocus() {
707
+ return setFocus(function (prev) {
708
+ return !prev;
709
+ });
710
+ };
711
+ var initialConversation = rest.conversation;
712
+ var _useState1 = React.useState(function () {
713
+ return initializeConversation({
714
+ agent: agent,
715
+ initialConversation: initialConversation
716
+ });
717
+ }),
718
+ _useState10 = _slicedToArray(_useState1, 2),
719
+ conversation = _useState10[0],
720
+ setConversation = _useState10[1];
721
+ var conversationRef = React.useRef();
722
+ conversationRef.current = conversation;
723
+ React.useEffect(function () {
724
+ setConversation(initializeConversation({
725
+ agent: agent,
726
+ initialConversation: initialConversation
727
+ }));
728
+ }, [agent, initialConversation]);
729
+ var _useState11 = React.useState(false),
730
+ _useState12 = _slicedToArray(_useState11, 2),
731
+ isConnected = _useState12[0],
732
+ setIsConnected = _useState12[1];
733
+ var _useState13 = React.useState(false),
734
+ _useState14 = _slicedToArray(_useState13, 2),
735
+ responding = _useState14[0],
736
+ setResponding = _useState14[1];
737
+ var _useState15 = React.useState(false),
738
+ _useState16 = _slicedToArray(_useState15, 2),
739
+ loading = _useState16[0],
740
+ setLoading = _useState16[1];
741
+ var socketManagerRef = React.useRef(null);
742
+ var metadataRef = React.useRef();
743
+ metadataRef.current = metadata;
744
+ React.useEffect(function () {
745
+ if (url && !readOnly) {
746
+ socketManagerRef.current = ChatManager.create({
747
+ url: url,
748
+ authToken: token,
749
+ agent: agent,
750
+ onMessage: function onMessage(data) {
751
+ // Example SSE message
752
+ // {"output":" I","trace_id":"94008937-f598-4be3-8714-5c6a4b4c9a32","span_id":"07b85d19-fb89-4a57-9566-6a9d9fdb0dc7"}
753
+ // {"type":"complete","trace_id":"94008937-f598-4be3-8714-5c6a4b4c9a32","span_id":"07b85d19-fb89-4a57-9566-6a9d9fdb0dc7"}
754
+
755
+ // Check if the incoming data contains an 'output' property
756
+ if (data.output) {
757
+ // We are starting to respond
758
+ setResponding(true);
759
+ // We are done loading the response
760
+ setLoading(false);
761
+ // Update the conversation state using the setConversation function
762
+ setConversation(function (prev) {
763
+ // Get the last message in the current conversation
764
+ var lastMessage = prev[prev.length - 1];
765
+
766
+ // Clean the output by removing any prefix like "user_id-<number>: "
767
+ var cleanOutput = data.output.replace(/^user_id-\d+:\s*/, "");
768
+
769
+ // Check if the last message in the conversation is from the assistant
770
+ if (lastMessage.role === "assistant") {
771
+ // If the last message is from the assistant, update its content
772
+ // by appending the cleaned output and replace the last message
773
+ return [].concat(_toConsumableArray(prev.slice(0, -1)), [// Keep all messages except the last one
774
+ _objectSpread2(_objectSpread2({}, lastMessage), {}, {
775
+ // Copy the last message
776
+ content: lastMessage.content + cleanOutput // Append the new content
777
+ })]);
778
+ } else {
779
+ // If the last message is not from the assistant, add a new message
780
+ // from the assistant with the cleaned output
781
+ return [].concat(_toConsumableArray(prev), [{
782
+ role: "assistant",
783
+ content: cleanOutput
784
+ }]);
785
+ }
786
+ });
787
+ }
788
+ if (data.complete) {
789
+ console.log("complete");
790
+ setResponding(false);
791
+ setIsConnected(true);
792
+ }
793
+ },
794
+ onOpen: function onOpen() {
795
+ console.log("Chat Manager Connected", metadataRef.current);
796
+ setIsConnected(true);
797
+
798
+ // Take the current conversation and format it for the chat manager history
799
+ var history = initialConversation;
800
+ socketManagerRef.current.sendMessage({
801
+ handshake: true,
802
+ history: history,
803
+ metadata: _objectSpread2({
804
+ user_agent: navigator.userAgent
805
+ }, metadataRef.current)
806
+ });
807
+ },
808
+ onClose: function onClose() {
809
+ console.log("Chat Manager Disconnecting");
810
+ setIsConnected(false);
811
+ },
812
+ onError: function onError() {
813
+ setIsConnected(false);
814
+ }
815
+ });
816
+ socketManagerRef.current.connect();
817
+ }
818
+ return function () {
819
+ if (url) {
820
+ console.log("Cleaing up Socket");
821
+ socketManagerRef.current.disconnect();
822
+ setIsConnected(false);
823
+ }
824
+ };
825
+ }, [url, agent, token]);
826
+ React.useEffect(function () {
827
+ if (socketManagerRef.current && context) {
828
+ console.log("Setting context", context);
829
+ setConversation(function (prev) {
830
+ return [].concat(_toConsumableArray(prev), [{
831
+ role: "system",
832
+ content: context
833
+ }]);
834
+ });
835
+ socketManagerRef.current.sendMessage({
836
+ context: context
837
+ });
838
+ }
839
+ }, [context]);
840
+ var resetConversation = function resetConversation() {
841
+ if (url && !readOnly && socketManagerRef.current) {
842
+ socketManagerRef.current.sendMessage({
843
+ reset: true
844
+ });
845
+ }
846
+ setConversation([defaultGreetingMessage(agent)]);
847
+ };
848
+ var contextValue = React.useMemo(function () {
849
+ return {
850
+ conversation: conversation,
851
+ setConversation: setConversation,
852
+ resetConversation: resetConversation,
853
+ isConnected: isConnected,
854
+ setIsConnected: setIsConnected,
855
+ socketManagerRef: socketManagerRef,
856
+ agent: agent,
857
+ toggleFocus: toggleFocus,
858
+ responding: responding,
859
+ context: context,
860
+ setLoading: setLoading,
861
+ loading: loading
862
+ };
863
+ }, [conversation, isConnected, agent, responding, context]);
864
+ if (apiRef) {
865
+ apiRef.current = {
866
+ resetConversation: resetConversation
867
+ };
868
+ }
869
+ return /*#__PURE__*/React.createElement(KoobyContext.Provider, {
870
+ value: contextValue
871
+ }, /*#__PURE__*/React.createElement("div", {
872
+ className: "kooby ".concat(focus || expanded ? "kooby-focus" : "")
873
+ }, children), debug && /*#__PURE__*/React.createElement("code", {
874
+ className: "kooby-debug"
875
+ }, /*#__PURE__*/React.createElement("pre", null, JSON.stringify(conversation, null, 2))));
876
+ };
877
+ Kooby.Content = Content;
878
+ Kooby.Conversation = Conversation;
879
+ Kooby.TextBox = TextBox;
880
+ Kooby.Toolbar = Toolbar;
881
+ Kooby.ConnectionStatus = ConnectionStatus;
882
+
883
+ exports.Kooby = Kooby;