@scout9/app 1.0.0-alpha.0.1.9 → 1.0.0-alpha.0.1.90

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 (70) hide show
  1. package/README.md +32 -0
  2. package/dist/{index-92deaa5f.cjs → exports-e7d51b70.cjs} +46618 -4591
  3. package/dist/index.cjs +58 -15
  4. package/dist/{multipart-parser-090f08a9.cjs → multipart-parser-e09a67c9.cjs} +13 -7
  5. package/dist/spirits-3b603262.cjs +1218 -0
  6. package/dist/spirits.cjs +9 -0
  7. package/dist/testing-tools.cjs +48 -0
  8. package/package.json +30 -8
  9. package/src/cli.js +162 -69
  10. package/src/core/config/agents.js +300 -7
  11. package/src/core/config/entities.js +58 -28
  12. package/src/core/config/index.js +37 -15
  13. package/src/core/config/project.js +160 -6
  14. package/src/core/config/workflow.js +13 -12
  15. package/src/core/data.js +27 -0
  16. package/src/core/index.js +386 -137
  17. package/src/core/sync.js +71 -0
  18. package/src/core/templates/Dockerfile +22 -0
  19. package/src/core/templates/app.js +453 -0
  20. package/src/core/templates/project-files.js +36 -0
  21. package/src/core/templates/template-package.json +13 -0
  22. package/src/exports.js +21 -17
  23. package/src/platform.js +189 -33
  24. package/src/public.d.ts.text +330 -0
  25. package/src/report.js +117 -0
  26. package/src/runtime/client/api.js +56 -159
  27. package/src/runtime/client/config.js +60 -11
  28. package/src/runtime/client/entity.js +19 -6
  29. package/src/runtime/client/index.js +5 -3
  30. package/src/runtime/client/message.js +13 -3
  31. package/src/runtime/client/platform.js +86 -0
  32. package/src/runtime/client/{agent.js → users.js} +35 -3
  33. package/src/runtime/client/utils.js +10 -9
  34. package/src/runtime/client/workflow.js +131 -9
  35. package/src/runtime/entry.js +2 -2
  36. package/src/testing-tools/dev.js +373 -0
  37. package/src/testing-tools/index.js +1 -0
  38. package/src/testing-tools/mocks.js +37 -5
  39. package/src/testing-tools/spirits.js +530 -0
  40. package/src/utils/audio-buffer.js +16 -0
  41. package/src/utils/audio-type.js +27 -0
  42. package/src/utils/configs/agents.js +68 -0
  43. package/src/utils/configs/entities.js +145 -0
  44. package/src/utils/configs/project.js +23 -0
  45. package/src/utils/configs/workflow.js +47 -0
  46. package/src/utils/file-type.js +569 -0
  47. package/src/utils/file.js +158 -0
  48. package/src/utils/glob.js +30 -0
  49. package/src/utils/image-buffer.js +23 -0
  50. package/src/utils/image-type.js +39 -0
  51. package/src/utils/index.js +1 -0
  52. package/src/utils/is-svg.js +37 -0
  53. package/src/utils/logger.js +111 -0
  54. package/src/utils/module.js +14 -25
  55. package/src/utils/project-templates.js +191 -0
  56. package/src/utils/project.js +387 -0
  57. package/src/utils/video-type.js +29 -0
  58. package/types/index.d.ts +7588 -206
  59. package/types/index.d.ts.map +97 -22
  60. package/dist/index-1b8d7dd2.cjs +0 -49555
  61. package/dist/index-2ccb115e.cjs +0 -49514
  62. package/dist/index-66b06a30.cjs +0 -49549
  63. package/dist/index-bc029a1d.cjs +0 -49528
  64. package/dist/index-d9a93523.cjs +0 -49527
  65. package/dist/multipart-parser-1508046a.cjs +0 -413
  66. package/dist/multipart-parser-7007403a.cjs +0 -413
  67. package/dist/multipart-parser-70c32c1d.cjs +0 -413
  68. package/dist/multipart-parser-71dec101.cjs +0 -413
  69. package/dist/multipart-parser-f15bf2e0.cjs +0 -414
  70. package/src/public.d.ts +0 -209
