@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.
- package/CHANGELOG.md +1 -52
- package/ExtUtil.js +1 -0
- package/TdCache copy.js +242 -0
- package/TiledeskExpression.js +1 -6
- package/TiledeskWhenExpression.js +1 -18
- package/engine/MongodbBotsDataSource.js +1 -3
- package/engine/MongodbIntentsMachine.js +2 -3
- package/engine/TiledeskChatbot.js +4 -76
- package/engine/TiledeskChatbotConst.js +1 -7
- package/engine/mock/MockBotsDataSource.js +6 -11
- package/index.js +36 -132
- package/models/faq_kb.js +0 -11
- package/package.json +1 -1
- package/services/AIController.js +1 -31
- package/services/AIService.js +33 -62
- package/services/IntegrationService.js +1 -4
- package/services/{LLMService.js → KbService.js} +3 -3
- package/services/RequestService.js +2 -23
- package/services/TilebotService.js +3 -19
- package/tiledeskChatbotPlugs/DirectivesChatbotPlug.js +17 -34
- package/tiledeskChatbotPlugs/directives/DirAiCondition.js +51 -18
- package/tiledeskChatbotPlugs/directives/DirAiPrompt.js +52 -103
- package/tiledeskChatbotPlugs/directives/DirAskGPTV2.js +5 -108
- package/tiledeskChatbotPlugs/directives/DirCallSubagent.js +8 -34
- package/tiledeskChatbotPlugs/directives/DirCaptureUserReply.js +11 -36
- package/tiledeskChatbotPlugs/directives/DirGptTask.js +4 -16
- package/tiledeskChatbotPlugs/directives/DirIntent.js +6 -12
- package/tiledeskChatbotPlugs/directives/DirIteration.js +10 -63
- package/tiledeskChatbotPlugs/directives/DirMoveToAgent.js +16 -69
- package/tiledeskChatbotPlugs/directives/DirRemoveCurrentBot.js +2 -40
- package/tiledeskChatbotPlugs/directives/DirReply.js +6 -81
- package/tiledeskChatbotPlugs/directives/DirReplyV2.js +4 -58
- package/tiledeskChatbotPlugs/directives/DirWebRequest.js +0 -8
- package/tiledeskChatbotPlugs/directives/DirWebRequestV2.js +1 -11
- package/tiledeskChatbotPlugs/directives/DirWebRequestV2_old.js +418 -0
- package/tiledeskChatbotPlugs/directives/DirWebResponse.js +2 -5
- package/tiledeskChatbotPlugs/directives/Directives.js +0 -6
- package/utils/HttpUtils.js +17 -99
- package/utils/TiledeskChatbotUtil.js +5 -73
- package/utils/winston.js +2 -80
- package/services/InternalSubAgentService.js +0 -330
- package/tiledeskChatbotPlugs/directives/DirInviteHuman.js +0 -259
- package/tiledeskChatbotPlugs/directives/DirInvokeSubAgent.js +0 -345
- package/tiledeskChatbotPlugs/directives/DirJSONConditionMulti.js +0 -171
- package/tiledeskChatbotPlugs/directives/DirRemoveHuman.js +0 -129
- package/tiledeskChatbotPlugs/directives/DirReturn.js +0 -98
- package/utils/ConnectorsV3.js +0 -292
- package/utils/LlmStream.js +0 -215
- package/utils/SentenceChunker.js +0 -94
- package/utils/StreamSender.js +0 -109
|
@@ -1,259 +0,0 @@
|
|
|
1
|
-
const { DirIntent } = require('./DirIntent');
|
|
2
|
-
const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
|
|
3
|
-
const { Filler } = require('../Filler');
|
|
4
|
-
const httpUtils = require('../../utils/HttpUtils');
|
|
5
|
-
const winston = require('../../utils/winston');
|
|
6
|
-
const { Logger } = require('../../Logger');
|
|
7
|
-
|
|
8
|
-
const SEPARATORS = /[,;\n]/;
|
|
9
|
-
const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
|
|
10
|
-
const AUTOMATION_PREFIX = 'automation-request-';
|
|
11
|
-
|
|
12
|
-
class DirInviteHuman {
|
|
13
|
-
|
|
14
|
-
static INVITE_TIMEOUT_MS = 30000;
|
|
15
|
-
static AUTOMATION_PREFIX = AUTOMATION_PREFIX;
|
|
16
|
-
|
|
17
|
-
constructor(context) {
|
|
18
|
-
if (!context) {
|
|
19
|
-
throw new Error('context object is mandatory.');
|
|
20
|
-
}
|
|
21
|
-
this.context = context;
|
|
22
|
-
this.chatbot = context.chatbot;
|
|
23
|
-
this.requestId = context.requestId;
|
|
24
|
-
this.projectId = context.projectId;
|
|
25
|
-
this.token = context.token;
|
|
26
|
-
this.tdcache = context.tdcache;
|
|
27
|
-
this.API_ENDPOINT = context.API_ENDPOINT;
|
|
28
|
-
this.intentDir = new DirIntent(context);
|
|
29
|
-
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 });
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
execute(directive, callback) {
|
|
33
|
-
winston.verbose("Execute InviteHuman directive");
|
|
34
|
-
let called = false;
|
|
35
|
-
const safeCallback = (stop) => {
|
|
36
|
-
if (called) {
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
called = true;
|
|
40
|
-
callback(stop);
|
|
41
|
-
};
|
|
42
|
-
if (!directive || !directive.action) {
|
|
43
|
-
this.logger.error("[Invite Human] Incorrect action for ", directive?.name, directive);
|
|
44
|
-
winston.warn("(DirInviteHuman) Incorrect directive: ", directive);
|
|
45
|
-
safeCallback();
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
this.go(directive.action, (stop) => {
|
|
49
|
-
safeCallback(stop);
|
|
50
|
-
}).catch((err) => {
|
|
51
|
-
winston.error("(DirInviteHuman) unexpected error: " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
52
|
-
safeCallback();
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
async go(action, callback) {
|
|
57
|
-
const trueIntent = action.trueIntent;
|
|
58
|
-
const falseIntent = action.falseIntent;
|
|
59
|
-
|
|
60
|
-
if (!trueIntent && !falseIntent) {
|
|
61
|
-
this.logger.error("[Invite Human] missing both action.trueIntent & action.falseIntent");
|
|
62
|
-
winston.error("(DirInviteHuman) missing both action.trueIntent & action.falseIntent");
|
|
63
|
-
callback();
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
if (this.requestId && this.requestId.startsWith(AUTOMATION_PREFIX)) {
|
|
68
|
-
this.logger.error("[Invite Human] requires a conversation");
|
|
69
|
-
await this.setParameter("flowError", "(Invite human) requires a conversation");
|
|
70
|
-
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
let members;
|
|
75
|
-
try {
|
|
76
|
-
const variables = this.tdcache ? await TiledeskChatbot.allParametersStatic(this.tdcache, this.requestId) : {};
|
|
77
|
-
members = DirInviteHuman.resolveMembers(action.members, variables, new Filler());
|
|
78
|
-
} catch (err) {
|
|
79
|
-
const summary = DirInviteHuman.errorSummary(err);
|
|
80
|
-
this.logger.error("[Invite Human] Error resolving members: " + summary.message);
|
|
81
|
-
winston.error("(DirInviteHuman) error resolving members: " + JSON.stringify(summary));
|
|
82
|
-
await this.setParameter("flowError", "(Invite human) An error occurred: " + summary.message);
|
|
83
|
-
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
let result;
|
|
88
|
-
try {
|
|
89
|
-
const inviteBody = { department_id: action.departmentId || undefined, members: members };
|
|
90
|
-
if (falseIntent && typeof falseIntent === 'string' && falseIntent.length > 0) {
|
|
91
|
-
inviteBody.fallback_intent = falseIntent;
|
|
92
|
-
}
|
|
93
|
-
result = await this.invite(inviteBody);
|
|
94
|
-
} catch (err) {
|
|
95
|
-
const summary = DirInviteHuman.errorSummary(err);
|
|
96
|
-
this.logger.error("[Invite Human] Error: " + summary.message);
|
|
97
|
-
winston.error("(DirInviteHuman) invite error: " + JSON.stringify(summary));
|
|
98
|
-
await this.setParameter("flowError", "(Invite human) An error occurred: " + summary.message);
|
|
99
|
-
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
100
|
-
return;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const invited = (result && Array.isArray(result.invited)) ? result.invited : [];
|
|
104
|
-
await this.setParameter("invited_humans", invited);
|
|
105
|
-
await this.setParameter("invited_humans_count", invited.length);
|
|
106
|
-
|
|
107
|
-
if (invited.length > 0) {
|
|
108
|
-
this.logger.native("[Invite Human] Invited: " + invited.map((i) => i.fullname || i.id_user).join(', '));
|
|
109
|
-
this.jump(trueIntent, action.trueIntentAttributes, callback);
|
|
110
|
-
} else {
|
|
111
|
-
this.logger.native("[Invite Human] No human available");
|
|
112
|
-
this.jump(falseIntent, action.falseIntentAttributes, callback);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
jump(intent, attributes, callback) {
|
|
117
|
-
if (!intent) {
|
|
118
|
-
callback();
|
|
119
|
-
return;
|
|
120
|
-
}
|
|
121
|
-
const intentDirective = DirIntent.intentDirectiveFor(intent, attributes);
|
|
122
|
-
this.intentDir.execute(intentDirective, () => {
|
|
123
|
-
callback(true);
|
|
124
|
-
});
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
async setParameter(name, value) {
|
|
128
|
-
try {
|
|
129
|
-
if (this.chatbot) {
|
|
130
|
-
await this.chatbot.addParameter(name, value);
|
|
131
|
-
} else if (this.tdcache) {
|
|
132
|
-
await TiledeskChatbot.addParameterStatic(this.tdcache, this.requestId, name, value);
|
|
133
|
-
}
|
|
134
|
-
} catch (err) {
|
|
135
|
-
winston.error("(DirInviteHuman) error setting parameter " + name + ": " + JSON.stringify(DirInviteHuman.errorSummary(err)));
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
invite(body) {
|
|
140
|
-
return new Promise((resolve, reject) => {
|
|
141
|
-
const HTTPREQUEST = {
|
|
142
|
-
url: `${this.API_ENDPOINT}/${this.projectId}/requests/${this.requestId}/participants/invite`,
|
|
143
|
-
headers: {
|
|
144
|
-
'Content-Type': 'application/json',
|
|
145
|
-
'Authorization': DirInviteHuman.fixToken(this.token)
|
|
146
|
-
},
|
|
147
|
-
json: body,
|
|
148
|
-
method: 'POST',
|
|
149
|
-
timeout: DirInviteHuman.INVITE_TIMEOUT_MS
|
|
150
|
-
};
|
|
151
|
-
httpUtils.request(HTTPREQUEST, (err, resbody) => {
|
|
152
|
-
if (err) {
|
|
153
|
-
reject(err);
|
|
154
|
-
} else {
|
|
155
|
-
resolve(resbody);
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Resolves the "members" field of the action into a list of ids/emails.
|
|
163
|
-
* A token that is exactly one {{variable}} is replaced by the raw variable value
|
|
164
|
-
* (arrays are expanded); other tokens containing {{...}} are rendered with the Filler.
|
|
165
|
-
*/
|
|
166
|
-
static resolveMembers(rawMembers, variables, filler) {
|
|
167
|
-
const vars = variables || {};
|
|
168
|
-
const result = [];
|
|
169
|
-
|
|
170
|
-
const push = (value) => {
|
|
171
|
-
if (value === undefined || value === null) {
|
|
172
|
-
return;
|
|
173
|
-
}
|
|
174
|
-
if (Array.isArray(value)) {
|
|
175
|
-
value.forEach(push);
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
if (typeof value === 'string') {
|
|
179
|
-
const trimmed = value.trim();
|
|
180
|
-
if (trimmed.startsWith('[')) {
|
|
181
|
-
try {
|
|
182
|
-
const parsed = JSON.parse(trimmed);
|
|
183
|
-
if (Array.isArray(parsed)) {
|
|
184
|
-
parsed.forEach(push);
|
|
185
|
-
return;
|
|
186
|
-
}
|
|
187
|
-
} catch (err) {
|
|
188
|
-
// not a JSON array: treat as plain text
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
trimmed.split(SEPARATORS).map((s) => s.trim()).filter((s) => s.length > 0).forEach((s) => {
|
|
192
|
-
if (!result.includes(s)) {
|
|
193
|
-
result.push(s);
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
push(String(value));
|
|
199
|
-
};
|
|
200
|
-
|
|
201
|
-
if (rawMembers === undefined || rawMembers === null) {
|
|
202
|
-
return result;
|
|
203
|
-
}
|
|
204
|
-
const tokens = Array.isArray(rawMembers) ? rawMembers : String(rawMembers).split(SEPARATORS);
|
|
205
|
-
for (const token of tokens) {
|
|
206
|
-
if (typeof token !== 'string') {
|
|
207
|
-
push(token);
|
|
208
|
-
continue;
|
|
209
|
-
}
|
|
210
|
-
const trimmed = token.trim();
|
|
211
|
-
if (!trimmed) {
|
|
212
|
-
continue;
|
|
213
|
-
}
|
|
214
|
-
const placeholder = trimmed.match(SINGLE_PLACEHOLDER);
|
|
215
|
-
if (placeholder) {
|
|
216
|
-
push(DirInviteHuman.lookup(vars, placeholder[1]));
|
|
217
|
-
} else if (trimmed.includes('{{') && filler) {
|
|
218
|
-
push(filler.fill(trimmed, Object.assign({}, vars)));
|
|
219
|
-
} else {
|
|
220
|
-
push(trimmed);
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
return result;
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
static lookup(variables, path) {
|
|
227
|
-
return path.split('.').reduce((obj, key) => (obj !== undefined && obj !== null ? obj[key] : undefined), variables);
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
static fixToken(token) {
|
|
231
|
-
if (!token) {
|
|
232
|
-
return token;
|
|
233
|
-
}
|
|
234
|
-
return token.startsWith('JWT ') ? token : 'JWT ' + token;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* Reduces an axios-like error to a plain, log-safe summary.
|
|
239
|
-
* Never reads err.config, err.request or headers (they may carry the bot JWT).
|
|
240
|
-
*/
|
|
241
|
-
static errorSummary(err) {
|
|
242
|
-
const responseData = (err && err.response) ? err.response.data : undefined;
|
|
243
|
-
let message;
|
|
244
|
-
if (responseData && typeof responseData.error === 'string' && responseData.error.length > 0) {
|
|
245
|
-
message = responseData.error;
|
|
246
|
-
} else if (err && err.message) {
|
|
247
|
-
message = err.message;
|
|
248
|
-
} else {
|
|
249
|
-
message = String(err);
|
|
250
|
-
}
|
|
251
|
-
return {
|
|
252
|
-
message: message,
|
|
253
|
-
status: (err && err.response) ? err.response.status : undefined,
|
|
254
|
-
data: responseData
|
|
255
|
-
};
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
module.exports = { DirInviteHuman };
|
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
const tilebotService = require('../../services/TilebotService');
|
|
2
|
-
const { InternalSubAgentService, INTERNAL_SUB_AGENT_STATUS } = require('../../services/InternalSubAgentService');
|
|
3
|
-
const { TiledeskChatbotConst } = require('../../engine/TiledeskChatbotConst');
|
|
4
|
-
const { Logger } = require('../../Logger');
|
|
5
|
-
const winston = require('../../utils/winston');
|
|
6
|
-
|
|
7
|
-
class DirInvokeSubAgent {
|
|
8
|
-
|
|
9
|
-
constructor(context) {
|
|
10
|
-
if (!context) {
|
|
11
|
-
throw new Error('context object is mandatory.');
|
|
12
|
-
}
|
|
13
|
-
this.context = context;
|
|
14
|
-
this.chatbot = context.chatbot;
|
|
15
|
-
this.tdcache = context.tdcache;
|
|
16
|
-
this.requestId = context.requestId;
|
|
17
|
-
this.projectId = context.projectId;
|
|
18
|
-
this.logger = new Logger({ request_id: this.requestId, dev: this.context.supportRequest?.draft, intent_id: this.context.reply?.attributes?.intent_info?.intent_id });
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
execute(directive, callback) {
|
|
22
|
-
const action = directive.action;
|
|
23
|
-
if (!action) {
|
|
24
|
-
this.logger.error('[Invoke Sub-Agent] Incorrect action for ', directive.name, directive);
|
|
25
|
-
callback();
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
this.go(action, callback);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async go(action, callback) {
|
|
33
|
-
if (!this.tdcache) {
|
|
34
|
-
this.logger.error('[Invoke Sub-Agent] tdcache is mandatory');
|
|
35
|
-
callback();
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
if (!this.chatbot || !this.chatbot.botsDataSource) {
|
|
40
|
-
await this.#assignImmediateFailure(action, 'botsDataSource is mandatory');
|
|
41
|
-
callback();
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
const subagentId = action.subagent_id || action.agentKey || action.agent || action.key;
|
|
46
|
-
if (!subagentId) {
|
|
47
|
-
await this.#assignImmediateFailure(action, 'subagent_id is mandatory');
|
|
48
|
-
callback();
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
let subBot;
|
|
53
|
-
try {
|
|
54
|
-
subBot = await this.chatbot.botsDataSource.getBotByIdCache(subagentId, this.tdcache);
|
|
55
|
-
} catch (error) {
|
|
56
|
-
winston.error('(DirInvokeSubAgent) Error loading sub-agent bot: ', error);
|
|
57
|
-
await this.#assignImmediateFailure(action, error && error.message ? error.message : error);
|
|
58
|
-
callback();
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (!subBot) {
|
|
63
|
-
await this.#assignImmediateFailure(action, `Sub-agent bot not found: ${subagentId}`);
|
|
64
|
-
callback();
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const command = InternalSubAgentService.intentCommand(action.intentName);
|
|
69
|
-
if (!command) {
|
|
70
|
-
await this.#assignImmediateFailure(action, `Sub-agent intentName is required for: ${subagentId}`);
|
|
71
|
-
callback();
|
|
72
|
-
return;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const agent = InternalSubAgentService.agentFromSubBot(subBot, subagentId);
|
|
76
|
-
const mode = this.#resolveMode(action);
|
|
77
|
-
const waitForReturn = mode === 'wait_result';
|
|
78
|
-
const requestAttributes = await InternalSubAgentService.allParameters(this.tdcache, this.requestId);
|
|
79
|
-
const rawInput = action.input || action.payload || {};
|
|
80
|
-
const input = InternalSubAgentService.fillValue(rawInput, requestAttributes);
|
|
81
|
-
|
|
82
|
-
let run;
|
|
83
|
-
try {
|
|
84
|
-
run = await InternalSubAgentService.createRun(this.tdcache, {
|
|
85
|
-
projectId: this.projectId,
|
|
86
|
-
parentRequestId: this.requestId,
|
|
87
|
-
parentBotId: this.chatbot.botId,
|
|
88
|
-
subagentId: subagentId,
|
|
89
|
-
agent: agent,
|
|
90
|
-
action: action,
|
|
91
|
-
mode: mode,
|
|
92
|
-
input: input
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
await this.#assignRun(action, run);
|
|
96
|
-
|
|
97
|
-
if (waitForReturn) {
|
|
98
|
-
await this.#subscribeForReturn(action, run);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
const message = InternalSubAgentService.buildSubAgentMessage(this.context, run, command);
|
|
102
|
-
|
|
103
|
-
this.#dispatchToBot(message, subagentId, action, async (err) => {
|
|
104
|
-
if (err) {
|
|
105
|
-
await this.#failRun(run, action, err);
|
|
106
|
-
}
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
this.logger.native(`[Invoke Sub-Agent] Started ${subagentId} run ${run.runId} (${mode})`);
|
|
110
|
-
callback(waitForReturn);
|
|
111
|
-
} catch (error) {
|
|
112
|
-
winston.error('(DirInvokeSubAgent) Error invoking sub-agent: ', error);
|
|
113
|
-
await this.#assignImmediateFailure(action, error && error.message ? error.message : error);
|
|
114
|
-
callback();
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
#resolveMode(action) {
|
|
119
|
-
if (action.mode === 'wait_result' || action.mode === 'fire_and_continue') {
|
|
120
|
-
return action.mode;
|
|
121
|
-
}
|
|
122
|
-
// Legacy aliases (awaitWebhookPublish / waitForResult)
|
|
123
|
-
if (action.awaitWebhookPublish === true || action.waitForResult === true) {
|
|
124
|
-
return 'wait_result';
|
|
125
|
-
}
|
|
126
|
-
return 'fire_and_continue';
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async #assignRun(action, run) {
|
|
130
|
-
if (action.assignRunIdTo) {
|
|
131
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignRunIdTo, run.runId);
|
|
132
|
-
}
|
|
133
|
-
if (action.assignSubRequestIdTo) {
|
|
134
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignSubRequestIdTo, run.subRequestId);
|
|
135
|
-
}
|
|
136
|
-
if (action.assignStatusTo) {
|
|
137
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignStatusTo, run.status);
|
|
138
|
-
}
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
async #assignImmediateFailure(action, error) {
|
|
142
|
-
if (action.assignStatusTo) {
|
|
143
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignStatusTo, INTERNAL_SUB_AGENT_STATUS.FAILED);
|
|
144
|
-
}
|
|
145
|
-
if (action.assignErrorTo) {
|
|
146
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignErrorTo, error);
|
|
147
|
-
}
|
|
148
|
-
this.logger.error('[Invoke Sub-Agent] ', error);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* Waits for DirReturn on the subagent request (same Redis pub/sub + ready key as DirWebResponse).
|
|
153
|
-
*/
|
|
154
|
-
async #subscribeForReturn(action, run) {
|
|
155
|
-
const topic = InternalSubAgentService.webhookTopic(run.subRequestId);
|
|
156
|
-
const readyKey = TiledeskChatbotConst.redisWebhookReadyKey(run.subRequestId);
|
|
157
|
-
let handled = false;
|
|
158
|
-
|
|
159
|
-
const onReturnPayload = async (returnMessage, source) => {
|
|
160
|
-
if (handled) {
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
handled = true;
|
|
164
|
-
|
|
165
|
-
winston.verbose(`(DirInvokeSubAgent) Sub-agent return received via ${source} on ${topic}`);
|
|
166
|
-
|
|
167
|
-
try {
|
|
168
|
-
await this.tdcache.unsubscribe(topic);
|
|
169
|
-
} catch (e) {
|
|
170
|
-
winston.warn('(DirInvokeSubAgent) unsubscribe after return:', e);
|
|
171
|
-
}
|
|
172
|
-
await this.tdcache.del(readyKey).catch(() => {});
|
|
173
|
-
|
|
174
|
-
const httpStatus = returnMessage.status !== undefined ? returnMessage.status : 200;
|
|
175
|
-
const success = InternalSubAgentService.isWebhookSuccess(httpStatus);
|
|
176
|
-
const terminalStatus = success ? INTERNAL_SUB_AGENT_STATUS.COMPLETED : INTERNAL_SUB_AGENT_STATUS.FAILED;
|
|
177
|
-
const output = returnMessage.payload;
|
|
178
|
-
const error = success ? null : {
|
|
179
|
-
message: 'Sub-agent return returned error status',
|
|
180
|
-
status: httpStatus,
|
|
181
|
-
payload: output
|
|
182
|
-
};
|
|
183
|
-
|
|
184
|
-
const updatedRun = await InternalSubAgentService.updateRun(
|
|
185
|
-
this.tdcache,
|
|
186
|
-
run.parentRequestId,
|
|
187
|
-
run.runId,
|
|
188
|
-
{
|
|
189
|
-
status: terminalStatus,
|
|
190
|
-
output: output,
|
|
191
|
-
error: error
|
|
192
|
-
}
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
if (!updatedRun) {
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
const event = {
|
|
200
|
-
status: terminalStatus,
|
|
201
|
-
output: output,
|
|
202
|
-
error: error,
|
|
203
|
-
parentRequestId: run.parentRequestId,
|
|
204
|
-
subRequestId: run.subRequestId,
|
|
205
|
-
runId: run.runId
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
await InternalSubAgentService.assignParentResult(this.tdcache, this.requestId, action, event);
|
|
209
|
-
await this.#continueParent(action, event, success);
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
const listener = async (message) => {
|
|
213
|
-
let returnMessage;
|
|
214
|
-
try {
|
|
215
|
-
returnMessage = JSON.parse(message);
|
|
216
|
-
} catch (error) {
|
|
217
|
-
winston.error('(DirInvokeSubAgent) Error parsing return message: ', error);
|
|
218
|
-
await onReturnPayload({ status: 500, payload: null }, 'pubsub-parse-error');
|
|
219
|
-
return;
|
|
220
|
-
}
|
|
221
|
-
await onReturnPayload(returnMessage, 'pubsub');
|
|
222
|
-
};
|
|
223
|
-
|
|
224
|
-
winston.verbose(`(DirInvokeSubAgent) Subscribing for return on ${topic} (parent ${run.parentRequestId})`);
|
|
225
|
-
await this.tdcache.subscribe(topic, listener);
|
|
226
|
-
|
|
227
|
-
const pollIv = setInterval(async () => {
|
|
228
|
-
if (handled) {
|
|
229
|
-
clearInterval(pollIv);
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
try {
|
|
233
|
-
const raw = await this.tdcache.get(readyKey);
|
|
234
|
-
if (!raw) {
|
|
235
|
-
return;
|
|
236
|
-
}
|
|
237
|
-
let returnMessage;
|
|
238
|
-
try {
|
|
239
|
-
returnMessage = JSON.parse(raw);
|
|
240
|
-
} catch (error) {
|
|
241
|
-
winston.error('(DirInvokeSubAgent) Error parsing return ready key: ', error);
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
clearInterval(pollIv);
|
|
245
|
-
await onReturnPayload(returnMessage, 'redis-key');
|
|
246
|
-
} catch (error) {
|
|
247
|
-
winston.warn('(DirInvokeSubAgent) return ready key poll:', error);
|
|
248
|
-
}
|
|
249
|
-
}, 25);
|
|
250
|
-
|
|
251
|
-
this.#scheduleTimeout(action, run, () => {
|
|
252
|
-
clearInterval(pollIv);
|
|
253
|
-
});
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
#dispatchToBot(message, botId, action, callback) {
|
|
257
|
-
const useExt = action.useExt === true || action.dispatchViaExt === true;
|
|
258
|
-
if (useExt) {
|
|
259
|
-
tilebotService.sendMessageToBot(message, botId, callback);
|
|
260
|
-
return;
|
|
261
|
-
}
|
|
262
|
-
tilebotService.executeBlock(message, botId, callback);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
#scheduleTimeout(action, run, onTimeout) {
|
|
266
|
-
setTimeout(async () => {
|
|
267
|
-
const currentRun = await InternalSubAgentService.getRun(this.tdcache, run.parentRequestId, run.runId);
|
|
268
|
-
if (!currentRun || InternalSubAgentService.isTerminalStatus(currentRun.status)) {
|
|
269
|
-
if (onTimeout) {
|
|
270
|
-
onTimeout();
|
|
271
|
-
}
|
|
272
|
-
return;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const timeoutRun = await InternalSubAgentService.updateRun(
|
|
276
|
-
this.tdcache,
|
|
277
|
-
run.parentRequestId,
|
|
278
|
-
run.runId,
|
|
279
|
-
{
|
|
280
|
-
status: INTERNAL_SUB_AGENT_STATUS.TIMEOUT,
|
|
281
|
-
error: {
|
|
282
|
-
message: `Internal sub-agent timeout after ${run.timeoutMs} ms`
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
);
|
|
286
|
-
|
|
287
|
-
if (timeoutRun && this.#resolveMode(action) === 'wait_result') {
|
|
288
|
-
const event = {
|
|
289
|
-
status: INTERNAL_SUB_AGENT_STATUS.TIMEOUT,
|
|
290
|
-
error: timeoutRun.error,
|
|
291
|
-
parentRequestId: run.parentRequestId,
|
|
292
|
-
subRequestId: run.subRequestId,
|
|
293
|
-
runId: run.runId
|
|
294
|
-
};
|
|
295
|
-
await InternalSubAgentService.assignParentResult(this.tdcache, this.requestId, action, event);
|
|
296
|
-
await this.#continueParent(action, event, false);
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
if (onTimeout) {
|
|
300
|
-
onTimeout();
|
|
301
|
-
}
|
|
302
|
-
}, run.timeoutMs);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
async #continueParent(action, event, success) {
|
|
306
|
-
const intentName = success
|
|
307
|
-
? (action.trueIntent || action.onCompletedIntent || action.onCompleteIntent || action.thenIntent)
|
|
308
|
-
: (action.falseIntent || action.onFailedIntent || action.onTimeoutIntent);
|
|
309
|
-
|
|
310
|
-
if (!intentName) {
|
|
311
|
-
winston.warn('(DirInvokeSubAgent) No parent continuation intent configured on invoke_subagent action');
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
const message = InternalSubAgentService.buildParentContinuationMessage(this.context, intentName, event);
|
|
316
|
-
winston.verbose(`(DirInvokeSubAgent) Continuing parent ${event.parentRequestId} -> ${intentName}`);
|
|
317
|
-
this.#dispatchToBot(message, this.chatbot.botId, action, (err) => {
|
|
318
|
-
if (err) {
|
|
319
|
-
winston.error('(DirInvokeSubAgent) Parent continuation failed: ', err);
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
winston.debug('(DirInvokeSubAgent) Parent continuation dispatched');
|
|
323
|
-
});
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
async #failRun(run, action, error) {
|
|
327
|
-
const failedRun = await InternalSubAgentService.updateRun(
|
|
328
|
-
this.tdcache,
|
|
329
|
-
run.parentRequestId,
|
|
330
|
-
run.runId,
|
|
331
|
-
{
|
|
332
|
-
status: INTERNAL_SUB_AGENT_STATUS.FAILED,
|
|
333
|
-
error: {
|
|
334
|
-
message: error && error.message ? error.message : error
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
);
|
|
338
|
-
|
|
339
|
-
if (failedRun && this.#resolveMode(action) !== 'wait_result' && action.assignErrorTo) {
|
|
340
|
-
await InternalSubAgentService.addParameter(this.tdcache, this.requestId, action.assignErrorTo, failedRun.error);
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
module.exports = { DirInvokeSubAgent };
|