@tiledesk/tiledesk-tybot-connector 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +1 -52
  2. package/ExtUtil.js +1 -0
  3. package/TdCache copy.js +242 -0
  4. package/TiledeskExpression.js +1 -6
  5. package/TiledeskWhenExpression.js +1 -18
  6. package/engine/MongodbBotsDataSource.js +1 -3
  7. package/engine/MongodbIntentsMachine.js +2 -3
  8. package/engine/TiledeskChatbot.js +4 -76
  9. package/engine/TiledeskChatbotConst.js +1 -7
  10. package/engine/mock/MockBotsDataSource.js +6 -11
  11. package/index.js +36 -132
  12. package/models/faq_kb.js +0 -11
  13. package/package.json +1 -1
  14. package/services/AIController.js +1 -31
  15. package/services/AIService.js +33 -62
  16. package/services/IntegrationService.js +1 -4
  17. package/services/{LLMService.js → KbService.js} +3 -3
  18. package/services/RequestService.js +2 -23
  19. package/services/TilebotService.js +3 -19
  20. package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +17 -34
  21. package/tiledeskChatbotPlugs/directives/DirAiCondition.js +51 -18
  22. package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +52 -103
  23. package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +5 -108
  24. package/tiledeskChatbotPlugs/directives/DirCallSubagent.js +8 -34
  25. package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +11 -36
  26. package/tiledeskChatbotPlugs/directives/DirGptTask.js +4 -16
  27. package/tiledeskChatbotPlugs/directives/DirIntent.js +6 -12
  28. package/tiledeskChatbotPlugs/directives/DirIteration.js +10 -63
  29. package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +16 -69
  30. package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +2 -40
  31. package/tiledeskChatbotPlugs/directives/DirReply.js +6 -81
  32. package/tiledeskChatbotPlugs/directives/DirReplyV2.js +4 -58
  33. package/tiledeskChatbotPlugs/directives/DirWebRequest.js +0 -8
  34. package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +1 -11
  35. package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +418 -0
  36. package/tiledeskChatbotPlugs/directives/DirWebResponse.js +2 -5
  37. package/tiledeskChatbotPlugs/directives/Directives.js +0 -6
  38. package/utils/HttpUtils.js +17 -99
  39. package/utils/TiledeskChatbotUtil.js +5 -73
  40. package/utils/winston.js +2 -80
  41. package/services/InternalSubAgentService.js +0 -330
  42. package/tiledeskChatbotPlugs/directives/DirInviteHuman.js +0 -259
  43. package/tiledeskChatbotPlugs/directives/DirInvokeSubAgent.js +0 -345
  44. package/tiledeskChatbotPlugs/directives/DirJSONConditionMulti.js +0 -171
  45. package/tiledeskChatbotPlugs/directives/DirRemoveHuman.js +0 -129
  46. package/tiledeskChatbotPlugs/directives/DirReturn.js +0 -98
  47. package/utils/ConnectorsV3.js +0 -292
  48. package/utils/LlmStream.js +0 -215
  49. package/utils/SentenceChunker.js +0 -94
  50. package/utils/StreamSender.js +0 -109
@@ -1,13 +1,10 @@
1
1
  const { Filler } = require('../Filler');
2
2
  const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
3
3
  const { TiledeskChatbotUtil } = require('../../utils/TiledeskChatbotUtil');
4
- const { InternalSubAgentService } = require('../../services/InternalSubAgentService');
5
4
  let axios = require('axios');
6
5
  const { TiledeskClient } = require('@tiledesk/tiledesk-client');
7
6
  const { Logger } = require('../../Logger');
8
- const aiService = require('../../services/AIService');
9
7
  const winston = require('../../utils/winston')
10
- const { v4: uuidv4 } = require('uuid');
11
8
 
