@tiledesk/tiledesk-tybot-connector 2.1.15 → 2.2.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiledesk/tiledesk-tybot-connector",
3
- "version": "2.1.15",
3
+ "version": "2.2.1",
4
4
  "description": "Tiledesk Tybot connector",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -0,0 +1,34 @@
1
+ const httpUtils = require("../utils/HttpUtils");
2
+ const winston = require("../utils/winston");
3
+ const API_ENDPOINT = process.env.API_ENDPOINT;
4
+
5
+ class RequestService {
6
+
7
+ constructor() { }
8
+
9
+ replaceBot(id_project, request_id, data, token) {
10
+ const httpRequest = {
11
+ url: API_ENDPOINT + "/" + id_project + "/requests/" + request_id + "/replace",
12
+ headers: {
13
+ 'Content-Type': 'application/json',
14
+ 'Authorization': 'JWT ' + token
15
+ },
16
+ json: data,
17
+ method: 'PUT'
18
+ };
19
+
20
+ return new Promise((resolve, reject) => {
21
+ httpUtils.request(httpRequest, (err, resbody) => {
22
+ if (err) {
23
+ winston.error("(RequestService) error: ", err);
24
+ reject(err);
25
+ return;
26
+ }
27
+ resolve(resbody);
28
+ });
29
+ });
30
+ }
31
+ }
32
+
33
+ const requestService = new RequestService();
34
+ module.exports = requestService;
@@ -65,6 +65,8 @@ const { DirFlowLog } = require('./directives/DirFlowLog');
65
65
  const { DirAddKbContent } = require('./directives/DirAddKbContent');
66
66
  const { DirIteration } = require('./directives/DirIteration');
67
67
  const { AnalyticsClient } = require('../AnalyticsClient');
68
+ const { DirCallSubAgent } = require('./directives/DirCallSubagent');
69
+ const { DirReturnStack } = require('./directives/DirReturnStack');
68
70
  const { DirDataTables } = require('./directives/DirDataTables');
69
71
 
