@scout9/app 1.0.0-alpha.0.7.0 → 1.0.0-alpha.0.7.2

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var spirits = require("./spirits-59475def.cjs");
3
+ var spirits = require("./spirits-51104a4a.cjs");
4
4
  var require$$0$4 = require('util');
5
5
  var require$$0$3 = require('stream');
6
6
  var require$$1 = require('path');
@@ -35241,7 +35241,7 @@ function _loadUserPackageJson() {
35241
35241
  targetPkgUrl = isTest ? packageTestJsonUrl : packageJsonUrl;
35242
35242
  _context2.t0 = JSON;
35243
35243
  _context2.next = 10;
35244
- return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('dev-d74b94c8.js', document.baseURI).href))), 'utf-8');
35244
+ return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('dev-d2f96a9d.js', document.baseURI).href))), 'utf-8');
35245
35245
  case 10:
35246
35246
  _context2.t1 = _context2.sent;
35247
35247
  pkg = _context2.t0.parse.call(_context2.t0, _context2.t1);
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var spirits = require("./spirits-59475def.cjs");
4
- var dev = require("./dev-d74b94c8.cjs");
3
+ var spirits = require("./spirits-51104a4a.cjs");
4
+ var dev = require("./dev-d2f96a9d.cjs");
5
5
  var macros = require("./macros-22b2e0b8.cjs");
6
6
  var require$$0 = require('fs');
7
7
  var require$$2$1 = require('events');
@@ -29483,7 +29483,7 @@ class Body {
29483
29483
  }
29484
29484
  const {
29485
29485
  toFormData
29486
- } = await Promise.resolve().then(function () { return require("./multipart-parser-8ce4a465.cjs"); });
29486
+ } = await Promise.resolve().then(function () { return require("./multipart-parser-d0654ebb.cjs"); });
29487
29487
  return toFormData(this.body, ct);
29488
29488
  }
29489
29489
 