@@ -0,0 +1,1218 @@
1
+ 'use strict';
2
+
3
+ function _iterableToArrayLimit(r, l) {
4
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
5
+ if (null != t) {
6
+ var e,
7
+ n,
8
+ i,
9
+ u,
10
+ a = [],
11
+ f = !0,
12
+ o = !1;
13
+ try {
14
+ if (i = (t = t.call(r)).next, 0 === l) {
15
+ if (Object(t) !== t) return;
16
+ f = !1;
17
+ } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
18
+ } catch (r) {
19
+ o = !0, n = r;
20
+ } finally {
21
+ try {
22
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
23
+ } finally {
24
+ if (o) throw n;
25
+ }
26
+ }
27
+ return a;
28
+ }
29
+ }
30
+ function ownKeys(e, r) {
31
+ var t = Object.keys(e);
32
+ if (Object.getOwnPropertySymbols) {
33
+ var o = Object.getOwnPropertySymbols(e);
34
+ r && (o = o.filter(function (r) {
35
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
36
+ })), t.push.apply(t, o);
37
+ }
38
+ return t;
39
+ }
40
+ function _objectSpread2(e) {
41
+ for (var r = 1; r < arguments.length; r++) {
42
+ var t = null != arguments[r] ? arguments[r] : {};
43
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
44
+ _defineProperty(e, r, t[r]);
45
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
46
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
47
+ });
48
+ }
49
+ return e;
50
+ }
51
+ function _regeneratorRuntime() {
52
+ _regeneratorRuntime = function () {
53
+ return e;
54
+ };
55
+ var t,
56
+ e = {},
57
+ r = Object.prototype,
58
+ n = r.hasOwnProperty,
59
+ o = Object.defineProperty || function (t, e, r) {
60
+ t[e] = r.value;
61
+ },
62
+ i = "function" == typeof Symbol ? Symbol : {},
63
+ a = i.iterator || "@@iterator",
64
+ c = i.asyncIterator || "@@asyncIterator",
65
+ u = i.toStringTag || "@@toStringTag";
66
+ function define(t, e, r) {
67
+ return Object.defineProperty(t, e, {
68
+ value: r,
69
+ enumerable: !0,
70
+ configurable: !0,
71
+ writable: !0
72
+ }), t[e];
73
+ }
74
+ try {
75
+ define({}, "");
76
+ } catch (t) {
77
+ define = function (t, e, r) {
78
+ return t[e] = r;
79
+ };
80
+ }
81
+ function wrap(t, e, r, n) {
82
+ var i = e && e.prototype instanceof Generator ? e : Generator,
83
+ a = Object.create(i.prototype),
84
+ c = new Context(n || []);
85
+ return o(a, "_invoke", {
86
+ value: makeInvokeMethod(t, r, c)
87
+ }), a;
88
+ }
89
+ function tryCatch(t, e, r) {
90
+ try {
91
+ return {
92
+ type: "normal",
93
+ arg: t.call(e, r)
94
+ };
95
+ } catch (t) {
96
+ return {
97
+ type: "throw",
98
+ arg: t
99
+ };
100
+ }
101
+ }
102
+ e.wrap = wrap;
103
+ var h = "suspendedStart",
104
+ l = "suspendedYield",
105
+ f = "executing",
106
+ s = "completed",
107
+ y = {};
108
+ function Generator() {}
109
+ function GeneratorFunction() {}
110
+ function GeneratorFunctionPrototype() {}
111
+ var p = {};
112
+ define(p, a, function () {
113
+ return this;
114
+ });
115
+ var d = Object.getPrototypeOf,
116
+ v = d && d(d(values([])));
117
+ v && v !== r && n.call(v, a) && (p = v);
118
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
119
+ function defineIteratorMethods(t) {
120
+ ["next", "throw", "return"].forEach(function (e) {
121
+ define(t, e, function (t) {
122
+ return this._invoke(e, t);
123
+ });
124
+ });
125
+ }
126
+ function AsyncIterator(t, e) {
127
+ function invoke(r, o, i, a) {
128
+ var c = tryCatch(t[r], t, o);
129
+ if ("throw" !== c.type) {
130
+ var u = c.arg,
131
+ h = u.value;
132
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
133
+ invoke("next", t, i, a);
134
+ }, function (t) {
135
+ invoke("throw", t, i, a);
136
+ }) : e.resolve(h).then(function (t) {
137
+ u.value = t, i(u);
138
+ }, function (t) {
139
+ return invoke("throw", t, i, a);
140
+ });
141
+ }
142
+ a(c.arg);
143
+ }
144
+ var r;
145
+ o(this, "_invoke", {
146
+ value: function (t, n) {
147
+ function callInvokeWithMethodAndArg() {
148
+ return new e(function (e, r) {
149
+ invoke(t, n, e, r);
150
+ });
151
+ }
152
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
153
+ }
154
+ });
155
+ }
156
+ function makeInvokeMethod(e, r, n) {
157
+ var o = h;
158
+ return function (i, a) {
159
+ if (o === f) throw new Error("Generator is already running");
160
+ if (o === s) {
161
+ if ("throw" === i) throw a;
162
+ return {
163
+ value: t,
164
+ done: !0
165
+ };
166
+ }
167
+ for (n.method = i, n.arg = a;;) {
168
+ var c = n.delegate;
169
+ if (c) {
170
+ var u = maybeInvokeDelegate(c, n);
171
+ if (u) {
172
+ if (u === y) continue;
173
+ return u;
174
+ }
175
+ }
176
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
177
+ if (o === h) throw o = s, n.arg;
178
+ n.dispatchException(n.arg);
179
+ } else "return" === n.method && n.abrupt("return", n.arg);
180
+ o = f;
181
+ var p = tryCatch(e, r, n);
182
+ if ("normal" === p.type) {
183
+ if (o = n.done ? s : l, p.arg === y) continue;
184
+ return {
185
+ value: p.arg,
186
+ done: n.done
187
+ };
188
+ }
189
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
190
+ }
191
+ };
192
+ }
193
+ function maybeInvokeDelegate(e, r) {
194
+ var n = r.method,
195
+ o = e.iterator[n];
196
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
197
+ var i = tryCatch(o, e.iterator, r.arg);
198
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
199
+ var a = i.arg;
200
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
201
+ }
202
+ function pushTryEntry(t) {
203
+ var e = {
204
+ tryLoc: t[0]
205
+ };
206
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
207
+ }
208
+ function resetTryEntry(t) {
209
+ var e = t.completion || {};
210
+ e.type = "normal", delete e.arg, t.completion = e;
211
+ }
212
+ function Context(t) {
213
+ this.tryEntries = [{
214
+ tryLoc: "root"
215
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
216
+ }
217
+ function values(e) {
218
+ if (e || "" === e) {
219
+ var r = e[a];
220
+ if (r) return r.call(e);
221
+ if ("function" == typeof e.next) return e;
222
+ if (!isNaN(e.length)) {
223
+ var o = -1,
224
+ i = function next() {
225
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
226
+ return next.value = t, next.done = !0, next;
227
+ };
228
+ return i.next = i;
229
+ }
230
+ }
231
+ throw new TypeError(typeof e + " is not iterable");
232
+ }
233
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
234
+ value: GeneratorFunctionPrototype,
235
+ configurable: !0
236
+ }), o(GeneratorFunctionPrototype, "constructor", {
237
+ value: GeneratorFunction,
238
+ configurable: !0
239
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
240
+ var e = "function" == typeof t && t.constructor;
241
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
242
+ }, e.mark = function (t) {
243
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
244
+ }, e.awrap = function (t) {
245
+ return {
246
+ __await: t
247
+ };
248
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
249
+ return this;
250
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
251
+ void 0 === i && (i = Promise);
252
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
253
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
254
+ return t.done ? t.value : a.next();
255
+ });
256
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
257
+ return this;
258
+ }), define(g, "toString", function () {
259
+ return "[object Generator]";
260
+ }), e.keys = function (t) {
261
+ var e = Object(t),
262
+ r = [];
263
+ for (var n in e) r.push(n);
264
+ return r.reverse(), function next() {
265
+ for (; r.length;) {
266
+ var t = r.pop();
267
+ if (t in e) return next.value = t, next.done = !1, next;
268
+ }
269
+ return next.done = !0, next;
270
+ };
271
+ }, e.values = values, Context.prototype = {
272
+ constructor: Context,
273
+ reset: function (e) {
274
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
275
+ },
276
+ stop: function () {
277
+ this.done = !0;
278
+ var t = this.tryEntries[0].completion;
279
+ if ("throw" === t.type) throw t.arg;
280
+ return this.rval;
281
+ },
282
+ dispatchException: function (e) {
283
+ if (this.done) throw e;
284
+ var r = this;
285
+ function handle(n, o) {
286
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
287
+ }
288
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
289
+ var i = this.tryEntries[o],
290
+ a = i.completion;
291
+ if ("root" === i.tryLoc) return handle("end");
292
+ if (i.tryLoc <= this.prev) {
293
+ var c = n.call(i, "catchLoc"),
294
+ u = n.call(i, "finallyLoc");
295
+ if (c && u) {
296
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
297
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
298
+ } else if (c) {
299
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
300
+ } else {
301
+ if (!u) throw new Error("try statement without catch or finally");
302
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
303
+ }
304
+ }
305
+ }
306
+ },
307
+ abrupt: function (t, e) {
308
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
309
+ var o = this.tryEntries[r];
310
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
311
+ var i = o;
312
+ break;
313
+ }
314
+ }
315
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
316
+ var a = i ? i.completion : {};
317
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
318
+ },
319
+ complete: function (t, e) {
320
+ if ("throw" === t.type) throw t.arg;
321
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
322
+ },
323
+ finish: function (t) {
324
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
325
+ var r = this.tryEntries[e];
326
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
327
+ }
328
+ },
329
+ catch: function (t) {
330
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
331
+ var r = this.tryEntries[e];
332
+ if (r.tryLoc === t) {
333
+ var n = r.completion;
334
+ if ("throw" === n.type) {
335
+ var o = n.arg;
336
+ resetTryEntry(r);
337
+ }
338
+ return o;
339
+ }
340
+ }
341
+ throw new Error("illegal catch attempt");
342
+ },
343
+ delegateYield: function (e, r, n) {
344
+ return this.delegate = {
345
+ iterator: values(e),
346
+ resultName: r,
347
+ nextLoc: n
348
+ }, "next" === this.method && (this.arg = t), y;
349
+ }
350
+ }, e;
351
+ }
352
+ function _toPrimitive(t, r) {
353
+ if ("object" != typeof t || !t) return t;
354
+ var e = t[Symbol.toPrimitive];
355
+ if (void 0 !== e) {
356
+ var i = e.call(t, r || "default");
357
+ if ("object" != typeof i) return i;
358
+ throw new TypeError("@@toPrimitive must return a primitive value.");
359
+ }
360
+ return ("string" === r ? String : Number)(t);
361
+ }
362
+ function _toPropertyKey(t) {
363
+ var i = _toPrimitive(t, "string");
364
+ return "symbol" == typeof i ? i : String(i);
365
+ }
366
+ function _typeof(o) {
367
+ "@babel/helpers - typeof";
368
+
369
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
370
+ return typeof o;
371
+ } : function (o) {
372
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
373
+ }, _typeof(o);
374
+ }
375
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
376
+ try {
377
+ var info = gen[key](arg);
378
+ var value = info.value;
379
+ } catch (error) {
380
+ reject(error);
381
+ return;
382
+ }
383
+ if (info.done) {
384
+ resolve(value);
385
+ } else {
386
+ Promise.resolve(value).then(_next, _throw);
387
+ }
388
+ }
389
+ function _asyncToGenerator(fn) {
390
+ return function () {
391
+ var self = this,
392
+ args = arguments;
393
+ return new Promise(function (resolve, reject) {
394
+ var gen = fn.apply(self, args);
395
+ function _next(value) {
396
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
397
+ }
398
+ function _throw(err) {
399
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
400
+ }
401
+ _next(undefined);
402
+ });
403
+ };
404
+ }
405
+ function _classCallCheck(instance, Constructor) {
406
+ if (!(instance instanceof Constructor)) {
407
+ throw new TypeError("Cannot call a class as a function");
408
+ }
409
+ }
410
+ function _defineProperties(target, props) {
411
+ for (var i = 0; i < props.length; i++) {
412
+ var descriptor = props[i];
413
+ descriptor.enumerable = descriptor.enumerable || false;
414
+ descriptor.configurable = true;
415
+ if ("value" in descriptor) descriptor.writable = true;
416
+ Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
417
+ }
418
+ }
419
+ function _createClass(Constructor, protoProps, staticProps) {
420
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
421
+ if (staticProps) _defineProperties(Constructor, staticProps);
422
+ Object.defineProperty(Constructor, "prototype", {
423
+ writable: false
424
+ });
425
+ return Constructor;
426
+ }
427
+ function _defineProperty(obj, key, value) {
428
+ key = _toPropertyKey(key);
429
+ if (key in obj) {
430
+ Object.defineProperty(obj, key, {
431
+ value: value,
432
+ enumerable: true,
433
+ configurable: true,
434
+ writable: true
435
+ });
436
+ } else {
437
+ obj[key] = value;
438
+ }
439
+ return obj;
440
+ }
441
+ function _objectWithoutPropertiesLoose(source, excluded) {
442
+ if (source == null) return {};
443
+ var target = {};
444
+ var sourceKeys = Object.keys(source);
445
+ var key, i;
446
+ for (i = 0; i < sourceKeys.length; i++) {
447
+ key = sourceKeys[i];
448
+ if (excluded.indexOf(key) >= 0) continue;
449
+ target[key] = source[key];
450
+ }
451
+ return target;
452
+ }
453
+ function _objectWithoutProperties(source, excluded) {
454
+ if (source == null) return {};
455
+ var target = _objectWithoutPropertiesLoose(source, excluded);
456
+ var key, i;
457
+ if (Object.getOwnPropertySymbols) {
458
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
459
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
460
+ key = sourceSymbolKeys[i];
461
+ if (excluded.indexOf(key) >= 0) continue;
462
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
463
+ target[key] = source[key];
464
+ }
465
+ }
466
+ return target;
467
+ }
468
+ function _slicedToArray(arr, i) {
469
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
470
+ }
471
+ function _toConsumableArray(arr) {
472
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
473
+ }
474
+ function _arrayWithoutHoles(arr) {
475
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
476
+ }
477
+ function _arrayWithHoles(arr) {
478
+ if (Array.isArray(arr)) return arr;
479
+ }
480
+ function _iterableToArray(iter) {
481
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
482
+ }
483
+ function _unsupportedIterableToArray(o, minLen) {
484
+ if (!o) return;
485
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
486
+ var n = Object.prototype.toString.call(o).slice(8, -1);
487
+ if (n === "Object" && o.constructor) n = o.constructor.name;
488
+ if (n === "Map" || n === "Set") return Array.from(o);
489
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
490
+ }
491
+ function _arrayLikeToArray(arr, len) {
492
+ if (len == null || len > arr.length) len = arr.length;
493
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
494
+ return arr2;
495
+ }
496
+ function _nonIterableSpread() {
497
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
498
+ }
499
+ function _nonIterableRest() {
500
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
501
+ }
502
+ function _createForOfIteratorHelper(o, allowArrayLike) {
503
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
504
+ if (!it) {
505
+ if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
506
+ if (it) o = it;
507
+ var i = 0;
508
+ var F = function () {};
509
+ return {
510
+ s: F,
511
+ n: function () {
512
+ if (i >= o.length) return {
513
+ done: true
514
+ };
515
+ return {
516
+ done: false,
517
+ value: o[i++]
518
+ };
519
+ },
520
+ e: function (e) {
521
+ throw e;
522
+ },
523
+ f: F
524
+ };
525
+ }
526
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
527
+ }
528
+ var normalCompletion = true,
529
+ didErr = false,
530
+ err;
531
+ return {
532
+ s: function () {
533
+ it = it.call(o);
534
+ },
535
+ n: function () {
536
+ var step = it.next();
537
+ normalCompletion = step.done;
538
+ return step;
539
+ },
540
+ e: function (e) {
541
+ didErr = true;
542
+ err = e;
543
+ },
544
+ f: function () {
545
+ try {
546
+ if (!normalCompletion && it.return != null) it.return();
547
+ } finally {
548
+ if (didErr) throw err;
549
+ }
550
+ }
551
+ };
552
+ }
553
+
554
+ /**
555
+ * @typedef {Object} Document
556
+ * @property {string} id
557
+ */
558
+
559
+ /**
560
+ * Represents a change with before and after states of a given type.
561
+ * @template Type The type of the before and after properties.
562
+ * @typedef {Object} Change
563
+ * @property {Type} before - The state before the change.
564
+ * @property {Type} after - The state after the change.
565
+ */
566
+
567
+ /**
568
+ * @typedef {Object} ConversationData
569
+ * @property {import('../runtime/client/config.js').IScout9ProjectBuildConfig} config - used to define generation and extract persona metadata
570
+ * @property {import('../runtime/client/workflow.js').IConversation} conversation
571
+ * @property {Array<import('../runtime/client/message.js').IMessage>} messages
572
+ * @property {import('../runtime/client/message.js').IMessage} message - the message sent by the customer (should exist in messages)
573
+ * @property {import('../runtime/client/users.js').ICustomer} customer
574
+ * @property {any} context
575
+ */
576
+
577
+ /**
578
+ * @typedef {Object} ParseOutput
579
+ * @property {Array<import('../runtime/client/message.js').IMessage>} messages
580
+ * @property {import('../runtime/client/workflow.js').IConversation} conversation
581
+ * @property {import('../runtime/client/message.js').IMessage} message
582
+ * @property {any} context
583
+ */
584
+
585
+ /**
586
+ * @typedef {Object} WorkflowOutput
587
+ * @property {Array<import('../runtime/client/workflow.js').IWorkflowResponseSlot>} slots
588
+ * @property {Array<import('../runtime/client/message.js').IMessage>} messages
589
+ * @property {import('../runtime/client/workflow.js').IConversation} conversation
590
+ * @property {any} context
591
+ */
592
+
593
+ /**
594
+ * @typedef {Object} GenerateOutput
595
+ * @property {import('@scout9/admin').GenerateResponse | undefined} generate
596
+ * @property {Array<import('../runtime/client/message.js').IMessage>} messages
597
+ * @property {import('../runtime/client/workflow.js').IConversation} conversation
598
+ * @property {any} context
599
+ */
600
+
601
+ /**
602
+ * @callback ParseFun
603
+ * @param {string} message - message to send
604
+ * @param {string | undefined} language - language to parse in, defaults to "en" for english
605
+ * @returns {Promise<import('@scout9/admin').ParseResponse>}
606
+ */
607
+
608
+ /**
609
+ * @callback WorkflowFun
610
+ * @param {import('../runtime/client/workflow.js').IWorkflowEvent} event - conversation data
611
+ * @returns {Promise<import('../runtime/client/workflow.js').IWorkflowResponse>}
612
+ */
613
+
614
+ /**
615
+ * @callback GenerateFun
616
+ * @param {import('@scout9/admin').GenerateRequestOneOf} data - data to generate from
617
+ * @returns {Promise<import('@scout9/admin').GenerateResponse>}
618
+ */
619
+
620
+ /**
621
+ * @callback IdGeneratorFun
622
+ * @param {import('../runtime/client/message.js').IMessage.role} prefix
623
+ * @returns {string}
624
+ */
625
+ /**
626
+ * @callback StatusCallback
627
+ * @param {string} message
628
+ * @param {'info' | 'warn' | 'error' | 'success' | undefined} [level]
629
+ * @param {string | undefined} [type]
630
+ * @param {any | undefined} [payload]
631
+ * @returns {void}
632
+ */
633
+
634
+ /**
635
+ * @typedef {Object} CustomerSpiritCallbacks
636
+ * @property {ParseFun} parser
637
+ * @property {WorkflowFun} workflow
638
+ * @property {GenerateFun} generator
639
+ * @property {IdGeneratorFun} idGenerator
640
+ * @property {StatusCallback | undefined} [progress]
641
+ */
642
+
643
+ /**
644
+ * @typedef {Object} ConversationEvent
645
+ * @property {Change<import('../runtime/client/workflow.js').IConversation> & {forwardNote?: string; forward?: import('../runtime/client/message.js').IWorkflowResponseSlot['forward']}} conversation
646
+ * @property {Change<Array<import('../runtime/client/message.js').IMessage>>} messages
647
+ * @property {Change<Object>} context
648
+ * @property {Change<import('../runtime/client/message.js').IMessage>} message
649
+ */
650
+ var Spirits = {
651
+ /**
652
+ * Customer message
653
+ * @param {ConversationData & CustomerSpiritCallbacks} input
654
+ * @returns {Promise<ConversationEvent>}
655
+ */
656
+ customer: function () {
657
+ var _customer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input) {
658
+ var _recentUserMessage;
659
+ var customer, config, parser, workflow, generator, idGenerator, _input$progress, progress, messageBefore, contextBefore, messagesBefore, conversationBefore, conversation, messages, context, message, updateConversation, updateContext, userMessages, recentUserMessage, lockConversation, incrementLockAttempt, _addInstruction, addInstruction, persona, invalidRoles, parsePayload, index, _message, previousUserMessages, oldKeyCount, newKeyCount, noNewContext, slots, hasNoInstructions, hasNoCustomMessage, previousLockAttempt, resettedIntent, _forward, _forwardNote, _iterator, _step, _step$value, forward, forwardNote, instructions, removeInstructions, manualMessage, scheduled, resetIntent, secondsDelay, contextUpsert, _iterator2, _step2, instruction, _iterator3, _step3, _loop, manualMessageObj, now, generatorPayload, agentMessages, lastAgentMessage;
660
+ return _regeneratorRuntime().wrap(function _callee$(_context2) {
661
+ while (1) switch (_context2.prev = _context2.next) {
662
+ case 0:
663
+ customer = input.customer, config = input.config, parser = input.parser, workflow = input.workflow, generator = input.generator, idGenerator = input.idGenerator, _input$progress = input.progress, progress = _input$progress === void 0 ? function (message, level, type, payload) {} : _input$progress, messageBefore = input.message, contextBefore = input.context, messagesBefore = input.messages, conversationBefore = input.conversation;
664
+ conversation = input.conversation, messages = input.messages, context = input.context, message = input.message; // 0. Setup Helpers
665
+ updateConversation = function updateConversation(previousConversation, conversationUpdates) {
666
+ progress('Update conversation', 'info', 'UPDATE_CONVERSATION', conversationUpdates);
667
+ return _objectSpread2(_objectSpread2({}, previousConversation), conversationUpdates);
668
+ };
669
+ updateContext = function updateContext(previousContext, newContext) {
670
+ progress('Update context', 'info', 'UPDATE_CONTEXT', newContext);
671
+ return _objectSpread2(_objectSpread2({}, previousContext), newContext);
672
+ };
673
+ userMessages = function userMessages(_messages) {
674
+ return _messages.filter(function (m) {
675
+ return m.role === 'customer' || m.role === 'user';
676
+ });
677
+ };
678
+ recentUserMessage = function recentUserMessage(_messages) {
679
+ var _userMessages = userMessages(_messages);
680
+ return _userMessages[_userMessages.length - 1];
681
+ };
682
+ lockConversation = function lockConversation(_conversation, reason) {
683
+ return updateConversation(_conversation, {
684
+ locked: true,
685
+ lockedReason: conversation.lockedReason || reason || 'Unknown'
686
+ });
687
+ };
688
+ incrementLockAttempt = function incrementLockAttempt(_conversation, _config) {
689
+ if (typeof _conversation.lockAttempts !== 'number') {
690
+ _conversation.lockAttempts = 0;
691
+ }
692
+ _conversation.lockAttempts++;
693
+ if (_conversation.lockAttempts > ((_config === null || _config === void 0 ? void 0 : _config.maxLockAttempts) || 3)) {
694
+ _conversation.locked = true;
695
+ _conversation.lockedReason = "Max lock attempts exceeded (".concat(_conversation.lockAttempts, " > ").concat((_config === null || _config === void 0 ? void 0 : _config.maxLockAttempts) || 3, ")");
696
+ }
697
+ progress('Incremented lock attempt', 'info', 'UPDATE_CONVERSATION', {
698
+ lockAttempts: _conversation.lockAttempts,
699
+ locked: _conversation.locked,
700
+ lockedReason: _conversation.lockedReason || ''
701
+ });
702
+ return _conversation;
703
+ };
704
+ _addInstruction = function _addInstruction(instruction, _messages, _conversation, _config, previousLockAttempt, id) {
705
+ var systemMessages = _messages.filter(function (m) {
706
+ return m.role === 'system';
707
+ });
708
+ var lastSystemMessage = systemMessages[systemMessages.length - 1];
709
+ var addedMessage = false;
710
+ var changedConversation = false;
711
+
712
+ // If instruction does not equal previous system message, add it, otherwise lock attempt
713
+ if (!lastSystemMessage || instruction !== lastSystemMessage.content) {
714
+ _messages.push({
715
+ id: id,
716
+ role: 'system',
717
+ content: instruction,
718
+ time: new Date().toISOString()
719
+ });
720
+ addedMessage = true;
721
+ } else {
722
+ // Handle repeated instruction
723
+ // Increment lock attempt if instructions are repeated and we haven't already incremented lock attempt (for example if a forward is provided)
724
+ if (previousLockAttempt === (conversation.lockAttempts || 0)) {
725
+ _conversation = incrementLockAttempt(_conversation, _config);
726
+ changedConversation = true;
727
+ }
728
+ }
729
+ return {
730
+ conversation: _conversation,
731
+ messages: _messages,
732
+ addedMessage: addedMessage,
733
+ changedConversation: changedConversation
734
+ };
735
+ };
736
+ addInstruction = function addInstruction(instruction, previousLockAttempt) {
737
+ var id = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : idGenerator('sys');
738
+ var _addInstruction2 = _addInstruction(instruction, messages, conversation, config, previousLockAttempt, id),
739
+ newConversation = _addInstruction2.conversation,
740
+ newMessages = _addInstruction2.messages,
741
+ addedMessage = _addInstruction2.addedMessage,
742
+ changedConversation = _addInstruction2.changedConversation;
743
+ conversation = newConversation;
744
+ messages = newMessages;
745
+ if (addedMessage) {
746
+ progress('Added instruction', 'info', 'ADD_MESSAGE', newMessages[newMessages.length - 1]);
747
+ }
748
+ if (changedConversation) {
749
+ progress('Updated conversation', 'info', 'UPDATE_CONVERSATION', newConversation);
750
+ }
751
+ }; // 1. Check inputs
752
+ if (conversation.$agent) {
753
+ _context2.next = 12;
754
+ break;
755
+ }
756
+ throw new Error("No agent found in conversation, must define \".$agent\" in the conversation");
757
+ case 12:
758
+ persona = (config.persona || config.agents).find(function (p) {
759
+ return p.id === conversation.$agent;
760
+ });
761
+ if (persona) {
762
+ _context2.next = 15;
763
+ break;
764
+ }
765
+ throw new Error("No persona found (\"".concat(conversation.$agent, "\") in provided config"));
766
+ case 15:
767
+ if (messages.every(function (m) {
768
+ return !!m.id;
769
+ })) {
770
+ _context2.next = 17;
771
+ break;
772
+ }
773
+ throw new Error("Every message must have an \".id\", ensure all messages have an id assigned before running");
774
+ case 17:
775
+ if (messages.every(function (m) {
776
+ return m.role === 'customer' || m.role === 'agent' || m.role === 'system';
777
+ })) {
778
+ _context2.next = 20;
779
+ break;
780
+ }
781
+ invalidRoles = messages.filter(function (m) {
782
+ return m.role !== 'customer' && m.role !== 'agent' && m.role !== 'system';
783
+ });
784
+ throw new Error("Every message must have a role of \"customer\", \"agent\", or \"system\". Got invalid roles: ".concat(invalidRoles.map(function (m) {
785
+ return m.role;
786
+ }).join(', ')));
787
+ case 20:
788
+ // if message is not in messages, then add it
789
+ if (!messages.find(function (m) {
790
+ return m.id === input.message.id;
791
+ })) {
792
+ messages.push(input.message);
793
+ }
794
+
795
+ // 2. Parse the message
796
+ progress('Parsing message', 'info', 'SET_PROCESSING', 'user');
797
+ _context2.next = 24;
798
+ return parser(message.content, 'en');
799
+ case 24:
800
+ parsePayload = _context2.sent;
801
+ if (parsePayload.intent) {
802
+ message.intent = parsePayload.intent;
803
+ }
804
+ if (typeof parsePayload.intentScore === 'number') {
805
+ message.intentScore = parsePayload.intentScore;
806
+ }
807
+ message.context = parsePayload.context;
808
+ index = messages.findIndex(function (m) {
809
+ return m.content === message.content || m.id === message.id;
810
+ });
811
+ if (index === -1) {
812
+ _message = {
813
+ id: idGenerator('customer'),
814
+ role: 'customer',
815
+ content: message,
816
+ context: parsePayload.context,
817
+ time: new Date().toISOString()
818
+ };
819
+ if (parsePayload.intent) {
820
+ _message.intent = parsePayload.intent;
821
+ }
822
+ if (typeof parsePayload.intentScore === 'number') {
823
+ _message.intentScore = parsePayload.intentScore;
824
+ }
825
+ message = _message;
826
+ messages.push(_message);
827
+ progress('Added message', 'info', 'ADD_MESSAGE', _message);
828
+ } else {
829
+ messages[index].context = parsePayload.context;
830
+ if (parsePayload.intent) {
831
+ messages[index].intent = parsePayload.intent;
832
+ }
833
+ if (typeof parsePayload.intentScore === 'number') {
834
+ messages[index].intentScore = parsePayload.intentScore;
835
+ }
836
+ message = messages[index];
837
+ progress('Parsed message', 'success', 'UPDATE_MESSAGE', message);
838
+ }
839
+ // If this is the first user message, then update conversations intent
840
+ previousUserMessages = messages.filter(function (m) {
841
+ return m.role === 'customer' && m.content !== message.content;
842
+ });
843
+ if (!conversation.intent || previousUserMessages.length === 0 && parsePayload.intent) {
844
+ conversation.intent = parsePayload.intent;
845
+ conversation.intentScore = (parsePayload === null || parsePayload === void 0 ? void 0 : parsePayload.intentScore) || 0;
846
+ progress('Updated conversation intent', 'info', 'UPDATE_CONVERSATION', {
847
+ intent: parsePayload.intent,
848
+ intentScore: (parsePayload === null || parsePayload === void 0 ? void 0 : parsePayload.intentScore) || 0
849
+ });
850
+ }
851
+ oldKeyCount = Object.keys(context).length;
852
+ context = updateContext(context, parsePayload.context);
853
+ newKeyCount = Object.keys(context).length;
854
+ if (!conversation.locked && newKeyCount > oldKeyCount) {
855
+ // Reset lock attempts
856
+ conversation.locked = false;
857
+ conversation.lockAttempts = 0;
858
+ conversation.lockedReason = '';
859
+ progress('Reset lock', 'info', 'UPDATE_CONVERSATION', {
860
+ locked: false,
861
+ lockAttempts: 0,
862
+ lockedReason: ''
863
+ });
864
+ }
865
+ noNewContext = Object.keys(parsePayload.context).length === 0; // 3. Run the workflow
866
+ progress('Running workflow', 'info', 'SET_PROCESSING', 'system');
867
+ _context2.next = 40;
868
+ return workflow({
869
+ messages: messages,
870
+ conversation: conversation,
871
+ context: context,
872
+ message: message,
873
+ agent: persona,
874
+ customer: customer,
875
+ intent: {
876
+ current: ((_recentUserMessage = recentUserMessage(messages)) === null || _recentUserMessage === void 0 ? void 0 : _recentUserMessage.intent) || null,
877
+ flow: messages.map(function (m) {
878
+ return m.intent;
879
+ }).filter(Boolean),
880
+ initial: conversation.intent || null
881
+ },
882
+ stagnationCount: conversation.lockAttempts || 0
883
+ }).then(function (res) {
884
+ return Array.isArray(res) ? res : [res];
885
+ });
886
+ case 40:
887
+ slots = _context2.sent;
888
+ hasNoInstructions = slots.every(function (s) {
889
+ return !s.instructions || Array.isArray(s) && s.instructions.length === 0;
890
+ });
891
+ hasNoCustomMessage = slots.every(function (s) {
892
+ return !s.message;
893
+ });
894
+ previousLockAttempt = conversation.lockAttempts || 0; // Used to track
895
+ if (hasNoInstructions && noNewContext) {
896
+ conversation = incrementLockAttempt(conversation, config);
897
+ } else {
898
+ conversation.lockAttempts = 0;
899
+ conversation.locked = false;
900
+ conversation.lockedReason = '';
901
+ progress('Reset lock', 'info', 'UPDATE_CONVERSATION', {
902
+ lockAttempts: 0,
903
+ locked: false,
904
+ lockedReason: ''
905
+ });
906
+ }
907
+ resettedIntent = false;
908
+ _iterator = _createForOfIteratorHelper(slots);
909
+ _context2.prev = 47;
910
+ _iterator.s();
911
+ case 49:
912
+ if ((_step = _iterator.n()).done) {
913
+ _context2.next = 89;
914
+ break;
915
+ }
916
+ _step$value = _step.value, forward = _step$value.forward, forwardNote = _step$value.forwardNote, instructions = _step$value.instructions, removeInstructions = _step$value.removeInstructions, manualMessage = _step$value.message, scheduled = _step$value.scheduled, resetIntent = _step$value.resetIntent, secondsDelay = _step$value.secondsDelay, contextUpsert = _step$value.contextUpsert;
917
+ // Forward to agent or other agent
918
+ if (forward) {
919
+ conversation = lockConversation(conversation, 'App instructed forward');
920
+ _forward = forward;
921
+ _forwardNote = forwardNote;
922
+ if (typeof forward === 'string') {
923
+ updateConversation(conversation, {
924
+ forwarded: forward
925
+ });
926
+ messages.push({
927
+ id: idGenerator('sys'),
928
+ role: 'system',
929
+ content: "forwarded to \"".concat(forward, "\""),
930
+ time: new Date().toISOString()
931
+ });
932
+ progress("Forwarded to \"".concat(forward, "\""), 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
933
+ } else if (typeof forward === 'boolean') {
934
+ updateConversation(conversation, {
935
+ forwarded: conversation.$agent
936
+ });
937
+ messages.push({
938
+ id: idGenerator('sys'),
939
+ role: 'system',
940
+ content: "forwarded to \"".concat(forward, "\""),
941
+ time: new Date().toISOString()
942
+ });
943
+ progress("Forwarded to agent", 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
944
+ } else {
945
+ messages.push({
946
+ id: idGenerator('sys'),
947
+ role: 'system',
948
+ content: "forwarded to \"".concat(forward.to, "\" ").concat(forward.mode ? ' (' + forward.mode + ')' : ''),
949
+ time: new Date().toISOString()
950
+ });
951
+ progress("Forwarded to \"".concat(forward.to, "\" ").concat(forward.mode ? ' (' + forward.mode + ')' : ''), 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
952
+ updateConversation(conversation, {
953
+ forwarded: forward.to
954
+ });
955
+ }
956
+ }
957
+
958
+ // Insert instructions context
959
+ if (!instructions) {
960
+ _context2.next = 67;
961
+ break;
962
+ }
963
+ if (!(typeof instructions === 'string')) {
964
+ _context2.next = 57;
965
+ break;
966
+ }
967
+ addInstruction(instructions, previousLockAttempt);
968
+ _context2.next = 67;
969
+ break;
970
+ case 57:
971
+ if (!Array.isArray(instructions)) {
972
+ _context2.next = 62;
973
+ break;
974
+ }
975
+ _iterator2 = _createForOfIteratorHelper(instructions);
976
+ try {
977
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
978
+ instruction = _step2.value;
979
+ if (typeof instruction === 'string') {
980
+ addInstruction(instruction, previousLockAttempt);
981
+ } else {
982
+ addInstruction(instruction.content, previousLockAttempt, instruction.id);
983
+ }
984
+ }
985
+ } catch (err) {
986
+ _iterator2.e(err);
987
+ } finally {
988
+ _iterator2.f();
989
+ }
990
+ _context2.next = 67;
991
+ break;
992
+ case 62:
993
+ if (!(_typeof(instructions) === 'object' && 'content' in instructions && 'id' in instructions)) {
994
+ _context2.next = 66;
995
+ break;
996
+ }
997
+ addInstruction(instructions.content, previousLockAttempt, instructions.id);
998
+ _context2.next = 67;
999
+ break;
1000
+ case 66:
1001
+ throw new Error('instructions must be a string or array or {content: "", id: ""}');
1002
+ case 67:
1003
+ if (!removeInstructions) {
1004
+ _context2.next = 84;
1005
+ break;
1006
+ }
1007
+ _iterator3 = _createForOfIteratorHelper(removeInstructions);
1008
+ _context2.prev = 69;
1009
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
1010
+ var instructionId, index;
1011
+ return _regeneratorRuntime().wrap(function _loop$(_context) {
1012
+ while (1) switch (_context.prev = _context.next) {
1013
+ case 0:
1014
+ instructionId = _step3.value;
1015
+ index = messages.findIndex(function (m) {
1016
+ return m.id === instructionId;
1017
+ });
1018
+ if (index > -1) {
1019
+ messages.splice(index, 1);
1020
+ progress('Remove instruction', 'info', 'REMOVE_MESSAGE', instructionId);
1021
+ } else {
1022
+ console.log('instruction not found', instructionId);
1023
+ }
1024
+ case 3:
1025
+ case "end":
1026
+ return _context.stop();
1027
+ }
1028
+ }, _loop);
1029
+ });
1030
+ _iterator3.s();
1031
+ case 72:
1032
+ if ((_step3 = _iterator3.n()).done) {
1033
+ _context2.next = 76;
1034
+ break;
1035
+ }
1036
+ return _context2.delegateYield(_loop(), "t0", 74);
1037
+ case 74:
1038
+ _context2.next = 72;
1039
+ break;
1040
+ case 76:
1041
+ _context2.next = 81;
1042
+ break;
1043
+ case 78:
1044
+ _context2.prev = 78;
1045
+ _context2.t1 = _context2["catch"](69);
1046
+ _iterator3.e(_context2.t1);
1047
+ case 81:
1048
+ _context2.prev = 81;
1049
+ _iterator3.f();
1050
+ return _context2.finish(81);
1051
+ case 84:
1052
+ if (manualMessage) {
1053
+ manualMessageObj = {
1054
+ id: idGenerator('agent'),
1055
+ role: 'agent',
1056
+ content: message,
1057
+ time: new Date().toISOString()
1058
+ };
1059
+ if (scheduled) {
1060
+ manualMessageObj.time = new Date(scheduled * 1000).toISOString();
1061
+ manualMessageObj.scheduled = manualMessageObj.time;
1062
+ } else if (secondsDelay) {
1063
+ now = new Date();
1064
+ now.setSeconds(now.getSeconds() + secondsDelay);
1065
+ manualMessageObj.time = now.toISOString();
1066
+ manualMessageObj.delayInSeconds = secondsDelay;
1067
+ }
1068
+ messages.push(manualMessageObj);
1069
+ progress('Added manual message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1070
+ }
1071
+ if (contextUpsert) {
1072
+ context = updateContext(context, contextUpsert);
1073
+ progress('Upserted context', 'info', 'UPDATE_CONTEXT', contextUpsert);
1074
+ }
1075
+ if (resetIntent) {
1076
+ resettedIntent = true;
1077
+ }
1078
+ case 87:
1079
+ _context2.next = 49;
1080
+ break;
1081
+ case 89:
1082
+ _context2.next = 94;
1083
+ break;
1084
+ case 91:
1085
+ _context2.prev = 91;
1086
+ _context2.t2 = _context2["catch"](47);
1087
+ _iterator.e(_context2.t2);
1088
+ case 94:
1089
+ _context2.prev = 94;
1090
+ _iterator.f();
1091
+ return _context2.finish(94);
1092
+ case 97:
1093
+ if (resettedIntent && !_forward) {
1094
+ conversation.intent = null;
1095
+ conversation.intentScore = null;
1096
+ conversation.locked = false;
1097
+ conversation.lockedReason = '';
1098
+ conversation.lockAttempts = 0;
1099
+ progress('Reset conversation intent', 'info', 'UPDATE_CONVERSATION', {
1100
+ intent: null,
1101
+ intentScore: null,
1102
+ locked: false,
1103
+ lockAttempts: 0,
1104
+ lockedReason: ''
1105
+ });
1106
+ }
1107
+
1108
+ // 4. Generate response
1109
+ // If conversation previously locked, don't generate
1110
+ if (input.conversation.locked) {
1111
+ _context2.next = 112;
1112
+ break;
1113
+ }
1114
+ if (!((!conversation.locked || !hasNoInstructions) && !!hasNoCustomMessage)) {
1115
+ _context2.next = 112;
1116
+ break;
1117
+ }
1118
+ _context2.prev = 100;
1119
+ progress('Parsing message', 'info', 'SET_PROCESSING', 'system');
1120
+ _context2.next = 104;
1121
+ return generator({
1122
+ messages: messages,
1123
+ persona: persona,
1124
+ context: context,
1125
+ llm: config.llm,
1126
+ pmt: config.pmt
1127
+ });
1128
+ case 104:
1129
+ generatorPayload = _context2.sent;
1130
+ if (!generatorPayload.send) {
1131
+ progress('Generated response', 'failed', undefined, {
1132
+ error: generatorPayload.error || 'Unknown Reason'
1133
+ });
1134
+ console.error("Locking conversation, api returned send false: ".concat(generatorPayload.message), generatorPayload.error || 'Unknown Reason');
1135
+ conversation = lockConversation(conversation, 'API: ' + generatorPayload.error || 'Unknown Reason');
1136
+ } else {
1137
+ progress('Generated response', 'success', undefined, undefined);
1138
+ // Check if already had message
1139
+ agentMessages = messages.filter(function (m) {
1140
+ return m.role === 'agent';
1141
+ });
1142
+ lastAgentMessage = agentMessages[agentMessages.length - 1];
1143
+ if (lastAgentMessage && lastAgentMessage.content === generatorPayload.message) {
1144
+ // Error should not have happened
1145
+ conversation = lockConversation(conversation, 'Duplicate message');
1146
+ } else {
1147
+ messages.push({
1148
+ id: idGenerator('agent'),
1149
+ role: 'agent',
1150
+ content: generatorPayload.message,
1151
+ time: new Date().toISOString()
1152
+ });
1153
+ progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1154
+ }
1155
+
1156
+ // Check if conversation was marked for forward (generator message still allowed to be sent)
1157
+ if (generatorPayload.forward) {
1158
+ conversation = lockConversation(conversation, 'API: ' + generatorPayload.forwardNote || 'Forwarded by API');
1159
+ if (!_forward) {
1160
+ _forward = generatorPayload.forward;
1161
+ _forwardNote = generatorPayload.forwardNote;
1162
+ }
1163
+ }
1164
+ }
1165
+ _context2.next = 112;
1166
+ break;
1167
+ case 108:
1168
+ _context2.prev = 108;
1169
+ _context2.t3 = _context2["catch"](100);
1170
+ console.error("Locking conversation, error generating response: ".concat(_context2.t3.message));
1171
+ conversation = lockConversation(conversation, 'API: ' + _context2.t3.message);
1172
+ case 112:
1173
+ progress('Parsing message', 'info', 'SET_PROCESSING', null);
1174
+ return _context2.abrupt("return", {
1175
+ conversation: {
1176
+ before: conversationBefore,
1177
+ after: conversation,
1178
+ forward: _forward || null,
1179
+ forwardNote: _forwardNote || ''
1180
+ },
1181
+ messages: {
1182
+ before: messagesBefore,
1183
+ after: messages
1184
+ },
1185
+ message: {
1186
+ before: messageBefore,
1187
+ after: message
1188
+ },
1189
+ context: {
1190
+ before: contextBefore,
1191
+ after: context
1192
+ }
1193
+ });
1194
+ case 114:
1195
+ case "end":
1196
+ return _context2.stop();
1197
+ }
1198
+ }, _callee, null, [[47, 91, 94, 97], [69, 78, 81, 84], [100, 108]]);
1199
+ }));
1200
+ function customer(_x) {
1201
+ return _customer.apply(this, arguments);
1202
+ }
1203
+ return customer;
1204
+ }()
1205
+ };
1206
+
1207
+ exports.Spirits = Spirits;
1208
+ exports._asyncToGenerator = _asyncToGenerator;
1209
+ exports._classCallCheck = _classCallCheck;
1210
+ exports._createClass = _createClass;
1211
+ exports._createForOfIteratorHelper = _createForOfIteratorHelper;
1212
+ exports._defineProperty = _defineProperty;
1213
+ exports._objectSpread2 = _objectSpread2;
1214
+ exports._objectWithoutProperties = _objectWithoutProperties;
1215
+ exports._regeneratorRuntime = _regeneratorRuntime;
1216
+ exports._slicedToArray = _slicedToArray;
1217
+ exports._toConsumableArray = _toConsumableArray;
1218
+ exports._typeof = _typeof;