12
9
  class DirReply {
13
10
 
@@ -22,7 +19,6 @@ class DirReply {
22
19
  this.tdcache = context.tdcache;
23
20
  this.log = context.log;
24
21
  this.API_ENDPOINT = context.API_ENDPOINT;
25
- this.API_URL = context.API_URL;
26
22
 
27
23
  this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest?.draft, intent_id: this.context.reply?.intent_id || this.context.reply?.attributes?.intent_info?.intent_id });
28
24
  this.tdClient = new TiledeskClient({ projectId: this.context.projectId, token: this.context.token, APIURL: this.API_ENDPOINT, APIKEY: "___", log: this.log });
@@ -88,49 +84,24 @@ class DirReply {
88
84
  if (commands.length > 0) {
89
85
  for (let i = 0; i < commands.length; i++) {
90
86
  let command = commands[i];
87
+
91
88
  if (command.type === 'message' && command.message && command.message.text) {
92
89
  command.message.text = filler.fill(command.message.text, requestAttributes);
93
90
  TiledeskChatbotUtil.fillCommandAttachments(command, requestAttributes);
94
- winston.debug("(DirReply) command filled: " + command.message.text);
91
+ winston.debug("DirReply command filled: " + command.message.text);
95
92
  }
96
93
 
97
94
  if (command.type === 'message' && command.message && command.message.metadata) {
98
95
  command.message.metadata.src = filler.fill(command.message.metadata.src, requestAttributes);
99
96
  command.message.metadata.downloadURL = filler.fill(command.message.metadata.downloadURL, requestAttributes);
100
- winston.debug("(DirReply) command filled (metadata.src): " + command.message.metadata.src);
101
- winston.debug("(DirReply) command filled (metadata.downloadURL): " + command.message.metadata.downloadURL);
102
- }
103
-
104
- if (command.type === 'message' && command.message && command.message.type === 'tts') {
105
- command.message.text = filler.fill(command.message.text, requestAttributes);
106
-
107
- const uid = uuidv4();
108
- const voiceSettings = {
109
- text: command.message.text,
110
- provider: requestAttributes['VOICE_PROVIDER'],
111
- model: requestAttributes['TTS_MODEL'],
112
- voice: requestAttributes['TTS_VOICE_NAME'],
113
- language: requestAttributes['TTS_VOICE_LANGUAGE']
114
- }
115
- // No server-side preload: the widget synthesizes the audio through
116
- // the speech proxy, and metadata.src is only its last fallback.
117
- // const voiceSpeech = await aiService.textToSpeech(voiceSettings, this.projectId, this.token)
118
- command.message.metadata = {
119
- type: 'audio/mp3',
120
- uid: uid,
121
- // filename: `audio-${Date.now().toString(36)}.${voiceSpeech.contentType.split('/')[1]}`,
122
- filename: `audio-${uid}.mp3`,
123
- src: `${this.API_URL}/${this.projectId}/llm/speech/${uid}`,
124
- voiceSettings: voiceSettings
125
- }
126
- winston.debug("(DirReply) command filled (tts): " + command.message.text);
127
- winston.debug("(DirReply) command filled (tts metadata): " + JSON.stringify(command.message.metadata));
97
+ winston.debug("DirReply command filled (metadata.src): " + command.message.metadata.src);
98
+ winston.debug("DirReply command filled (metadata.downloadURL): " + command.message.metadata.downloadURL);
128
99
  }
129
100
 
130
101
  if (command.type === 'settings' && command.settings) {
131
102
  Object.keys(command.settings).forEach(k => {
132
103
  command.settings[k] = filler.fill(command.settings[k], requestAttributes)
133
- winston.debug("(DirReply) settings command filled: " + command.settings[k]);
104
+ winston.debug("DirReply settings command filled: " + command.settings[k]);
134
105
  })
135
106
  }
136
107
  }
@@ -191,22 +162,9 @@ class DirReply {
191
162
  winston.debug("DirReply reply with clean message: ", cleanMessage);
192
163
  this.logger.native("[Reply] Reply with 2: " + cleanMessage.text);
193
164
 
194
- const outboundRequestId = InternalSubAgentService.resolveOutboundRequestId(
195
- this.requestId,
196
- requestAttributes,
197
- this.context
198
- );
199
- if (outboundRequestId !== this.requestId) {
200
- winston.debug(`(DirReply) Sub-agent reply routed to parent request ${outboundRequestId}`);
201
- }
202
-
203
- if (this.context.turnId && this.tdcache) {
204
- await this.#tagStreamedReply(cleanMessage);
205
- }
206
-
207
165
  await TiledeskChatbotUtil.updateConversationTranscript(this.context.chatbot, cleanMessage);
208
166
  this.tdClient.sendSupportMessage(
209
- outboundRequestId,
167
+ this.requestId,
210
168
  cleanMessage,
211
169
  (err) => {
212
170
  if (err) {
@@ -227,39 +185,6 @@ class DirReply {
227
185
 
228
186
  }
229
187
 
230
- /**
231
- * Voice turns: when this reply speaks the text an AI action has just streamed (see DirAiPrompt), mark it with
232
- * attributes.stream_id so the channel closes the stream instead of speaking the text a second time.
233
- */
234
- async #tagStreamedReply(message) {
235
- try {
236
- const key = TiledeskChatbot.pendingStreamCacheKey(this.requestId);
237
- const pending = await this.tdcache.getJSON(key);
238
- if (!pending || !pending.stream_id || typeof pending.text !== "string") {
239
- return;
240
- }
241
- const streamed = pending.text.trim();
242
- const texts = [message.text];
243
- if (message.attributes && Array.isArray(message.attributes.commands)) {
244
- message.attributes.commands.forEach((c) => {
245
- if (c && c.type === "message" && c.message) {
246
- texts.push(c.message.text);
247
- }
248
- });
249
- }
250
- if (texts.some((t) => typeof t === "string" && t.trim() === streamed)) {
251
- message.attributes = message.attributes || {};
252
- message.attributes.stream_id = pending.stream_id;
253
- await this.tdcache.del(key);
254
- winston.verbose("(DirReply) reply closes stream " + pending.stream_id);
255
- } else {
256
- winston.verbose("(DirReply) reply does not match the pending stream " + pending.stream_id + ", sent untagged");
257
- }
258
- } catch (err) {
259
- winston.error("(DirReply) Error matching the streamed reply: " + err.message);
260
- }
261
- }
262
-
263
188
  }
264
189
 
265
190
  module.exports = { DirReply };
@@ -2,13 +2,11 @@ const { Filler } = require('../Filler');
2
2
  const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
3
3
  const { TiledeskChatbotConst } = require('../../engine/TiledeskChatbotConst');
4
4
  const { TiledeskChatbotUtil } = require('../../utils/TiledeskChatbotUtil');
5
- const { InternalSubAgentService } = require('../../services/InternalSubAgentService');
6
5
  const { DirIntent } = require("./DirIntent");
7
6
  // const { defaultOptions } = require('liquidjs');
8
7
  const { DirMessageToBot } = require('./DirMessageToBot');
9
8
  const { v4: uuidv4 } = require('uuid');
10
9
  const { TiledeskClient } = require('@tiledesk/tiledesk-client');
11
- const aiService = require('../../services/AIService');
12
10
  const winston = require('../../utils/winston');
13
11
  const { Logger } = require('../../Logger');
14
12
 
@@ -85,10 +83,6 @@ class DirReplyV2 {
85
83
  const buttons = TiledeskChatbotUtil.allReplyButtons(message);
86
84
  if (buttons && buttons.length > 0) {
87
85
  const locked = await this.lockUnlock(action); // first execution returns locked, then unlocked
88
- if (locked === null) { // could not lock: stop, do not ask
89
- callback(true);
90
- return;
91
- }
92
86
  if (locked) { // fist execution returns (just) locked
93
87
  must_stop = true; // you must stop after next callbacks (in this flow) if there are buttons
94
88
  if (action.noInputIntent) {
@@ -100,11 +94,6 @@ class DirReplyV2 {
100
94
  setTimeout(async () => {
101
95
  winston.debug("(DirReplyV2) noinput timeout triggered!");
102
96
  const userInput = await this.chatbot.getParameter(TiledeskChatbotConst.USER_INPUT);
103
- const lockedAction = await this.chatbot.currentLockedAction(this.requestId);
104
- if (lockedAction !== action["_tdActionId"]) {
105
- winston.debug("(DirReplyV2) lock owned by another action, skipping noinput");
106
- return;
107
- }
108
97
  if (userInput && userInput === timeout_id) {
109
98
  await this.chatbot.unlockIntent(this.requestId);
110
99
  await this.chatbot.unlockAction(this.requestId);
@@ -205,33 +194,6 @@ class DirReplyV2 {
205
194
  command.message.text = filler.fill(command.message.text, requestAttributes);
206
195
  TiledeskChatbotUtil.fillCommandAttachments(command, requestAttributes);
207
196
  }
208
-
209
- if (command.type === 'message' && command.message && command.message.metadata) {
210
- command.message.metadata.src = filler.fill(command.message.metadata.src, requestAttributes);
211
- command.message.metadata.downloadURL = filler.fill(command.message.metadata.downloadURL, requestAttributes);
212
- winston.debug("(DirReplyV2) command filled (metadata.src): " + command.message.metadata.src);
213
- winston.debug("(DirReplyV2) command filled (metadata.downloadURL): " + command.message.metadata.downloadURL);
214
- }
215
-
216
- if (command.type === 'message' && command.message && command.message.type === 'tts') {
217
- command.message.text = filler.fill(command.message.text, requestAttributes);
218
- const voiceSettings = {
219
- text: command.message.text,
220
- provider: requestAttributes['VOICE_PROVIDER'],
221
- model: requestAttributes['TTS_MODEL'],
222
- voice: requestAttributes['TTS_VOICE_NAME'],
223
- language: requestAttributes['TTS_VOICE_LANGUAGE']
224
- }
225
- const voiceSpeech = await aiService.textToSpeech(voiceSettings, this.projectId, this.token)
226
- command.message.metadata = {
227
- type: voiceSpeech.contentType,
228
- uid: Date.now().toString(36),
229
- filename: `audio-${Date.now().toString(36)}.${voiceSpeech.contentType.split('/')[1]}`,
230
- src: this.API_ENDPOINT + "/files?path=" + encodeURIComponent(voiceSpeech.filename)
231
- }
232
- winston.debug("(DirReplyV2) command filled (tts): " + command.message.text);
233
- winston.debug("(DirReplyV2) command filled (tts metadata): " + JSON.stringify(command.message.metadata));
234
- }
235
197
  }
236
198
  }
237
199
  }
@@ -284,19 +246,9 @@ class DirReplyV2 {
284
246
  // }
285
247
  cleanMessage.senderFullname = this.context.chatbot.bot.name;
286
248
  winston.debug("(DirReplyV2) Reply: ", cleanMessage);
287
-
288
- const outboundRequestId = InternalSubAgentService.resolveOutboundRequestId(
289
- this.requestId,
290
- requestAttributes,
291
- this.context
292
- );
293
- if (outboundRequestId !== this.requestId) {
294
- winston.debug(`(DirReplyV2) Sub-agent reply routed to parent request ${outboundRequestId}`);
295
- }
296
-
297
249
  await TiledeskChatbotUtil.updateConversationTranscript(this.context.chatbot, cleanMessage);
298
250
  this.tdClient.sendSupportMessage(
299
- outboundRequestId,
251
+ this.requestId,
300
252
  cleanMessage,
301
253
  (err) => {
302
254
  if (err) {
@@ -320,16 +272,10 @@ class DirReplyV2 {
320
272
 
321
273
 
322
274
  async lockUnlock(action, callback) {
323
- const lockedAction = await this.chatbot.currentLockedAction(this.requestId);
324
- // a lock only counts as "waiting for the reply" when this very action set it
325
- const own = lockedAction && lockedAction === action["_tdActionId"];
275
+ let lockedAction = await this.chatbot.currentLockedAction(this.requestId);
326
276
 
327
- if (!own) {
328
- const intent_name = this.reply?.attributes?.intent_info?.intent_name;
329
- if (!intent_name) {
330
- winston.error("(DirReplyV2) Cannot lock: missing attributes.intent_info.intent_name");
331
- return null; // caller stops the block without locking
332
- }
277
+ if (!lockedAction) {
278
+ const intent_name = this.reply.attributes.intent_info.intent_name
333
279
  const actionId = action["_tdActionId"];
334
280
  await this.chatbot.lockIntent(this.requestId, intent_name);
335
281
  await this.chatbot.lockAction(this.requestId, actionId);
@@ -3,7 +3,6 @@ let https = require("https");
3
3
  const { Filler } = require('../Filler');
4
4
  const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
5
5
  const { TiledeskJSONEval } = require('../../TiledeskJSONEval');
6
- const { AnalyticsClient } = require('../../AnalyticsClient');
7
6
  const winston = require('../../utils/winston');
8
7
 
9
8
  class DirWebRequest {
@@ -28,13 +27,6 @@ class DirWebRequest {
28
27
  return;
29
28
  }
30
29
  this.go(action, () => {
31
- AnalyticsClient.track('webhook.triggered', this.context.projectId, {
32
- webhook_id: action.webhookId || action._id || 'unknown',
33
- agent_id: this.context.chatbot?.botId || '',
34
- block_id: directive.blockId || directive.action?.blockId || 'unknown',
35
- async: action.async === true,
36
- request_id: this.requestId || null
37
- });
38
30
  callback();
39
31
  });
40
32
  }
@@ -3,7 +3,6 @@ let https = require("https");
3
3
  const { Filler } = require('../Filler');
4
4
  const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
5
5
  const { DirIntent } = require('./DirIntent');
6
- const { AnalyticsClient } = require('../../AnalyticsClient');
7
6
  const winston = require('../../utils/winston');
8
7
  const { Logger } = require('../../Logger');
9
8
 
@@ -38,13 +37,6 @@ class DirWebRequestV2 {
38
37
  this.logger.native("Executing WebRequest action ", directive.action)
39
38
  this.go(action, (stop) => {
40
39
  this.logger.native("[Web Request] Executed");
41
- AnalyticsClient.track('webhook.triggered', this.context.projectId, {
42
- webhook_id: action.webhookId || action._id || 'unknown',
43
- agent_id: this.context.chatbot?.botId || '',
44
- block_id: directive.blockId || directive.action?.blockId || 'unknown',
45
- async: action.async === true,
46
- request_id: this.requestId || null
47
- });
48
40
  callback(stop);
49
41
  }).catch((err) => {
50
42
  // do not nothing
@@ -119,7 +111,6 @@ class DirWebRequestV2 {
119
111
  HTTPREQUEST, async (err, res) => {
120
112
 
121
113
  let resbody = res.data;
122
- console.log("\n\nDirWebRequestV2 resbody: ", resbody);
123
114
  let status = res.status;
124
115
  let error = res.error;
125
116
  await this.#assignAttributes(action, resbody, status, error)
@@ -127,7 +118,7 @@ class DirWebRequestV2 {
127
118
  this.logger.native("[Web Request] resbody: ", resbody);
128
119
 
129
120
  if (err) {
130
- this.logger.error("[Web Request] error: ", err);
121
+ this.logger.error("WebRequest error: ", err);
131
122
  winston.log("webRequest error: ", err);
132
123
  if (callback) {
133
124
  if (falseIntent) {
@@ -140,7 +131,6 @@ class DirWebRequestV2 {
140
131
  }
141
132
  }
142
133
  else if (res.status >= 200 && res.status <= 299) {
143
-
144
134
  if (trueIntent) {
145
135
  await this.#executeCondition(true, trueIntent, trueIntentAttributes, falseIntent, falseIntentAttributes);
146
136
  callback(true);