@tiledesk/tiledesk-server 3.0.0 → 3.1.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 (138) hide show
  1. package/.circleci/config.yml +1 -1
  2. package/CHANGELOG.md +37 -0
  3. package/Dockerfile +3 -2
  4. package/Dockerfile-en +3 -2
  5. package/Dockerfile-jobs +3 -2
  6. package/Dockerfile-profiler +3 -2
  7. package/README.md +15 -0
  8. package/app.js +14 -1
  9. package/bin/quota-reset +68 -0
  10. package/bin/quota-restore +86 -0
  11. package/channels/chat21/chat21Handler.js +50 -34
  12. package/channels/chat21/chat21JoinTracker.js +43 -0
  13. package/config/database.js +5 -5
  14. package/config/native_mcp/native_mcp_servers.json +1 -0
  15. package/controllers/chatbot.controller.js +80 -27
  16. package/controllers/intents.controller.js +42 -0
  17. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-chat21-ionic.md +468 -0
  18. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-design-studio.md +1349 -0
  19. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md +1694 -0
  20. package/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-tybot.md +789 -0
  21. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-server.md +83 -0
  22. package/docs/superpowers/plans/2026-09-29-hitl-known-limits-tybot.md +76 -0
  23. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-chat21-ionic.md +97 -0
  24. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-design-studio.md +72 -0
  25. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-server.md +223 -0
  26. package/docs/superpowers/plans/2026-09-29-hitl-participant-removal-tybot.md +121 -0
  27. package/docs/superpowers/plans/2026-09-29-hitl-pre-branch-ports.md +65 -0
  28. package/docs/superpowers/plans/2026-09-30-flow-start-points-design-studio.md +88 -0
  29. package/docs/superpowers/plans/2026-09-30-flow-start-points-server.md +103 -0
  30. package/docs/superpowers/plans/2026-09-30-flow-start-points-tybot.md +43 -0
  31. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-design-studio.md +80 -0
  32. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-runtime.md +39 -0
  33. package/docs/superpowers/plans/2026-10-01-scheduled-start-point-server.md +106 -0
  34. package/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md +715 -0
  35. package/docs/superpowers/specs/2026-09-30-flow-start-points-design.md +156 -0
  36. package/docs/superpowers/specs/2026-10-01-scheduled-start-point-design.md +303 -0
  37. package/docs/superpowers/todo/2026-09-14-webhook-chatbot-shared-code-fixes.md +191 -0
  38. package/event/botEvent.js +12 -1
  39. package/event/emailEvent.js +3 -0
  40. package/event/messageEvent.js +44 -0
  41. package/jobs.js +10 -0
  42. package/jobsManager.js +19 -0
  43. package/middleware/errorHandler.js +6 -2
  44. package/models/agentPrompt.js +104 -0
  45. package/models/analyticResult.js +1 -1
  46. package/models/channelConstants.js +3 -2
  47. package/models/quotaUsage.js +71 -0
  48. package/models/request.js +6 -0
  49. package/models/requestSnapshot.js +12 -0
  50. package/models/routerLogger.js +1 -1
  51. package/models/webhook.js +44 -0
  52. package/package.json +7 -5
  53. package/pubmodules/emailNotification/requestNotification.js +14 -22
  54. package/pubmodules/events/test/eventRoute.js +7 -6
  55. package/pubmodules/rules/conciergeBot.js +9 -4
  56. package/routes/agentPrompts.js +132 -0
  57. package/routes/auth.js +1 -12
  58. package/routes/campaigns.js +0 -13
  59. package/routes/dataTable.js +0 -3
  60. package/routes/faq_kb.js +12 -1
  61. package/routes/messagesRoot.js +0 -1
  62. package/routes/quotes.js +38 -1
  63. package/routes/request.js +81 -5
  64. package/routes/users.js +0 -1
  65. package/routes/webhook.js +160 -8
  66. package/routes/webhooks.js +276 -6
  67. package/routes/widgetLoader.js +6 -3
  68. package/services/QuoteManager.js +77 -16
  69. package/services/aiService.js +1 -1
  70. package/services/chatbotService.js +55 -1
  71. package/services/departmentService.js +60 -43
  72. package/services/dolphinSchedulerClient.js +116 -0
  73. package/services/emailService.js +6 -1
  74. package/services/hitlParticipantListener.js +260 -0
  75. package/services/participantInviteService.js +302 -0
  76. package/services/participantRemoveService.js +79 -0
  77. package/services/quotaSnapshotService.js +1167 -0
  78. package/services/requestService.js +102 -144
  79. package/services/scheduledStart/dolphinBackend.js +246 -0
  80. package/services/scheduledStart/schedulerBackend.js +101 -0
  81. package/services/scheduledStart/schedulerServiceClient.js +41 -0
  82. package/services/scheduledStartPublishListener.js +186 -0
  83. package/services/scheduledStartRules.js +173 -0
  84. package/services/scheduledStartService.js +130 -0
  85. package/services/startPointCleanupListener.js +30 -0
  86. package/services/startPointService.js +158 -0
  87. package/services/testWsService.js +1 -4
  88. package/services/updateRequestSnapshotQueued.js +8 -9
  89. package/services/webhookConversationService.js +185 -0
  90. package/services/webhookSettingsValidator.js +61 -0
  91. package/template/email/checkpointReachedEmail.html +5 -0
  92. package/test/agentPromptsRoute.test.js +154 -0
  93. package/test/agentTokensQuota.js +237 -0
  94. package/test/botEventHitlFallback.js +19 -0
  95. package/test/chat21HandlerJoinWiring.js +59 -0
  96. package/test/dataTablesRoute.test.js +10 -2
  97. package/test/dateUtils.test.js +0 -3
  98. package/test/departmentService.js +8 -12
  99. package/test/{fileRoute.js → deprecated/_deprecated_fileRoute} +2 -2
  100. package/test/{kbsettingsRoute.js → deprecated/_deprecated_kbsettingsRoute} +3 -3
  101. package/test/faqRoute.js +6 -1
  102. package/test/faqkbRoute.js +14 -10
  103. package/test/faqkbV3Route.js +1 -1
  104. package/test/filepRoute.js +4 -50
  105. package/test/hitlParticipantListener.js +446 -0
  106. package/test/hitlQueueWiring.js +191 -0
  107. package/test/hitlWaitingReset.js +124 -0
  108. package/test/inviteParticipantsRoute.js +492 -0
  109. package/test/kbRoute.js +1 -1
  110. package/test/messageRoute.js +33 -21
  111. package/test/nativemcp.test.js +7 -1
  112. package/test/openaiRoute.js +2 -8
  113. package/test/publishFailLoud.test.js +414 -0
  114. package/test/quotaSnapshots.js +1044 -0
  115. package/test/removeParticipantsRoute.js +186 -0
  116. package/test/requestService.js +24 -16
  117. package/test/requestServiceRemoveParticipant.js +144 -0
  118. package/test/requestVisibility.test.js +186 -0
  119. package/test/scheduledStartFacade.js +184 -0
  120. package/test/scheduledStartHandover.js +95 -0
  121. package/test/scheduledStartPublish.js +320 -0
  122. package/test/scheduledStartRoute.js +163 -0
  123. package/test/scheduledStartRules.js +177 -0
  124. package/test/scheduledStartRun.js +299 -0
  125. package/test/scheduledStartSchedulerBackend.js +116 -0
  126. package/test/scheduledStartService.js +290 -0
  127. package/test/startPointsCleanup.js +69 -0
  128. package/test/startPointsRegression.js +169 -0
  129. package/test/startPointsRoute.js +158 -0
  130. package/test/webhookConversationRoute.js +347 -0
  131. package/test/webhookConversationService.js +261 -0
  132. package/test/webhookConversationTestUtils.js +55 -0
  133. package/utils/aiUtils.js +95 -1
  134. package/utils/intentFieldNames.js +192 -0
  135. package/utils/quotaCliUtil.js +43 -0
  136. package/utils/requestVisibility.js +355 -0
  137. package/websocket/webSocketServer.js +36 -31
  138. /package/test/{imageRoute.js → deprecated/_deprecated_imageRoute} +0 -0