70
72
  class DirectivesChatbotPlug {
@@ -276,6 +278,8 @@ class DirectivesChatbotPlug {
276
278
  [Directives.REPLACE_BOT]: DirReplaceBot,
277
279
  [Directives.REPLACE_BOT_V2]: DirReplaceBotV2,
278
280
  [Directives.REPLACE_BOT_V3]: DirReplaceBotV3,
281
+ [Directives.CALL_SUBAGENT]: DirCallSubAgent,
282
+ [Directives.RETURN_STACK]: DirReturnStack,
279
283
  [Directives.WAIT]: DirWait,
280
284
  [Directives.LOCK_INTENT]: DirLockIntent,
281
285
  [Directives.UNLOCK_INTENT]: DirUnlockIntent,
@@ -0,0 +1,60 @@
1
+ class SubagentStack {
2
+
3
+ constructor(options) {
4
+ if (!options) {
5
+ throw new Error('(SubagentStack) options object is mandatory.');
6
+ }
7
+ if (!options.tdCache) {
8
+ throw new Error('(SubagentStack) options.tdCache object is mandatory.');
9
+ }
10
+
11
+ this.tdCache = options.tdCache;
12
+ }
13
+
14
+ stackKey(requestId) {
15
+ return `subagent:stack:${requestId}`;
16
+ }
17
+
18
+ // Save parent state in the stack before calling the subagent
19
+ async push(requestId, snapshot) {
20
+ const key = this.stackKey(requestId);
21
+ await this.tdCache.lPush(key, JSON.stringify(snapshot));
22
+ await this.tdCache.expire(key, 60 * 60 * 24); // 24 hours
23
+ }
24
+
25
+ // Restore parent state from the stack after the subagent return
26
+ async pop(requestId) {
27
+ const key = this.stackKey(requestId);
28
+ const value = await this.tdCache.lPop(key);
29
+ if (!value) {
30
+ return null;
31
+ }
32
+ return JSON.parse(value);
33
+ }
34
+
35
+ // Look at the top of the stack without removing it
36
+ async peek(requestId) {
37
+ const key = this.stackKey(requestId);
38
+ const value = await this.tdCache.lIndex(key, 0);
39
+ if (!value) {
40
+ return null;
41
+ }
42
+ return JSON.parse(value);
43
+ }
44
+
45
+ // Number of elements in the stack
46
+ async size(requestId) {
47
+ const key = this.stackKey(requestId);
48
+ const size = await this.tdCache.lLen(key);
49
+ return size;
50
+ }
51
+
52
+ // Clear the stack
53
+ async clear(requestId) {
54
+ const key = this.stackKey(requestId);
55
+ await this.tdCache.del(key);
56
+ }
57
+
58
+ }
59
+
60
+ module.exports = { SubagentStack };
@@ -832,8 +832,8 @@ class DirAiPrompt {
832
832
  : {};
833
833
  for (const key of Object.keys(base)) {
834
834
  const v = base[key];
835
- if (v !== undefined && v !== null && typeof v !== 'string') {
836
- base[key] = typeof v === 'object' ? JSON.stringify(v) : String(v);
835
+ if (v !== undefined && v !== null) {
836
+ base[key] = DirAiPrompt.sanitizeHeaderValue(v);
837
837
  }
838
838
  }
839
839
  if (!variables || typeof variables !== 'object' || Array.isArray(variables)) {
@@ -849,7 +849,7 @@ class DirAiPrompt {
849
849
  base[key] = '';
850
850
  continue;
851
851
  }
852
- base[key] = typeof v === 'object' ? JSON.stringify(v) : String(v);
852
+ base[key] = DirAiPrompt.sanitizeHeaderValue(v);
853
853
  } catch (err) {
854
854
  winston.warn("DirAiPrompt mergeHeadersWithVariables skip key:", key, err);
855
855
  }
@@ -857,6 +857,28 @@ class DirAiPrompt {
857
857
  return base;
858
858
  }
859
859
 
860
+ // Header values reject backslash and control chars. Email bodies often
861
+ // arrive with real newlines or literal "\n" sequences in x-last-user-text.
862
+ static sanitizeHeaderValue(value) {
863
+ if (value == null) return '';
864
+ let str;
865
+ try {
866
+ str = typeof value === 'object' ? JSON.stringify(value) : String(value);
867
+ } catch (err) {
868
+ return '';
869
+ }
870
+ return str
871
+ .replace(/\\r\\n/g, ' ')
872
+ .replace(/\\n/g, ' ')
873
+ .replace(/\\r/g, ' ')
874
+ .replace(/\\t/g, ' ')
875
+ .replace(/[\u0000-\u001F\u007F]/g, ' ')
876
+ .replace(/\\/g, '')
877
+ .replace(/[^\t\x20-\x7E\x80-\xFF]/g, '')
878
+ .replace(/ {2,}/g, ' ')
879
+ .trim();
880
+ }
881
+
860
882
  async resolveNativeServerUrls(servers) {
861
883
  if (!Array.isArray(servers)) return null;
862
884
 
@@ -0,0 +1,152 @@
1
+ const { TiledeskClient } = require('@tiledesk/tiledesk-client');
2
+ const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
3
+ const { Filler } = require('../Filler');
4
+
5
+ const axios = require("axios").default;
6
+ let https = require("https");
7
+ const winston = require('../../utils/winston');
8
+ const httpUtils = require('../../utils/HttpUtils');
9
+ const { Logger } = require('../../Logger');
10
+ const { AnalyticsClient } = require('../../AnalyticsClient');
11
+ const { SubagentStack } = require('../SubagentStack');
12
+ const requestService = require('../../services/RequestService');
13
+ const jwt = require('jsonwebtoken');
14
+
15
+ class DirCallSubAgent {
16
+
17
+ constructor(context) {
18
+ if (!context) {
19
+ throw new Error('context object is mandatory.');
20
+ }
21
+ this.context = context;
22
+ this.requestId = context.requestId;
23
+ this.API_ENDPOINT = context.API_ENDPOINT;
24
+
25
+ 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 });
26
+ this.tdClient = new TiledeskClient({ projectId: this.context.projectId, token: this.context.token, APIURL: this.API_ENDPOINT, APIKEY: "___" });
27
+ }
28
+
29
+ execute(directive, callback) {
30
+ winston.verbose("Execute CallSubAgent directive");
31
+ let action;
32
+ if (directive.action) {
33
+ action = directive.action;
34
+ }
35
+ else {
36
+ this.logger.error("Incorrect action for ", directive.name, directive)
37
+ winston.warn("DirCallSubAgent Incorrect directive: ", directive);
38
+ callback();
39
+ return;
40
+ }
41
+ this.go(action, (stop) => {
42
+ this.logger.native("[Call SubAgent] Executed");
43
+ callback(stop);
44
+ })
45
+ }
46
+
47
+ async go(action, callback) {
48
+ winston.debug("(DirCallSubAgent) Action: ", action);
49
+ let botId = action.botId;
50
+ let botSlug = action.botSlug;
51
+ let useSlug = action.useSlug;
52
+ let blockName = action.blockName;
53
+
54
+ const variables =
55
+ await TiledeskChatbot.allParametersStatic(
56
+ this.context.tdcache, this.context.requestId
57
+ );
58
+
59
+ const filler = new Filler();
60
+
61
+ botSlug = filler.fill(botSlug, variables);
62
+ blockName = filler.fill(blockName, variables);
63
+
64
+ let data = {};
65
+ if (useSlug && useSlug === true) {
66
+ data.slug = botSlug;
67
+ } else {
68
+ data.id = botId;
69
+ }
70
+
71
+ const subagentStack = new SubagentStack({ tdCache: this.context.tdcache });
72
+ const intentAction = this.context.reply.actions.find(action => action._tdActionType === "intent");
73
+
74
+ const parentId = this.context.chatbot?.botId;
75
+ const parentParticipantId = participantBotIdFromToken(this.context.token) || parentId;
76
+
77
+ winston.debug("(DirCallSubAgent) push " + JSON.stringify({
78
+ requestId: this.requestId,
79
+ parentId: parentId,
80
+ parentParticipantId: parentParticipantId,
81
+ targetBotId: botId,
82
+ blockName: blockName,
83
+ nextBlock: intentAction && intentAction.intentName
84
+ }));
85
+ const stackData = {
86
+ parentId: parentId,
87
+ parentParticipantId: parentParticipantId,
88
+ parentToken: this.context.token,
89
+ nextBlock: intentAction
90
+ }
91
+ await subagentStack.push(this.requestId, stackData);
92
+
93
+ try {
94
+ const resbody = await requestService.replaceBot(this.context.projectId, this.requestId, data, this.context.token);
95
+ if (this.context.chatbot?.bot.root_id) {
96
+ AnalyticsClient.track('agent.bot_switched', this.context.projectId, {
97
+ from_agent_id: this.context.chatbot?.bot.root_id,
98
+ to_agent_id: resbody?.replaced_bot_root_id || (useSlug ? botSlug : botId) || '',
99
+ intent_name: this.context.reply?.attributes?.intent_info?.intent_name || null,
100
+ request_id: this.requestId || null
101
+ });
102
+ }
103
+ } catch (error) {
104
+ await subagentStack.pop(this.requestId);
105
+ winston.error("(DirCallSubAgent) error: ", error);
106
+ this.logger.error("(ReplaceBot) Invoke subagent error: ", error);
107
+ if (callback) {
108
+ callback(true);
109
+ }
110
+ return;
111
+ }
112
+
113
+ if (blockName) {
114
+ winston.debug("(DirCallSubAgent) Sending hidden /start message to bot in dept");
115
+ const message = {
116
+ type: "text",
117
+ text: "/" + blockName,
118
+ attributes: {
119
+ subtype: "info"
120
+ }
121
+ }
122
+ this.tdClient.sendSupportMessage(
123
+ this.requestId,
124
+ message, (err) => {
125
+ if (err) {
126
+ winston.debug("(DirCallSubAgent) Error sending hidden message: " + err.message);
127
+ }
128
+ callback(true);
129
+ });
130
+ }
131
+ else {
132
+ callback();
133
+ }
134
+ }
135
+
136
+ }
137
+
138
+ // The bot JWT is signed for the bot that is a participant of the request. After a publish
139
+ // that is the development bot, while chatbot.botId is the published copy running the flow.
140
+ function participantBotIdFromToken(token) {
141
+ if (!token || typeof token !== 'string') {
142
+ return null;
143
+ }
144
+ const raw = token.startsWith('JWT ') ? token.slice(4) : token;
145
+ const payload = jwt.decode(raw);
146
+ if (!payload || payload.sub !== 'bot' || !payload._id) {
147
+ return null;
148
+ }
149
+ return String(payload._id);
150
+ }
151
+
152
+ module.exports = { DirCallSubAgent };
@@ -0,0 +1,107 @@
1
+ const { TiledeskClient } = require("@tiledesk/tiledesk-client");
2
+ const { Logger } = require("../../Logger");
3
+ const { SubagentStack } = require("../SubagentStack");
4
+ const winston = require('../../utils/winston.js');
5
+ const requestService = require("../../services/RequestService.js");
6
+ const tilebotService = require("../../services/TilebotService.js");
7
+ const { v4: uuidv4 } = require('uuid');
8
+
9
+ class DirReturnStack {
10
+
11
+ constructor(context) {
12
+ if (!context) {
13
+ throw new Error('context object is mandatory');
14
+ }
15
+ this.context = context;
16
+ this.requestId = context.requestId;
17
+ this.API_ENDPOINT = context.API_ENDPOINT;
18
+
19
+ 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 });
20
+ this.tdClient = new TiledeskClient({ projectId: this.context.projectId, token: this.context.token, APIURL: this.API_ENDPOINT, APIKEY: "___" });
21
+ }
22
+
23
+ execute(directive, callback) {
24
+ winston.verbose("Execute ReturnStack directive");
25
+ let action;
26
+ if (directive.action) {
27
+ action = directive.action;
28
+ }
29
+ else {
30
+ this.logger.error("Incorrect action for ", directive.name, directive);
31
+ winston.warn("DirReturnStack Incorrect directive: ", directive);
32
+ callback();
33
+ return;
34
+ }
35
+ this.go(action, (stop) => {
36
+ this.logger.native("[Return Stack] Executed");
37
+ callback(stop);
38
+ })
39
+ }
40
+
41
+ async go(action, callback) {
42
+ winston.debug("(DirReturnStack) Action: ", action);
43
+ const subagentStack = new SubagentStack({ tdCache: this.context.tdcache });
44
+ const data = await subagentStack.pop(this.requestId);
45
+ if (!data?.parentId) {
46
+ this.logger.error("(ReturnStack) No parentId found");
47
+ callback(true);
48
+ return;
49
+ }
50
+ const parentParticipantId = data.parentParticipantId || data.parentId;
51
+ try {
52
+ winston.debug("(DirReturnStack) pop " + JSON.stringify({
53
+ requestId: this.requestId,
54
+ parentId: data.parentId,
55
+ parentParticipantId: parentParticipantId,
56
+ nextBlock: data.nextBlock && data.nextBlock.intentName
57
+ }));
58
+ await requestService.replaceBot(this.context.projectId, this.requestId, { id: parentParticipantId }, this.context.token);
59
+ } catch (error) {
60
+ winston.error("(DirReturnStack) error: ", error);
61
+ this.logger.error("(ReturnStack) Invoke subagent error: ", error);
62
+ callback(true);
63
+ return;
64
+ }
65
+
66
+ if (data.nextBlock?._tdActionType === "intent" && data.nextBlock?.intentName) {
67
+
68
+ let intent_command_request = {
69
+ "payload": {
70
+ "_id": uuidv4(),
71
+ "senderFullname": "_tdinternal",
72
+ "type": "text",
73
+ "sender": "_tdinternal",
74
+ "recipient": this.requestId,
75
+ "text": "/" + data.nextBlock.intentName,
76
+ "id_project": this.context.projectId,
77
+ "request": {
78
+ "request_id": this.requestId,
79
+ "id_project": this.context.projectId,
80
+ "draft": false
81
+ }
82
+ },
83
+ "token": data.parentToken
84
+ }
85
+
86
+ tilebotService.sendMessageToBot(
87
+ intent_command_request,
88
+ data.parentId,
89
+ (err) => {
90
+ if (err) {
91
+ winston.error("(DirReturnStack) error: ", err);
92
+ this.logger.error("(ReturnStack) Send message to bot error: ", err);
93
+ callback(true);
94
+ return;
95
+ }
96
+ callback(true);
97
+ }
98
+ );
99
+ return;
100
+ }
101
+
102
+
103
+ callback(true);
104
+ }
105
+ }
106
+
107
+ module.exports = { DirReturnStack };
@@ -33,6 +33,8 @@ class Directives {
33
33
  static CAPTURE_USER_REPLY = "capture_user_reply";
34
34
  static REPLACE_BOT_V2 = "replacebotv2";
35
35
  static REPLACE_BOT_V3 = "replacebotv3";
36
+ static CALL_SUBAGENT = "callsubagent";
37
+ static RETURN_STACK = "returnstack";
36
38
  static ITERATION = "iteration";
37
39
  /**** AI ****/
38
40
  static ASK_GPT = "askgpt";