@@ -41884,7 +41884,7 @@ function _loadUserPackageJson() {
41884
41884
  targetPkgUrl = isTest ? packageTestJsonUrl : packageJsonUrl;
41885
41885
  _context.t0 = JSON;
41886
41886
  _context.next = 10;
41887
- return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-ddb54eed.js', document.baseURI).href))), 'utf-8');
41887
+ return fs__default["default"].readFile(new URL(targetPkgUrl, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-5a88279c.js', document.baseURI).href))), 'utf-8');
41888
41888
  case 10:
41889
41889
  _context.t1 = _context.sent;
41890
41890
  pkg = _context.t0.parse.call(_context.t0, _context.t1);
@@ -43176,7 +43176,7 @@ var ProjectFiles = /*#__PURE__*/function () {
43176
43176
  return ProjectFiles;
43177
43177
  }();
43178
43178
 
43179
- var __filename$1 = node_url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-ddb54eed.js', document.baseURI).href)));
43179
+ var __filename$1 = node_url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-5a88279c.js', document.baseURI).href)));
43180
43180
  var __dirname$1 = path__default["default"].dirname(__filename$1);
43181
43181
  function zipDirectory(source, out) {
43182
43182
  var archive = archiver$1('tar', {
@@ -43391,7 +43391,7 @@ function _buildApp() {
43391
43391
  case 11:
43392
43392
  _context4.t0 = JSON;
43393
43393
  _context4.next = 14;
43394
- return fs__default["default"].readFile(new URL(templatePackagePath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-ddb54eed.js', document.baseURI).href))), 'utf-8');
43394
+ return fs__default["default"].readFile(new URL(templatePackagePath, (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index-5a88279c.js', document.baseURI).href))), 'utf-8');
43395
43395
  case 14:
43396
43396
  _context4.t1 = _context4.sent;
43397
43397
  packageTemplate = _context4.t0.parse.call(_context4.t0, _context4.t1);
package/dist/index.cjs CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var index = require("./index-ddb54eed.cjs");
6
- var dev = require("./dev-d74b94c8.cjs");
7
- require("./spirits-59475def.cjs");
5
+ var index = require("./index-5a88279c.cjs");
6
+ var dev = require("./dev-d2f96a9d.cjs");
7
+ require("./spirits-51104a4a.cjs");
8
8
  require("./macros-22b2e0b8.cjs");
9
9
  require('fs');
10
10
  require('events');
@@ -2,9 +2,9 @@
2
2
 
3
3
  require('node:fs');
4
4
  require('node:path');
5
- var index = require("./index-ddb54eed.cjs");
6
- require("./spirits-59475def.cjs");
7
- require("./dev-d74b94c8.cjs");
5
+ var index = require("./index-5a88279c.cjs");
6
+ require("./spirits-51104a4a.cjs");
7
+ require("./dev-d2f96a9d.cjs");
8
8
  require('util');
9
9
  require('stream');
10
10
  require('path');
@@ -731,15 +731,111 @@ var Spirits = {
731
731
  /**
732
732
  * Customer message
733
733
  * @param {ConversationData & CustomerSpiritCallbacks} input
734
+ * @param {(error: Error) => void} onError
734
735
  * @returns {Promise<ConversationEvent>}
735
736
  */
736
737
  customer: function () {
737
738
  var _customer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input) {
738
739
  var _recentUserMessage;
739
- var customer, config, parser, workflow, generator, transformer, idGenerator, _input$progress, progress, messageBefore, contextBefore, messagesBefore, conversationBefore, conversation, messages, context, message, followup, entityContextUpsert, updateConversation, updateContext, userMessages, recentUserMessage, lockConversation, incrementLockAttempt, _addInstruction, addInstruction, persona, invalidRoles, parsePayload, index, _message, previousUserMessages, oldKeyCount, newKeyCount, noNewContext, slots, hasNoInstructions, hasNoCustomMessage, messagesToTransform, previousLockAttempt, resettedIntent, _forward, _forwardNote, _tasks, _iterator, _step, _step$value, forward, forwardNote, instructions, removeInstructions, manualMessage, scheduled, resetIntent, secondsDelay, contextUpsert, anticipate, slotFollowup, slotEntityContextUpsert, tasks, _slots, map, i, _anticipate$i, keywords, _slot, slotId, _tasks2, _iterator3, _step3, instruction, _iterator4, _step4, _loop, manualMessageObj, now, generatorInput, generatorPayload, agentMessages, lastAgentMessage, _generatorPayload$ent, _generatorPayload$con, _iterator2, _step2, transformResponse, _agentMessages, _lastAgentMessage;
740
+ var onError,
741
+ customer,
742
+ config,
743
+ parser,
744
+ workflow,
745
+ generator,
746
+ transformer,
747
+ idGenerator,
748
+ _input$progress,
749
+ progress,
750
+ messageBefore,
751
+ contextBefore,
752
+ messagesBefore,
753
+ conversationBefore,
754
+ conversation,
755
+ messages,
756
+ context,
757
+ message,
758
+ followup,
759
+ entityContextUpsert,
760
+ updateConversation,
761
+ updateContext,
762
+ userMessages,
763
+ recentUserMessage,
764
+ lockConversation,
765
+ incrementLockAttempt,
766
+ _addInstruction,
767
+ addInstruction,
768
+ persona,
769
+ invalidRoles,
770
+ parsePayload,
771
+ index,
772
+ _message,
773
+ previousUserMessages,
774
+ oldKeyCount,
775
+ newKeyCount,
776
+ noNewContext,
777
+ slots,
778
+ hasNoInstructions,
779
+ hasNoCustomMessage,
780
+ messagesToTransform,
781
+ previousLockAttempt,
782
+ resettedIntent,
783
+ _forward,
784
+ _forwardNote,
785
+ _tasks,
786
+ _iterator,
787
+ _step,
788
+ _step$value,
789
+ forward,
790
+ forwardNote,
791
+ instructions,
792
+ removeInstructions,
793
+ manualMessage,
794
+ scheduled,
795
+ resetIntent,
796
+ secondsDelay,
797
+ contextUpsert,
798
+ anticipate,
799
+ slotFollowup,
800
+ slotEntityContextUpsert,
801
+ tasks,
802
+ _slots,
803
+ map,
804
+ i,
805
+ _anticipate$i,
806
+ keywords,
807
+ _slot,
808
+ slotId,
809
+ _tasks2,
810
+ _iterator4,
811
+ _step4,
812
+ instruction,
813
+ _iterator5,
814
+ _step5,
815
+ _loop,
816
+ manualMessageObj,
817
+ now,
818
+ generatorInput,
819
+ generatorPayload,
820
+ _generatorPayload$ent,
821
+ _generatorPayload$con,
822
+ _generatorPayload$med,
823
+ agentMessages,
824
+ lastAgentMessage,
825
+ addedMessages,
826
+ _iterator2,
827
+ _step2,
828
+ newMessage,
829
+ _iterator3,
830
+ _step3,
831
+ transformResponse,
832
+ _agentMessages,
833
+ _lastAgentMessage,
834
+ _args2 = arguments;
740
835
  return _regeneratorRuntime().wrap(function _callee$(_context2) {
741
836
  while (1) switch (_context2.prev = _context2.next) {
742
837
  case 0:
838
+ onError = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : function () {};
743
839
  customer = input.customer, config = input.config, parser = input.parser, workflow = input.workflow, generator = input.generator, transformer = input.transformer, 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;
744
840
  conversation = input.conversation, messages = input.messages, context = input.context, message = input.message; // Storing post process events here
745
841
  followup = [];
@@ -832,40 +928,40 @@ var Spirits = {
832
928
  }
833
929
  }; // 1. Check inputs
834
930
  if (conversation.$agent) {
835
- _context2.next = 14;
931
+ _context2.next = 15;
836
932
  break;
837
933
  }
838
934
  throw new Error("SpiritsError: No agent found in conversation, must define \".$agent\" in the conversation");
839
- case 14:
935
+ case 15:
840
936
  persona = (config.persona || config.personas || config.agents).find(function (p) {
841
937
  return p.id === conversation.$agent;
842
938
  });
843
939
  if (persona) {
844
- _context2.next = 19;
940
+ _context2.next = 20;
845
941
  break;
846
942
  }
847
943
  if (!(config.persona || config.personas || config.agents).some(function (a) {
848
944
  return !a.id;
849
945
  })) {
850
- _context2.next = 18;
946
+ _context2.next = 19;
851
947
  break;
852
948
  }
853
949
  throw new Error("SpiritsError: No persona found (\"".concat(conversation.$agent, "\") in provided config, some persona's did not contain an \"id\" (Internal Mapping Error)"));
854
- case 18:
855
- throw new Error("SpiritsError: No persona found (\"".concat(conversation.$agent, "\") in provided config"));
856
950
  case 19:
951
+ throw new Error("SpiritsError: No persona found (\"".concat(conversation.$agent, "\") in provided config"));
952
+ case 20:
857
953
  if (messages.every(function (m) {
858
954
  return !!m.id;
859
955
  })) {
860
- _context2.next = 21;
956
+ _context2.next = 22;
861
957
  break;
862
958
  }
863
959
  throw new Error("SpiritsError: Every message must have an \".id\", ensure all messages have an id assigned before running");
864
- case 21:
960
+ case 22:
865
961
  if (messages.every(function (m) {
866
962
  return m.role === 'customer' || m.role === 'agent' || m.role === 'system';
867
963
  })) {
868
- _context2.next = 24;
964
+ _context2.next = 25;
869
965
  break;
870
966
  }
871
967
  invalidRoles = messages.filter(function (m) {
@@ -874,7 +970,7 @@ var Spirits = {
874
970
  throw new Error("SpiritsError: Every message must have a role of \"customer\", \"agent\", or \"system\". Got invalid roles: ".concat(invalidRoles.map(function (m) {
875
971
  return m.role;
876
972
  }).join(', ')));
877
- case 24:
973
+ case 25:
878
974
  // if message is not in messages, then add it
879
975
  if (!messages.find(function (m) {
880
976
  return m.id === input.message.id;
@@ -884,9 +980,9 @@ var Spirits = {
884
980
 
885
981
  // 2. Parse the message
886
982
  progress('Parsing message', 'info', 'SET_PROCESSING', 'user');
887
- _context2.next = 28;
983
+ _context2.next = 29;
888
984
  return parser(message.content, 'en');
889
- case 28:
985
+ case 29:
890
986
  parsePayload = _context2.sent;
891
987
  if (parsePayload.intent) {
892
988
  message.intent = parsePayload.intent;
@@ -957,7 +1053,7 @@ var Spirits = {
957
1053
  }
958
1054
  noNewContext = Object.keys(parsePayload.context).length === 0; // 3. Run the workflow
959
1055
  progress('Running workflow', 'info', 'SET_PROCESSING', 'system');
960
- _context2.next = 45;
1056
+ _context2.next = 46;
961
1057
  return workflow({
962
1058
  messages: messages,
963
1059
  conversation: conversation,
@@ -986,7 +1082,7 @@ var Spirits = {
986
1082
  return accumulator;
987
1083
  }, []);
988
1084
  });
989
- case 45:
1085
+ case 46:
990
1086
  slots = _context2.sent;
991
1087
  hasNoInstructions = slots.every(function (s) {
992
1088
  return !s.instructions || Array.isArray(s.instructions) && s.instructions.length === 0;
@@ -1013,20 +1109,20 @@ var Spirits = {
1013
1109
  resettedIntent = false;
1014
1110
  /** @type {Array<string> | undefined} */
1015
1111
  _iterator = _createForOfIteratorHelper(slots);
1016
- _context2.prev = 53;
1112
+ _context2.prev = 54;
1017
1113
  _iterator.s();
1018
- case 55:
1114
+ case 56:
1019
1115
  if ((_step = _iterator.n()).done) {
1020
- _context2.next = 126;
1116
+ _context2.next = 127;
1021
1117
  break;
1022
1118
  }
1023
1119
  _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, anticipate = _step$value.anticipate, slotFollowup = _step$value.followup, slotEntityContextUpsert = _step$value.entityContextUpsert, tasks = _step$value.tasks;
1024
1120
  if (!anticipate) {
1025
- _context2.next = 70;
1121
+ _context2.next = 71;
1026
1122
  break;
1027
1123
  }
1028
1124
  if (!Array.isArray(anticipate)) {
1029
- _context2.next = 65;
1125
+ _context2.next = 66;
1030
1126
  break;
1031
1127
  }
1032
1128
  // 'literal' anticipation
@@ -1046,11 +1142,11 @@ var Spirits = {
1046
1142
  slots: _slots,
1047
1143
  map: map
1048
1144
  });
1049
- _context2.next = 70;
1145
+ _context2.next = 71;
1050
1146
  break;
1051
- case 65:
1147
+ case 66:
1052
1148
  if (!('yes' in anticipate && 'no' in anticipate && 'did' in anticipate)) {
1053
- _context2.next = 69;
1149
+ _context2.next = 70;
1054
1150
  break;
1055
1151
  }
1056
1152
  // "did" anticipation
@@ -1062,11 +1158,11 @@ var Spirits = {
1062
1158
  },
1063
1159
  did: anticipate.did
1064
1160
  });
1065
- _context2.next = 70;
1161
+ _context2.next = 71;
1066
1162
  break;
1067
- case 69:
1068
- throw new Error("Invalid anticipate payload \"".concat(JSON.stringify(anticipate), "\""));
1069
1163
  case 70:
1164
+ throw new Error("Invalid anticipate payload \"".concat(JSON.stringify(anticipate), "\""));
1165
+ case 71:
1070
1166
  // tasks from auto/manual ingress to execute
1071
1167
  if (!!tasks && Array.isArray(tasks) && !!tasks.length) {
1072
1168
  if (!_tasks) _tasks = [];
@@ -1122,25 +1218,25 @@ var Spirits = {
1122
1218
 
1123
1219
  // Insert instructions context
1124
1220
  if (!instructions) {
1125
- _context2.next = 89;
1221
+ _context2.next = 90;
1126
1222
  break;
1127
1223
  }
1128
1224
  if (!(typeof instructions === 'string')) {
1129
- _context2.next = 79;
1225
+ _context2.next = 80;
1130
1226
  break;
1131
1227
  }
1132
1228
  addInstruction(instructions, previousLockAttempt);
1133
- _context2.next = 89;
1229
+ _context2.next = 90;
1134
1230
  break;
1135
- case 79:
1231
+ case 80:
1136
1232
  if (!Array.isArray(instructions)) {
1137
- _context2.next = 84;
1233
+ _context2.next = 85;
1138
1234
  break;
1139
1235
  }
1140
- _iterator3 = _createForOfIteratorHelper(instructions);
1236
+ _iterator4 = _createForOfIteratorHelper(instructions);
1141
1237
  try {
1142
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1143
- instruction = _step3.value;
1238
+ for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1239
+ instruction = _step4.value;
1144
1240
  if (typeof instruction === 'string') {
1145
1241
  addInstruction(instruction, previousLockAttempt);
1146
1242
  } else {
@@ -1148,35 +1244,35 @@ var Spirits = {
1148
1244
  }
1149
1245
  }
1150
1246
  } catch (err) {
1151
- _iterator3.e(err);
1247
+ _iterator4.e(err);
1152
1248
  } finally {
1153
- _iterator3.f();
1249
+ _iterator4.f();
1154
1250
  }
1155
- _context2.next = 89;
1251
+ _context2.next = 90;
1156
1252
  break;
1157
- case 84:
1253
+ case 85:
1158
1254
  if (!(_typeof(instructions) === 'object' && 'content' in instructions)) {
1159
- _context2.next = 88;
1255
+ _context2.next = 89;
1160
1256
  break;
1161
1257
  }
1162
1258
  addInstruction(instructions.content, previousLockAttempt, instructions.id);
1163
- _context2.next = 89;
1259
+ _context2.next = 90;
1164
1260
  break;
1165
- case 88:
1166
- throw new Error("SpiritsError: instructions must be a string or array or {content: \"<instruction>\"}, got: ".concat(JSON.stringify(instructions)));
1167
1261
  case 89:
1262
+ throw new Error("SpiritsError: instructions must be a string or array or {content: \"<instruction>\"}, got: ".concat(JSON.stringify(instructions)));
1263
+ case 90:
1168
1264
  if (!removeInstructions) {
1169
- _context2.next = 106;
1265
+ _context2.next = 107;
1170
1266
  break;
1171
1267
  }
1172
- _iterator4 = _createForOfIteratorHelper(removeInstructions);
1173
- _context2.prev = 91;
1268
+ _iterator5 = _createForOfIteratorHelper(removeInstructions);
1269
+ _context2.prev = 92;
1174
1270
  _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
1175
1271
  var instructionId, index;
1176
1272
  return _regeneratorRuntime().wrap(function _loop$(_context) {
1177
1273
  while (1) switch (_context.prev = _context.next) {
1178
1274
  case 0:
1179
- instructionId = _step4.value;
1275
+ instructionId = _step5.value;
1180
1276
  index = messages.findIndex(function (m) {
1181
1277
  return m.id === instructionId;
1182
1278
  });
@@ -1194,30 +1290,30 @@ var Spirits = {
1194
1290
  }
1195
1291
  }, _loop);
1196
1292
  });
1197
- _iterator4.s();
1198
- case 94:
1199
- if ((_step4 = _iterator4.n()).done) {
1200
- _context2.next = 98;
1293
+ _iterator5.s();
1294
+ case 95:
1295
+ if ((_step5 = _iterator5.n()).done) {
1296
+ _context2.next = 99;
1201
1297
  break;
1202
1298
  }
1203
- return _context2.delegateYield(_loop(), "t0", 96);
1204
- case 96:
1205
- _context2.next = 94;
1299
+ return _context2.delegateYield(_loop(), "t0", 97);
1300
+ case 97:
1301
+ _context2.next = 95;
1206
1302
  break;
1207
- case 98:
1208
- _context2.next = 103;
1303
+ case 99:
1304
+ _context2.next = 104;
1209
1305
  break;
1210
- case 100:
1211
- _context2.prev = 100;
1212
- _context2.t1 = _context2["catch"](91);
1213
- _iterator4.e(_context2.t1);
1214
- case 103:
1215
- _context2.prev = 103;
1216
- _iterator4.f();
1217
- return _context2.finish(103);
1218
- case 106:
1306
+ case 101:
1307
+ _context2.prev = 101;
1308
+ _context2.t1 = _context2["catch"](92);
1309
+ _iterator5.e(_context2.t1);
1310
+ case 104:
1311
+ _context2.prev = 104;
1312
+ _iterator5.f();
1313
+ return _context2.finish(104);
1314
+ case 107:
1219
1315
  if (!manualMessage) {
1220
- _context2.next = 122;
1316
+ _context2.next = 123;
1221
1317
  break;
1222
1318
  }
1223
1319
  /** @type {import('@scout9/app').Message} */
@@ -1229,25 +1325,25 @@ var Spirits = {
1229
1325
  time: new Date().toISOString()
1230
1326
  };
1231
1327
  if (!(_typeof(manualMessage) === 'object')) {
1232
- _context2.next = 114;
1328
+ _context2.next = 115;
1233
1329
  break;
1234
1330
  }
1235
1331
  Object.assign(manualMessageObj, manualMessage);
1236
1332
  manualMessageObj.role = 'agent';
1237
1333
  manualMessageObj.time = new Date().toISOString();
1238
- _context2.next = 119;
1334
+ _context2.next = 120;
1239
1335
  break;
1240
- case 114:
1336
+ case 115:
1241
1337
  if (!(typeof manualMessage === 'string')) {
1242
- _context2.next = 118;
1338
+ _context2.next = 119;
1243
1339
  break;
1244
1340
  }
1245
1341
  manualMessageObj.content = manualMessage;
1246
- _context2.next = 119;
1342
+ _context2.next = 120;
1247
1343
  break;
1248
- case 118:
1249
- throw new Error('Manual message must be of type "string" or "DirectMessage"');
1250
1344
  case 119:
1345
+ throw new Error('Manual message must be of type "string" or "DirectMessage"');
1346
+ case 120:
1251
1347
  if (scheduled) {
1252
1348
  manualMessageObj.time = new Date(scheduled * 1000).toISOString();
1253
1349
  manualMessageObj.scheduled = manualMessageObj.time;
@@ -1259,7 +1355,7 @@ var Spirits = {
1259
1355
  }
1260
1356
  messages.push(manualMessageObj);
1261
1357
  progress('Added manual message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1262
- case 122:
1358
+ case 123:
1263
1359
  if (contextUpsert) {
1264
1360
  context = updateContext(context, contextUpsert);
1265
1361
  progress('Upserted context', 'info', 'UPDATE_CONTEXT', contextUpsert);
@@ -1267,21 +1363,21 @@ var Spirits = {
1267
1363
  if (resetIntent) {
1268
1364
  resettedIntent = true;
1269
1365
  }
1270
- case 124:
1271
- _context2.next = 55;
1366
+ case 125:
1367
+ _context2.next = 56;
1272
1368
  break;
1273
- case 126:
1274
- _context2.next = 131;
1369
+ case 127:
1370
+ _context2.next = 132;
1275
1371
  break;
1276
- case 128:
1277
- _context2.prev = 128;
1278
- _context2.t2 = _context2["catch"](53);
1372
+ case 129:
1373
+ _context2.prev = 129;
1374
+ _context2.t2 = _context2["catch"](54);
1279
1375
  _iterator.e(_context2.t2);
1280
- case 131:
1281
- _context2.prev = 131;
1376
+ case 132:
1377
+ _context2.prev = 132;
1282
1378
  _iterator.f();
1283
- return _context2.finish(131);
1284
- case 134:
1379
+ return _context2.finish(132);
1380
+ case 135:
1285
1381
  if (resettedIntent && !_forward) {
1286
1382
  conversation.intent = null;
1287
1383
  conversation.intentScore = null;
@@ -1300,15 +1396,17 @@ var Spirits = {
1300
1396
  // 4. Generate response
1301
1397
  // If conversation previously locked, don't generate
1302
1398
  if (input.conversation.locked) {
1303
- _context2.next = 184;
1399
+ _context2.next = 187;
1304
1400
  break;
1305
1401
  }
1306
1402
  if (!((!conversation.locked || !hasNoInstructions) && !!hasNoCustomMessage)) {
1307
- _context2.next = 151;
1403
+ _context2.next = 153;
1308
1404
  break;
1309
1405
  }
1310
- _context2.prev = 137;
1406
+ _context2.prev = 138;
1311
1407
  progress('Generating message', 'info', 'SET_PROCESSING', 'system');
1408
+
1409
+ /** @type {import('@scout9/admin').GenerateRequestOneOf1} */
1312
1410
  generatorInput = {
1313
1411
  messages: messages,
1314
1412
  persona: persona,
@@ -1319,16 +1417,16 @@ var Spirits = {
1319
1417
  if (!!_tasks && Array.isArray(_tasks) && !!_tasks.length) {
1320
1418
  generatorInput.tasks = _tasks;
1321
1419
  }
1322
- _context2.next = 143;
1420
+ _context2.next = 144;
1323
1421
  return generator(generatorInput);
1324
- case 143:
1422
+ case 144:
1325
1423
  generatorPayload = _context2.sent;
1326
1424
  if (!generatorPayload.send) {
1327
1425
  progress('Generated response', 'failed', undefined, {
1328
1426
  error: generatorPayload.error || 'Unknown Reason'
1329
1427
  });
1330
- console.error("Locking conversation, api returned send false: ".concat(generatorPayload.message), generatorPayload.error || 'Unknown Reason');
1331
- conversation = lockConversation(conversation, 'API: ' + generatorPayload.error || 'Unknown Reason');
1428
+ console.error("Locking conversation, api returned send false: ".concat(generatorPayload.message), generatorPayload.error || generatorPayload.forwardNote || 'Unknown Reason');
1429
+ conversation = lockConversation(conversation, 'API: ' + generatorPayload.error || generatorPayload.forwardNote || 'Unknown Reason');
1332
1430
  } else {
1333
1431
  progress('Generated response', 'success', undefined, undefined);
1334
1432
  // Check if already had message
@@ -1336,19 +1434,49 @@ var Spirits = {
1336
1434
  return m.role === 'agent';
1337
1435
  });
1338
1436
  lastAgentMessage = agentMessages[agentMessages.length - 1];
1339
- if (lastAgentMessage && lastAgentMessage.content === generatorPayload.message) {
1437
+ addedMessages = [{
1438
+ id: idGenerator('agent'),
1439
+ content: generatorPayload.message,
1440
+ role: 'agent',
1441
+ time: new Date().toISOString(),
1442
+ entities: (_generatorPayload$ent = generatorPayload.entities) !== null && _generatorPayload$ent !== void 0 ? _generatorPayload$ent : [],
1443
+ context: (_generatorPayload$con = generatorPayload.context) !== null && _generatorPayload$con !== void 0 ? _generatorPayload$con : {},
1444
+ mediaUrls: (_generatorPayload$med = generatorPayload.mediaUrls) !== null && _generatorPayload$med !== void 0 ? _generatorPayload$med : []
1445
+ }].concat(_toConsumableArray(((generatorPayload === null || generatorPayload === void 0 ? void 0 : generatorPayload.addedMessages) || []).map(function (message) {
1446
+ var _message$time, _message$entities, _message$context;
1447
+ return {
1448
+ id: idGenerator('agent'),
1449
+ content: message.content,
1450
+ role: 'agent',
1451
+ time: ((_message$time = message.time) === null || _message$time === void 0 || (_message$time = _message$time.toDate()) === null || _message$time === void 0 ? void 0 : _message$time.toISOString()) || new Date().toISOString(),
1452
+ entities: (_message$entities = message.entities) !== null && _message$entities !== void 0 ? _message$entities : {},
1453
+ context: (_message$context = message.context) !== null && _message$context !== void 0 ? _message$context : {},
1454
+ mediaUrls: message.mediaUrls
1455
+ };
1456
+ }))).reduce(function (accumulator, message) {
1457
+ if (!accumulator.find(function (m) {
1458
+ return m.content === message.content;
1459
+ })) accumulator.push(message);
1460
+ return accumulator;
1461
+ }, []);
1462
+ if (lastAgentMessage && lastAgentMessage.content && addedMessages.some(function (message) {
1463
+ return message.content === lastAgentMessage.content;
1464
+ })) {
1340
1465
  // Error should not have happened
1341
1466
  conversation = lockConversation(conversation, 'Duplicate message');
1342
1467
  } else {
1343
- messages.push({
1344
- id: idGenerator('agent'),
1345
- role: 'agent',
1346
- content: generatorPayload.message,
1347
- time: new Date().toISOString(),
1348
- entities: (_generatorPayload$ent = generatorPayload.entities) !== null && _generatorPayload$ent !== void 0 ? _generatorPayload$ent : [],
1349
- context: (_generatorPayload$con = generatorPayload.context) !== null && _generatorPayload$con !== void 0 ? _generatorPayload$con : {}
1350
- });
1351
- progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1468
+ _iterator2 = _createForOfIteratorHelper(addedMessages);
1469
+ try {
1470
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1471
+ newMessage = _step2.value;
1472
+ messages.push(message);
1473
+ progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1474
+ }
1475
+ } catch (err) {
1476
+ _iterator2.e(err);
1477
+ } finally {
1478
+ _iterator2.f();
1479
+ }
1352
1480
  }
1353
1481
 
1354
1482
  // Check if conversation was marked for forward (generator message still allowed to be sent)
@@ -1360,29 +1488,30 @@ var Spirits = {
1360
1488
  }
1361
1489
  }
1362
1490
  }
1363
- _context2.next = 151;
1491
+ _context2.next = 153;
1364
1492
  break;
1365
- case 147:
1366
- _context2.prev = 147;
1367
- _context2.t3 = _context2["catch"](137);
1368
- console.error("Locking conversation, error generating response: ".concat(_context2.t3.message));
1493
+ case 148:
1494
+ _context2.prev = 148;
1495
+ _context2.t3 = _context2["catch"](138);
1496
+ onError(_context2.t3);
1497
+ console.error("Spirits: Locking conversation, error generating response: ".concat(_context2.t3.message));
1369
1498
  conversation = lockConversation(conversation, 'API: ' + _context2.t3.message);
1370
- case 151:
1499
+ case 153:
1371
1500
  if (!(messagesToTransform.length && transformer)) {
1372
- _context2.next = 183;
1501
+ _context2.next = 186;
1373
1502
  break;
1374
1503
  }
1375
- _context2.prev = 152;
1376
- _iterator2 = _createForOfIteratorHelper(messagesToTransform);
1377
1504
  _context2.prev = 154;
1378
- _iterator2.s();
1379
- case 156:
1380
- if ((_step2 = _iterator2.n()).done) {
1381
- _context2.next = 167;
1505
+ _iterator3 = _createForOfIteratorHelper(messagesToTransform);
1506
+ _context2.prev = 156;
1507
+ _iterator3.s();
1508
+ case 158:
1509
+ if ((_step3 = _iterator3.n()).done) {
1510
+ _context2.next = 169;
1382
1511
  break;
1383
1512
  }
1384
- _step2.value;
1385
- _context2.next = 160;
1513
+ _step3.value;
1514
+ _context2.next = 162;
1386
1515
  return transformer({
1387
1516
  message: messagesToTransform,
1388
1517
  persona: persona,
@@ -1390,7 +1519,7 @@ var Spirits = {
1390
1519
  messages: messages,
1391
1520
  context: context
1392
1521
  });
1393
- case 160:
1522
+ case 162:
1394
1523
  transformResponse = _context2.sent;
1395
1524
  progress('Generated response', 'success', undefined, undefined);
1396
1525
  // Check if already had message
@@ -1410,36 +1539,37 @@ var Spirits = {
1410
1539
  });
1411
1540
  progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
1412
1541
  }
1413
- case 165:
1414
- _context2.next = 156;
1415
- break;
1416
1542
  case 167:
1417
- _context2.next = 172;
1543
+ _context2.next = 158;
1418
1544
  break;
1419
1545
  case 169:
1420
- _context2.prev = 169;
1421
- _context2.t4 = _context2["catch"](154);
1422
- _iterator2.e(_context2.t4);
1423
- case 172:
1424
- _context2.prev = 172;
1425
- _iterator2.f();
1426
- return _context2.finish(172);
1427
- case 175:
1428
- _context2.next = 181;
1546
+ _context2.next = 174;
1429
1547
  break;
1548
+ case 171:
1549
+ _context2.prev = 171;
1550
+ _context2.t4 = _context2["catch"](156);
1551
+ _iterator3.e(_context2.t4);
1552
+ case 174:
1553
+ _context2.prev = 174;
1554
+ _iterator3.f();
1555
+ return _context2.finish(174);
1430
1556
  case 177:
1431
- _context2.prev = 177;
1432
- _context2.t5 = _context2["catch"](152);
1557
+ _context2.next = 184;
1558
+ break;
1559
+ case 179:
1560
+ _context2.prev = 179;
1561
+ _context2.t5 = _context2["catch"](154);
1433
1562
  console.error("Locking conversation, error transforming response: ".concat(_context2.t5.message));
1434
1563
  conversation = lockConversation(conversation, 'API: ' + _context2.t5.message);
1435
- case 181:
1436
- _context2.next = 184;
1564
+ onError(_context2.t5);
1565
+ case 184:
1566
+ _context2.next = 187;
1437
1567
  break;
1438
- case 183:
1568
+ case 186:
1439
1569
  if (messagesToTransform.length) {
1440
1570
  console.warn("No transformer provided");
1441
1571
  }
1442
- case 184:
1572
+ case 187:
1443
1573
  progress('Parsing message', 'info', 'SET_PROCESSING', null);
1444
1574
  return _context2.abrupt("return", {
1445
1575
  conversation: {
@@ -1463,11 +1593,11 @@ var Spirits = {
1463
1593
  followup: followup,
1464
1594
  entityContextUpsert: entityContextUpsert
1465
1595
  });
1466
- case 186:
1596
+ case 189:
1467
1597
  case "end":
1468
1598
  return _context2.stop();
1469
1599
  }
1470
- }, _callee, null, [[53, 128, 131, 134], [91, 100, 103, 106], [137, 147], [152, 177], [154, 169, 172, 175]]);
1600
+ }, _callee, null, [[54, 129, 132, 135], [92, 101, 104, 107], [138, 148], [154, 179], [156, 171, 174, 177]]);
1471
1601
  }));
1472
1602
  function customer(_x) {
1473
1603
  return _customer.apply(this, arguments);
package/dist/spirits.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var spirits = require("./spirits-59475def.cjs");
5
+ var spirits = require("./spirits-51104a4a.cjs");
6
6
 
7
7
 
8
8
 
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dev = require("./dev-d74b94c8.cjs");
6
- require("./spirits-59475def.cjs");
5
+ var dev = require("./dev-d2f96a9d.cjs");
6
+ require("./spirits-51104a4a.cjs");
7
7
  require('util');
8
8
  require('stream');
9
9
  require('path');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scout9/app",
3
- "version": "1.0.0-alpha.0.7.0",
3
+ "version": "1.0.0-alpha.0.7.2",
4
4
  "description": "Build and deploy your Scout9 app for SMS auto replies",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -114,9 +114,11 @@ export const Spirits = {
114
114
  /**
115
115
  * Customer message
116
116
  * @param {ConversationData & CustomerSpiritCallbacks} input
117
+ * @param {(error: Error) => void} onError
117
118
  * @returns {Promise<ConversationEvent>}
118
119
  */
119
- customer: async function (input) {
120
+ customer: async function (input, onError = () => {
121
+ }) {
120
122
  const {
121
123
  customer,
122
124
  config,
@@ -432,7 +434,7 @@ export const Spirits = {
432
434
  yes: anticipate.yes,
433
435
  no: anticipate.no
434
436
  },
435
- did: anticipate.did,
437
+ did: anticipate.did
436
438
  });
437
439
  } else {
438
440
  throw new Error(`Invalid anticipate payload "${JSON.stringify(anticipate)}"`);
@@ -509,7 +511,8 @@ export const Spirits = {
509
511
  } else if (typeof instructions === 'object' && 'content' in instructions) {
510
512
  addInstruction(instructions.content, previousLockAttempt, instructions.id);
511
513
  } else {
512
- throw new Error(`SpiritsError: instructions must be a string or array or {content: "<instruction>"}, got: ${JSON.stringify(instructions)}`);
514
+ throw new Error(`SpiritsError: instructions must be a string or array or {content: "<instruction>"}, got: ${JSON.stringify(
515
+ instructions)}`);
513
516
  }
514
517
  }
515
518
 
@@ -522,7 +525,8 @@ export const Spirits = {
522
525
  messages.splice(index, 1);
523
526
  progress('Remove instruction', 'info', 'REMOVE_MESSAGE', instructionId);
524
527
  } else {
525
- console.log(`Instruction not found "${instructionId}", other ids: ${messages.map(m => `"${m.id}"`).join(', ')}`);
528
+ console.log(`Instruction not found "${instructionId}", other ids: ${messages.map(m => `"${m.id}"`)
529
+ .join(', ')}`);
526
530
  }
527
531
  }
528
532
  }
@@ -591,13 +595,16 @@ export const Spirits = {
591
595
  if ((!conversation.locked || !hasNoInstructions) && !!hasNoCustomMessage) {
592
596
  try {
593
597
  progress('Generating message', 'info', 'SET_PROCESSING', 'system');
598
+
599
+ /** @type {import('@scout9/admin').GenerateRequestOneOf1} */
594
600
  const generatorInput = {
595
601
  messages,
596
602
  persona,
597
603
  context,
598
604
  llm: config.llm,
599
605
  pmt: config.pmt
600
- }
606
+ };
607
+
601
608
  if (!!_tasks && Array.isArray(_tasks) && !!_tasks.length) {
602
609
  generatorInput.tasks = _tasks;
603
610
  }
@@ -606,27 +613,51 @@ export const Spirits = {
606
613
  progress('Generated response', 'failed', undefined, {error: generatorPayload.error || 'Unknown Reason'});
607
614
  console.error(
608
615
  `Locking conversation, api returned send false: ${generatorPayload.message}`,
609
- generatorPayload.error || 'Unknown Reason'
616
+ generatorPayload.error || generatorPayload.forwardNote || 'Unknown Reason'
617
+ );
618
+ conversation = lockConversation(
619
+ conversation,
620
+ 'API: ' + generatorPayload.error || generatorPayload.forwardNote || 'Unknown Reason'
610
621
  );
611
- conversation = lockConversation(conversation, 'API: ' + generatorPayload.error || 'Unknown Reason');
612
622
  } else {
613
623
  progress('Generated response', 'success', undefined, undefined);
614
624
  // Check if already had message
615
625
  const agentMessages = messages.filter(m => m.role === 'agent');
616
626
  const lastAgentMessage = agentMessages[agentMessages.length - 1];
617
- if (lastAgentMessage && lastAgentMessage.content === generatorPayload.message) {
618
- // Error should not have happened
619
- conversation = lockConversation(conversation, 'Duplicate message');
620
- } else {
621
- messages.push({
627
+ const addedMessages = [
628
+ {
622
629
  id: idGenerator('agent'),
623
- role: 'agent',
624
630
  content: generatorPayload.message,
631
+ role: 'agent',
625
632
  time: new Date().toISOString(),
626
633
  entities: generatorPayload.entities ?? [],
627
- context: generatorPayload.context ?? {}
628
- });
629
- progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
634
+ context: generatorPayload.context ?? {},
635
+ mediaUrls: generatorPayload.mediaUrls ?? []
636
+ },
637
+ ...(generatorPayload?.addedMessages || [])
638
+ .map((message) => ({
639
+ id: idGenerator('agent'),
640
+ content: message.content,
641
+ role: 'agent',
642
+ time: message.time?.toDate()?.toISOString() || new Date().toISOString(),
643
+ entities: message.entities ?? {},
644
+ context: message.context ?? {},
645
+ mediaUrls: message.mediaUrls
646
+ }))
647
+ ]
648
+ .reduce((accumulator, message) => {
649
+ if (!accumulator.find(m => m.content === message.content)) accumulator.push(message);
650
+ return accumulator;
651
+ }, []);
652
+
653
+ if (lastAgentMessage && lastAgentMessage.content && addedMessages.some((message) => message.content === lastAgentMessage.content)) {
654
+ // Error should not have happened
655
+ conversation = lockConversation(conversation, 'Duplicate message');
656
+ } else {
657
+ for (const newMessage of addedMessages) {
658
+ messages.push(message);
659
+ progress('Added agent message', 'info', 'ADD_MESSAGE', messages[messages.length - 1]);
660
+ }
630
661
  }
631
662
 
632
663
  // Check if conversation was marked for forward (generator message still allowed to be sent)
@@ -643,7 +674,8 @@ export const Spirits = {
643
674
  }
644
675
 
645
676
  } catch (e) {
646
- console.error(`Locking conversation, error generating response: ${e.message}`);
677
+ onError(e);
678
+ console.error(`Spirits: Locking conversation, error generating response: ${e.message}`);
647
679
  conversation = lockConversation(conversation, 'API: ' + e.message);
648
680
  }
649
681
  }
@@ -680,9 +712,10 @@ export const Spirits = {
680
712
  } catch (e) {
681
713
  console.error(`Locking conversation, error transforming response: ${e.message}`);
682
714
  conversation = lockConversation(conversation, 'API: ' + e.message);
715
+ onError(e);
683
716
  }
684
717
  } else if (messagesToTransform.length) {
685
- console.warn(`No transformer provided`)
718
+ console.warn(`No transformer provided`);
686
719
  }
687
720
  }
688
721
 
package/types/index.d.ts CHANGED
@@ -883,7 +883,7 @@ declare module '@scout9/app/testing-tools' {
883
883
 
884
884
  declare module '@scout9/app/spirits' {
885
885
  export namespace Spirits {
886
- function customer(input: ConversationData & CustomerSpiritCallbacks): Promise<ConversationEvent>;
886
+ function customer(input: ConversationData & CustomerSpiritCallbacks, onError?: (error: Error) => void): Promise<ConversationEvent>;
887
887
  }
888
888
  export type Document = {
889
889
  id: string;