@@ -0,0 +1,789 @@
1
+ # Webhook-started chatbot conversations + HITL — tybot (tiledesk-chatbot) Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Add the flow action `invite_human` that asks tiledesk-server to invite platform users into the current conversation (the bot stays), stores who was invited, and branches to "invited" / "no human available".
6
+
7
+ **Architecture:** A new directive `DirInviteHuman` (modelled on `DirIfOnlineAgentsV2`) resolves the `members` field against flow variables, calls `POST {API_ENDPOINT}/{projectId}/requests/{requestId}/participants/invite` with the bot token, sets `invited_humans` / `invited_humans_count`, and jumps with `DirIntent`. It does not wait: the next block (Reply V2 / Capture User Reply) waits for the human.
8
+
9
+ **Tech Stack:** Node.js, Express, mocha + assert, Redis (tdcache), liquidjs (`Filler`).
10
+
11
+ **Spec:** `tiledesk-server/docs/superpowers/specs/2026-09-15-webhook-chatbot-hitl-design.md` (section 6, 9.2). Server contract: `tiledesk-server/docs/superpowers/plans/2026-09-15-webhook-chatbot-hitl-server.md` Task 4.
12
+
13
+ ## Global Constraints
14
+
15
+ - Repo `tiledesk-chatbot`, branch `feature/webhook-chatbot-hitl` created from `origin/main` (`ce06bf8e`, 2.1.13). Code lives in `tybotRoute/`. Never commit to `main` / `main_pre`.
16
+ - Action type / directive name: exactly `invite_human`. Action fields: `departmentId?`, `members?` (string, comma/semicolon/newline separated, supports `{{variables}}`), `trueIntent`, `falseIntent`, `trueIntentAttributes?`, `falseIntentAttributes?`.
17
+ - Server call: `POST ${API_ENDPOINT}/${projectId}/requests/${requestId}/participants/invite`, header `Authorization: JWT <bot token>`, body `{ department_id, members: string[] }`; response `{ request_id, department_id, invited: [{ id_user, fullname, already_participant }], reason? }`.
18
+ - Flow variables set: `invited_humans` (array as returned), `invited_humans_count` (number). Error text in `flowError`: `(Invite human) requires a conversation` for `automation-request-…` ids, `(Invite human) An error occurred: <message>` for HTTP errors.
19
+ - Every jump ends with `callback(true)`. Do not copy the undefined `intentDirective` bug of `DirIfOnlineAgentsV2.js:140`.
20
+ - Server returns 422 for invites into conversations not started by a webhook (server Ruling 12); the
21
+ directive's HTTP-error path already sends the flow to `falseIntent` with `flowError`.
22
+ - Commit messages end with `Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>`.
23
+
24
+ ### How to run tests
25
+ Requires a local Redis. From `tybotRoute/`:
26
+
27
+ ```bash
28
+ cd /Users/nicocardone/Desktop/DEV/TILEDESK/tiledesk-chatbot/tybotRoute
29
+ API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
30
+ npx mocha <test file> --timeout 60000 --exit
31
+ ```
32
+ (`services/TilebotService.js` reads `TILEBOT_ENDPOINT` at module load; the conversation tests host tilebot on 10001 and a mock Tiledesk API on 10002, like `test/conversation-replyv2_button_match_test.js`.)
33
+
34
+ ---
35
+
36
+ ## File Structure
37
+
38
+ | File | Status | Responsibility |
39
+ |---|---|---|
40
+ | `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js` | Create | directive: members resolution, server call, variables, jumps |
41
+ | `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js` | Modify | `INVITE_HUMAN` constant |
42
+ | `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` | Modify | require + handlers map entry |
43
+ | `tybotRoute/test/invite_human_members_test.js` | Create | unit tests for members resolution |
44
+ | `tybotRoute/test/conversation-invite_human_bot.js` | Create | bot fixture |
45
+ | `tybotRoute/test/conversation-invite_human_test.js` | Create | conversation tests (mock API) |
46
+
47
+ ---
48
+
49
+ ### Task 1: Members resolution
50
+
51
+ **Files:**
52
+ - Create: `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js` (static helpers only in this task)
53
+ - Create: `tybotRoute/test/invite_human_members_test.js`
54
+
55
+ **Interfaces:**
56
+ - Produces:
57
+ - `DirInviteHuman.resolveMembers(rawMembers: string|Array|undefined, variables: Object, filler: {fill(text, params): string}): string[]` — ordered, trimmed, de-duplicated list.
58
+ - `DirInviteHuman.lookup(variables: Object, path: string): any` — dotted path lookup (`payload.oncall`).
59
+ - `DirInviteHuman.fixToken(token: string): string` — prefixes `JWT ` when missing.
60
+
61
+ - [ ] **Step 1: Create the feature branch**
62
+
63
+ ```bash
64
+ cd /Users/nicocardone/Desktop/DEV/TILEDESK/tiledesk-chatbot
65
+ git fetch origin
66
+ git switch -c feature/webhook-chatbot-hitl origin/main
67
+ git branch --unset-upstream
68
+ ```
69
+
70
+ - [ ] **Step 2: Write the failing tests**
71
+
72
+ Create `tybotRoute/test/invite_human_members_test.js`:
73
+
74
+ ```js
75
+ var assert = require('assert');
76
+ const { DirInviteHuman } = require('../tiledeskChatbotPlugs/directives/DirInviteHuman');
77
+ const { Filler } = require('../tiledeskChatbotPlugs/Filler');
78
+
79
+ describe('DirInviteHuman.resolveMembers', function () {
80
+
81
+ const filler = new Filler();
82
+
83
+ it('returns an empty list for empty values', () => {
84
+ assert.deepStrictEqual(DirInviteHuman.resolveMembers(undefined, {}, filler), []);
85
+ assert.deepStrictEqual(DirInviteHuman.resolveMembers(null, {}, filler), []);
86
+ assert.deepStrictEqual(DirInviteHuman.resolveMembers('', {}, filler), []);
87
+ assert.deepStrictEqual(DirInviteHuman.resolveMembers(' , ;\n ', {}, filler), []);
88
+ });
89
+
90
+ it('splits on comma, semicolon and newline, trims and removes duplicates', () => {
91
+ const members = DirInviteHuman.resolveMembers(' a@acme.it, b@acme.it;c@acme.it\nb@acme.it ', {}, filler);
92
+ assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'c@acme.it']);
93
+ });
94
+
95
+ it('expands a variable holding an array', () => {
96
+ const members = DirInviteHuman.resolveMembers('{{oncall}}, ops@acme.it', { oncall: ['a@acme.it', 'b@acme.it'] }, filler);
97
+ assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'ops@acme.it']);
98
+ });
99
+
100
+ it('expands a dotted variable path and a comma-separated string variable', () => {
101
+ const variables = { payload: { oncall: ['a@acme.it'] }, backup: 'b@acme.it, c@acme.it' };
102
+ const members = DirInviteHuman.resolveMembers('{{payload.oncall}};{{ backup }}', variables, filler);
103
+ assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'c@acme.it']);
104
+ });
105
+
106
+ it('expands a variable holding a JSON array string', () => {
107
+ const members = DirInviteHuman.resolveMembers('{{oncall}}', { oncall: '["a@acme.it","b@acme.it"]' }, filler);
108
+ assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it']);
109
+ });
110
+
111
+ it('fills placeholders embedded in text and drops unknown variables', () => {
112
+ const members = DirInviteHuman.resolveMembers('team-{{team}}@acme.it, {{unknown}}', { team: 'sre' }, filler);
113
+ assert.deepStrictEqual(members, ['team-sre@acme.it']);
114
+ });
115
+
116
+ it('accepts an array of members', () => {
117
+ const members = DirInviteHuman.resolveMembers(['a@acme.it', '{{oncall}}'], { oncall: 'b@acme.it' }, filler);
118
+ assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it']);
119
+ });
120
+ });
121
+
122
+ describe('DirInviteHuman.fixToken', function () {
123
+ it('prefixes JWT only when missing', () => {
124
+ assert.strictEqual(DirInviteHuman.fixToken('abc'), 'JWT abc');
125
+ assert.strictEqual(DirInviteHuman.fixToken('JWT abc'), 'JWT abc');
126
+ });
127
+ });
128
+ ```
129
+
130
+ - [ ] **Step 3: Run the tests to verify they fail**
131
+
132
+ Run (from `tybotRoute/`): `npx mocha test/invite_human_members_test.js --exit`
133
+ Expected: FAIL with `Cannot find module '../tiledeskChatbotPlugs/directives/DirInviteHuman'`.
134
+
135
+ - [ ] **Step 4: Implement the helpers**
136
+
137
+ Create `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`:
138
+
139
+ ```js
140
+ const SEPARATORS = /[,;\n]/;
141
+ const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
142
+
143
+ class DirInviteHuman {
144
+
145
+ constructor(context) {
146
+ if (!context) {
147
+ throw new Error('context object is mandatory.');
148
+ }
149
+ this.context = context;
150
+ }
151
+
152
+ /**
153
+ * Resolves the "members" field of the action into a list of ids/emails.
154
+ * A token that is exactly one {{variable}} is replaced by the raw variable value
155
+ * (arrays are expanded); other tokens containing {{...}} are rendered with the Filler.
156
+ */
157
+ static resolveMembers(rawMembers, variables, filler) {
158
+ const vars = variables || {};
159
+ const result = [];
160
+
161
+ const push = (value) => {
162
+ if (value === undefined || value === null) {
163
+ return;
164
+ }
165
+ if (Array.isArray(value)) {
166
+ value.forEach(push);
167
+ return;
168
+ }
169
+ if (typeof value === 'string') {
170
+ const trimmed = value.trim();
171
+ if (trimmed.startsWith('[')) {
172
+ try {
173
+ const parsed = JSON.parse(trimmed);
174
+ if (Array.isArray(parsed)) {
175
+ parsed.forEach(push);
176
+ return;
177
+ }
178
+ } catch (err) {
179
+ // not a JSON array: treat as plain text
180
+ }
181
+ }
182
+ trimmed.split(SEPARATORS).map((s) => s.trim()).filter((s) => s.length > 0).forEach((s) => {
183
+ if (!result.includes(s)) {
184
+ result.push(s);
185
+ }
186
+ });
187
+ return;
188
+ }
189
+ push(String(value));
190
+ };
191
+
192
+ if (rawMembers === undefined || rawMembers === null) {
193
+ return result;
194
+ }
195
+ const tokens = Array.isArray(rawMembers) ? rawMembers : String(rawMembers).split(SEPARATORS);
196
+ for (const token of tokens) {
197
+ if (typeof token !== 'string') {
198
+ push(token);
199
+ continue;
200
+ }
201
+ const trimmed = token.trim();
202
+ if (!trimmed) {
203
+ continue;
204
+ }
205
+ const placeholder = trimmed.match(SINGLE_PLACEHOLDER);
206
+ if (placeholder) {
207
+ push(DirInviteHuman.lookup(vars, placeholder[1]));
208
+ } else if (trimmed.includes('{{') && filler) {
209
+ push(filler.fill(trimmed, Object.assign({}, vars)));
210
+ } else {
211
+ push(trimmed);
212
+ }
213
+ }
214
+ return result;
215
+ }
216
+
217
+ static lookup(variables, path) {
218
+ return path.split('.').reduce((obj, key) => (obj !== undefined && obj !== null ? obj[key] : undefined), variables);
219
+ }
220
+
221
+ static fixToken(token) {
222
+ if (!token) {
223
+ return token;
224
+ }
225
+ return token.startsWith('JWT ') ? token : 'JWT ' + token;
226
+ }
227
+ }
228
+
229
+ module.exports = { DirInviteHuman };
230
+ ```
231
+
232
+ - [ ] **Step 5: Run the tests to verify they pass**
233
+
234
+ Run (from `tybotRoute/`): `npx mocha test/invite_human_members_test.js --exit`
235
+ Expected: PASS (8 passing).
236
+
237
+ - [ ] **Step 6: Commit**
238
+
239
+ ```bash
240
+ git add tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js tybotRoute/test/invite_human_members_test.js
241
+ git commit -m "feat(directives): resolve invite_human members from flow variables
242
+
243
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
244
+ ```
245
+
246
+ ---
247
+
248
+ ### Task 2: `invite_human` directive, registration and conversation tests
249
+
250
+ **Files:**
251
+ - Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`
252
+ - Modify: `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js` (after `static ADD_TAGS = 'add_tags'`)
253
+ - Modify: `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` (require after line 51 `DirIfOnlineAgentsV2`; handlers map `:250-314`)
254
+ - Create: `tybotRoute/test/conversation-invite_human_bot.js`
255
+ - Create: `tybotRoute/test/conversation-invite_human_test.js`
256
+
257
+ **Interfaces:**
258
+ - Consumes: `DirInviteHuman.resolveMembers`, `DirInviteHuman.fixToken` (Task 1); directive context fields from `DirectivesChatbotPlug.js:158-171` (`projectId`, `chatbot`, `token`, `supportRequest`, `reply`, `requestId`, `API_ENDPOINT`, `tdcache`); `DirIntent.intentDirectiveFor(intent, json_params)`; `httpUtils.request(options, callback)`; `TiledeskChatbot.allParametersStatic(tdcache, requestId)`; `chatbot.addParameter(name, value)`.
259
+ - Produces: `Directives.INVITE_HUMAN === 'invite_human'`; handler registered in `DirectivesChatbotPlug`.
260
+
261
+ - [ ] **Step 1: Create the bot fixture**
262
+
263
+ Create `tybotRoute/test/conversation-invite_human_bot.js`:
264
+
265
+ ```js
266
+ function replyV2(actionId, text, buttons) {
267
+ const message = { type: "text", text: text };
268
+ if (buttons) {
269
+ message.attributes = { attachment: { type: "template", buttons: buttons } };
270
+ }
271
+ return {
272
+ "_tdActionType": "replyv2",
273
+ "_tdActionId": actionId,
274
+ "attributes": {
275
+ "disableInputMessage": false,
276
+ "commands": [
277
+ { "type": "wait", "time": 10 },
278
+ { "type": "message", "message": message }
279
+ ]
280
+ }
281
+ };
282
+ }
283
+
284
+ const intents = [
285
+ {
286
+ "webhook_enabled": false, "enabled": true, "language": "en",
287
+ "intent_display_name": "defaultFallback", "intent_id": "fallback-id",
288
+ "actions": [replyV2("fallback-action", "fallback")]
289
+ },
290
+ {
291
+ "webhook_enabled": false, "enabled": true, "language": "en",
292
+ "intent_display_name": "invite", "intent_id": "invite-id",
293
+ "actions": [{
294
+ "_tdActionType": "invite_human",
295
+ "_tdActionId": "invite-action",
296
+ "departmentId": "dep-sre",
297
+ "members": "{{oncall}}, ops@acme.it",
298
+ "trueIntent": "#invited-id",
299
+ "falseIntent": "#noone-id"
300
+ }]
301
+ },
302
+ {
303
+ "webhook_enabled": false, "enabled": true, "language": "en",
304
+ "intent_display_name": "invited", "intent_id": "invited-id",
305
+ "actions": [replyV2("ask-approval", "invited {{invited_humans_count}}: restart?", [
306
+ { "uid": "b1", "type": "action", "value": "Approve", "link": "", "target": "blank", "action": "#approved-id", "attributes": "", "show_echo": true },
307
+ { "uid": "b2", "type": "action", "value": "Reject", "link": "", "target": "blank", "action": "#rejected-id", "attributes": "", "show_echo": true }
308
+ ])]
309
+ },
310
+ {
311
+ "webhook_enabled": false, "enabled": true, "language": "en",
312
+ "intent_display_name": "noone", "intent_id": "noone-id",
313
+ "actions": [replyV2("noone-action", "no human available")]
314
+ },
315
+ {
316
+ "webhook_enabled": false, "enabled": true, "language": "en",
317
+ "intent_display_name": "approved", "intent_id": "approved-id",
318
+ "actions": [replyV2("approved-action", "approved by {{lastUserMessage.sender}}")]
319
+ },
320
+ {
321
+ "webhook_enabled": false, "enabled": true, "language": "en",
322
+ "intent_display_name": "rejected", "intent_id": "rejected-id",
323
+ "actions": [replyV2("rejected-action", "rejected")]
324
+ }
325
+ ];
326
+
327
+ const bot = {
328
+ "webhook_enabled": false,
329
+ "language": "en",
330
+ "name": "Invite human",
331
+ "type": "tilebot"
332
+ };
333
+
334
+ let intents_dict_by_display_name = {};
335
+ for (let i = 0; i < intents.length; i++) {
336
+ intents_dict_by_display_name[intents[i].intent_display_name] = intents[i];
337
+ }
338
+ let intents_dict_by_intent_id = {};
339
+ for (let i = 0; i < intents.length; i++) {
340
+ intents_dict_by_intent_id[intents[i].intent_id] = intents[i];
341
+ }
342
+
343
+ bot.intents = intents_dict_by_display_name;
344
+ bot.intents_by_intent_id = intents_dict_by_intent_id;
345
+ bot.questions_intent = {};
346
+
347
+ const bots_data = { "bots": {} };
348
+ bots_data.bots["botID"] = bot;
349
+
350
+ module.exports = { bots_data: bots_data };
351
+ ```
352
+
353
+ - [ ] **Step 2: Write the failing conversation tests**
354
+
355
+ Create `tybotRoute/test/conversation-invite_human_test.js`:
356
+
357
+ ```js
358
+ var assert = require('assert');
359
+ const tybot = require("..");
360
+ const tybotRoute = tybot.router;
361
+ var express = require('express');
362
+ var app = express();
363
+ const winston = require('../utils/winston');
364
+ app.use("/", tybotRoute);
365
+ app.use((err, req, res, next) => {
366
+ winston.error("General error", err);
367
+ });
368
+ require('dotenv').config();
369
+ const bodyParser = require('body-parser');
370
+ const { v4: uuidv4 } = require('uuid');
371
+ const bots_data = require('./conversation-invite_human_bot.js').bots_data;
372
+ const tilebotService = require('../services/TilebotService');
373
+
374
+ const PROJECT_ID = "projectID";
375
+ const BOT_ID = "botID";
376
+ const CHATBOT_TOKEN = "XXX";
377
+ const SERVER_PORT = 10001;
378
+ const API_PORT = 10002;
379
+
380
+ function supportRequestId() {
381
+ return "support-group-" + PROJECT_ID + "-" + uuidv4().replace(/-/g, "");
382
+ }
383
+
384
+ function automationRequestId() {
385
+ return "automation-request-" + PROJECT_ID + "-" + uuidv4().replace(/-/g, "");
386
+ }
387
+
388
+ function userMessage(requestId, text, extra) {
389
+ return {
390
+ "payload": Object.assign({
391
+ "_id": uuidv4(),
392
+ "senderFullname": "guest#367e",
393
+ "type": "text",
394
+ "sender": "A-SENDER",
395
+ "recipient": requestId,
396
+ "text": text,
397
+ "id_project": PROJECT_ID,
398
+ "metadata": "",
399
+ "request": { "request_id": requestId }
400
+ }, extra || {}),
401
+ "token": CHATBOT_TOKEN
402
+ };
403
+ }
404
+
405
+ const ONCALL_PAYLOAD = { attributes: { payload: { oncall: ['a@acme.it', 'b@acme.it'] } } };
406
+
407
+ function replyText(message) {
408
+ const commands = message.attributes && message.attributes.commands;
409
+ const messageCommand = commands && commands.find((c) => c.type === "message");
410
+ return messageCommand ? messageCommand.message.text : message.text;
411
+ }
412
+
413
+ /** Starts the mock Tiledesk API; handlers receive (req, res, finish) where finish(err?) closes it and ends the test. */
414
+ function mockApi(done, handlers) {
415
+ const endpointServer = express();
416
+ endpointServer.use(bodyParser.json());
417
+ let listener;
418
+ const finish = (err) => listener.close(() => done(err));
419
+ endpointServer.post('/:projectId/requests/:requestId/participants/invite', (req, res) => {
420
+ try {
421
+ handlers.invite(req, res, finish);
422
+ } catch (err) {
423
+ res.status(500).send({});
424
+ finish(err);
425
+ }
426
+ });
427
+ endpointServer.post('/:projectId/requests/:requestId/messages', (req, res) => {
428
+ res.send({ success: true });
429
+ try {
430
+ handlers.message(replyText(req.body), finish);
431
+ } catch (err) {
432
+ finish(err);
433
+ }
434
+ });
435
+ return new Promise((resolve) => {
436
+ listener = endpointServer.listen(API_PORT, '0.0.0.0', () => resolve(listener));
437
+ });
438
+ }
439
+
440
+ describe('Conversation for Invite human test', async () => {
441
+
442
+ let app_listener;
443
+
444
+ before(() => {
445
+ return new Promise((resolve) => {
446
+ tybot.startApp({
447
+ bots: bots_data,
448
+ TILEBOT_ENDPOINT: process.env.TILEBOT_ENDPOINT,
449
+ API_ENDPOINT: process.env.API_ENDPOINT,
450
+ REDIS_HOST: process.env.REDIS_HOST,
451
+ REDIS_PORT: process.env.REDIS_PORT,
452
+ REDIS_PASSWORD: process.env.REDIS_PASSWORD
453
+ }, () => {
454
+ app_listener = app.listen(SERVER_PORT, () => resolve());
455
+ });
456
+ });
457
+ });
458
+
459
+ after(function (done) {
460
+ app_listener.close(() => done());
461
+ });
462
+
463
+ it('invites the resolved members and continues in the invited block', (done) => {
464
+ const REQUEST_ID = supportRequestId();
465
+ let inviteCalled = false;
466
+ mockApi(done, {
467
+ invite: (req, res) => {
468
+ inviteCalled = true;
469
+ assert.strictEqual(req.params.projectId, PROJECT_ID);
470
+ assert.strictEqual(req.params.requestId, REQUEST_ID);
471
+ assert.strictEqual(req.headers.authorization, 'JWT ' + CHATBOT_TOKEN);
472
+ assert.strictEqual(req.body.department_id, 'dep-sre');
473
+ assert.deepStrictEqual(req.body.members, ['a@acme.it', 'b@acme.it', 'ops@acme.it']);
474
+ res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [{ id_user: 'agent-1', fullname: 'Agent One', already_participant: false }] });
475
+ },
476
+ message: (text, finish) => {
477
+ assert.strictEqual(text, 'invited 1: restart?');
478
+ assert.strictEqual(inviteCalled, true);
479
+ finish();
480
+ }
481
+ }).then(() => {
482
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
483
+ });
484
+ });
485
+
486
+ it('goes to the "no human available" block when nobody is invited', (done) => {
487
+ const REQUEST_ID = supportRequestId();
488
+ mockApi(done, {
489
+ invite: (req, res) => {
490
+ res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [], reason: 'no_available_agents' });
491
+ },
492
+ message: (text, finish) => {
493
+ assert.strictEqual(text, 'no human available');
494
+ finish();
495
+ }
496
+ }).then(() => {
497
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
498
+ });
499
+ });
500
+
501
+ it('goes to the "no human available" block when the server fails', (done) => {
502
+ const REQUEST_ID = supportRequestId();
503
+ mockApi(done, {
504
+ invite: (req, res) => {
505
+ res.status(500).send({ success: false, error: 'boom' });
506
+ },
507
+ message: (text, finish) => {
508
+ assert.strictEqual(text, 'no human available');
509
+ finish();
510
+ }
511
+ }).then(() => {
512
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
513
+ });
514
+ });
515
+
516
+ it('does not call the server for automation runs', (done) => {
517
+ const REQUEST_ID = automationRequestId();
518
+ mockApi(done, {
519
+ invite: () => {
520
+ throw new Error('invite endpoint must not be called for automation runs');
521
+ },
522
+ message: (text, finish) => {
523
+ assert.strictEqual(text, 'no human available');
524
+ finish();
525
+ }
526
+ }).then(() => {
527
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
528
+ });
529
+ });
530
+
531
+ it('resumes with the human answer after the invite (HITL round trip)', (done) => {
532
+ const REQUEST_ID = supportRequestId();
533
+ mockApi(done, {
534
+ invite: (req, res) => {
535
+ res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [{ id_user: 'agent-1', fullname: 'Agent One', already_participant: false }] });
536
+ },
537
+ message: (text, finish) => {
538
+ if (text === 'invited 1: restart?') {
539
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, 'Approve', { sender: 'agent-1', senderFullname: 'Agent One' }), BOT_ID, () => {});
540
+ } else {
541
+ assert.strictEqual(text, 'approved by agent-1');
542
+ finish();
543
+ }
544
+ }
545
+ }).then(() => {
546
+ tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
547
+ });
548
+ });
549
+ });
550
+ ```
551
+
552
+ - [ ] **Step 3: Run the conversation tests to verify they fail**
553
+
554
+ Run (from `tybotRoute/`):
555
+ ```bash
556
+ API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
557
+ npx mocha test/conversation-invite_human_test.js --timeout 60000 --exit
558
+ ```
559
+ Expected: FAIL — tests time out (`Timeout of 60000ms exceeded`) because `invite_human` is not a registered directive (`DirectivesChatbotPlug.js:316-320` silently skips unknown directives).
560
+
561
+ - [ ] **Step 4: Implement the directive**
562
+
563
+ In `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`, replace the header and constructor:
564
+
565
+ ```js
566
+ const SEPARATORS = /[,;\n]/;
567
+ const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
568
+
569
+ class DirInviteHuman {
570
+
571
+ constructor(context) {
572
+ if (!context) {
573
+ throw new Error('context object is mandatory.');
574
+ }
575
+ this.context = context;
576
+ }
577
+ ```
578
+
579
+ with:
580
+
581
+ ```js
582
+ const { DirIntent } = require('./DirIntent');
583
+ const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
584
+ const { Filler } = require('../Filler');
585
+ const httpUtils = require('../../utils/HttpUtils');
586
+ const winston = require('../../utils/winston');
587
+ const { Logger } = require('../../Logger');
588
+
589
+ const SEPARATORS = /[,;\n]/;
590
+ const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
591
+ const AUTOMATION_PREFIX = 'automation-request-';
592
+
593
+ class DirInviteHuman {
594
+
595
+ constructor(context) {
596
+ if (!context) {
597
+ throw new Error('context object is mandatory.');
598
+ }
599
+ this.context = context;
600
+ this.chatbot = context.chatbot;
601
+ this.requestId = context.requestId;
602
+ this.projectId = context.projectId;
603
+ this.token = context.token;
604
+ this.tdcache = context.tdcache;
605
+ this.API_ENDPOINT = context.API_ENDPOINT;
606
+ this.intentDir = new DirIntent(context);
607
+ 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 });
608
+ }
609
+
610
+ execute(directive, callback) {
611
+ winston.verbose("Execute InviteHuman directive");
612
+ if (!directive || !directive.action) {
613
+ this.logger.error("[Invite Human] Incorrect action for ", directive?.name, directive);
614
+ winston.warn("(DirInviteHuman) Incorrect directive: ", directive);
615
+ callback();
616
+ return;
617
+ }
618
+ this.go(directive.action, (stop) => {
619
+ callback(stop);
620
+ });
621
+ }
622
+
623
+ async go(action, callback) {
624
+ const trueIntent = action.trueIntent;
625
+ const falseIntent = action.falseIntent;
626
+
627
+ if (!trueIntent && !falseIntent) {
628
+ this.logger.error("[Invite Human] missing both action.trueIntent & action.falseIntent");
629
+ winston.error("(DirInviteHuman) missing both action.trueIntent & action.falseIntent");
630
+ callback();
631
+ return;
632
+ }
633
+
634
+ if (this.requestId && this.requestId.startsWith(AUTOMATION_PREFIX)) {
635
+ this.logger.error("[Invite Human] requires a conversation");
636
+ await this.setParameter("flowError", "(Invite human) requires a conversation");
637
+ this.jump(falseIntent, action.falseIntentAttributes, callback);
638
+ return;
639
+ }
640
+
641
+ let members = [];
642
+ try {
643
+ const variables = this.tdcache ? await TiledeskChatbot.allParametersStatic(this.tdcache, this.requestId) : {};
644
+ members = DirInviteHuman.resolveMembers(action.members, variables, new Filler());
645
+ } catch (err) {
646
+ winston.error("(DirInviteHuman) error resolving members: ", err);
647
+ }
648
+
649
+ let result;
650
+ try {
651
+ result = await this.invite({ department_id: action.departmentId || undefined, members: members });
652
+ } catch (err) {
653
+ const message = (err && err.message) ? err.message : String(err);
654
+ this.logger.error("[Invite Human] Error: " + message);
655
+ winston.error("(DirInviteHuman) invite error: ", err);
656
+ await this.setParameter("flowError", "(Invite human) An error occurred: " + message);
657
+ this.jump(falseIntent, action.falseIntentAttributes, callback);
658
+ return;
659
+ }
660
+
661
+ const invited = (result && Array.isArray(result.invited)) ? result.invited : [];
662
+ await this.setParameter("invited_humans", invited);
663
+ await this.setParameter("invited_humans_count", invited.length);
664
+
665
+ if (invited.length > 0) {
666
+ this.logger.native("[Invite Human] Invited: " + invited.map((i) => i.fullname || i.id_user).join(', '));
667
+ this.jump(trueIntent, action.trueIntentAttributes, callback);
668
+ } else {
669
+ this.logger.native("[Invite Human] No human available");
670
+ this.jump(falseIntent, action.falseIntentAttributes, callback);
671
+ }
672
+ }
673
+
674
+ jump(intent, attributes, callback) {
675
+ if (!intent) {
676
+ callback();
677
+ return;
678
+ }
679
+ const intentDirective = DirIntent.intentDirectiveFor(intent, attributes);
680
+ this.intentDir.execute(intentDirective, () => {
681
+ callback(true);
682
+ });
683
+ }
684
+
685
+ async setParameter(name, value) {
686
+ try {
687
+ if (this.chatbot) {
688
+ await this.chatbot.addParameter(name, value);
689
+ } else if (this.tdcache) {
690
+ await TiledeskChatbot.addParameterStatic(this.tdcache, this.requestId, name, value);
691
+ }
692
+ } catch (err) {
693
+ winston.error("(DirInviteHuman) error setting parameter " + name, err);
694
+ }
695
+ }
696
+
697
+ invite(body) {
698
+ return new Promise((resolve, reject) => {
699
+ const HTTPREQUEST = {
700
+ url: `${this.API_ENDPOINT}/${this.projectId}/requests/${this.requestId}/participants/invite`,
701
+ headers: {
702
+ 'Content-Type': 'application/json',
703
+ 'Authorization': DirInviteHuman.fixToken(this.token)
704
+ },
705
+ json: body,
706
+ method: 'POST'
707
+ };
708
+ httpUtils.request(HTTPREQUEST, (err, resbody) => {
709
+ if (err) {
710
+ reject(err);
711
+ } else {
712
+ resolve(resbody);
713
+ }
714
+ });
715
+ });
716
+ }
717
+ ```
718
+
719
+ (The static `resolveMembers`, `lookup`, `fixToken` methods and `module.exports` from Task 1 stay below, unchanged.)
720
+
721
+ - [ ] **Step 5: Register the directive**
722
+
723
+ In `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js`, replace:
724
+
725
+ ```js
726
+ static ADD_TAGS = 'add_tags'
727
+ ```
728
+
729
+ with:
730
+
731
+ ```js
732
+ static ADD_TAGS = 'add_tags'
733
+ static INVITE_HUMAN = "invite_human";
734
+ ```
735
+
736
+ In `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js`, after:
737
+
738
+ ```js
739
+ const { DirIfOnlineAgentsV2 } = require('./directives/DirIfOnlineAgentsV2');
740
+ ```
741
+
742
+ add:
743
+
744
+ ```js
745
+ const { DirInviteHuman } = require('./directives/DirInviteHuman');
746
+ ```
747
+
748
+ and in the `handlers` map replace:
749
+
750
+ ```js
751
+ [Directives.DATA_TABLES]: DirDataTables,
752
+ };
753
+ ```
754
+
755
+ with:
756
+
757
+ ```js
758
+ [Directives.DATA_TABLES]: DirDataTables,
759
+ [Directives.INVITE_HUMAN]: DirInviteHuman,
760
+ };
761
+ ```
762
+
763
+ - [ ] **Step 6: Run the tests to verify they pass**
764
+
765
+ Run (from `tybotRoute/`):
766
+ ```bash
767
+ npx mocha test/invite_human_members_test.js --exit
768
+ API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
769
+ npx mocha test/conversation-invite_human_test.js --timeout 60000 --exit
770
+ ```
771
+ Expected: PASS (8 passing, then 5 passing).
772
+
773
+ - [ ] **Step 7: Run neighbouring suites for regressions**
774
+
775
+ Run (from `tybotRoute/`):
776
+ ```bash
777
+ API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
778
+ npx mocha test/conversation-replyv2_button_match_test.js test/conversation-replyv2_noinput_test.js test/conversation-capture_test.js --timeout 60000 --exit
779
+ ```
780
+ Expected: same results as on `origin/main` (run the same command on a clean checkout of `origin/main` if any failure appears).
781
+
782
+ - [ ] **Step 8: Commit**
783
+
784
+ ```bash
785
+ git add tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js tybotRoute/tiledeskChatbotPlugs/directives/Directives.js tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js tybotRoute/test/conversation-invite_human_bot.js tybotRoute/test/conversation-invite_human_test.js
786
+ git commit -m "feat(directives): add invite_human action to bring platform users into the conversation
787
+
788
+ Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
789
+ ```