# Webhook-started chatbot conversations + HITL — tybot (tiledesk-chatbot) Implementation Plan

> **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.

**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".

**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.

**Tech Stack:** Node.js, Express, mocha + assert, Redis (tdcache), liquidjs (`Filler`).

**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.

## Global Constraints

- 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`.
- Action type / directive name: exactly `invite_human`. Action fields: `departmentId?`, `members?` (string, comma/semicolon/newline separated, supports `{{variables}}`), `trueIntent`, `falseIntent`, `trueIntentAttributes?`, `falseIntentAttributes?`.
- 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? }`.
- 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.
- Every jump ends with `callback(true)`. Do not copy the undefined `intentDirective` bug of `DirIfOnlineAgentsV2.js:140`.
- Server returns 422 for invites into conversations not started by a webhook (server Ruling 12); the
  directive's HTTP-error path already sends the flow to `falseIntent` with `flowError`.
- Commit messages end with `Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>`.

### How to run tests
Requires a local Redis. From `tybotRoute/`:

```bash
cd /Users/nicocardone/Desktop/DEV/TILEDESK/tiledesk-chatbot/tybotRoute
API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
  npx mocha <test file> --timeout 60000 --exit
```
(`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`.)

---

## File Structure

| File | Status | Responsibility |
|---|---|---|
| `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js` | Create | directive: members resolution, server call, variables, jumps |
| `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js` | Modify | `INVITE_HUMAN` constant |
| `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` | Modify | require + handlers map entry |
| `tybotRoute/test/invite_human_members_test.js` | Create | unit tests for members resolution |
| `tybotRoute/test/conversation-invite_human_bot.js` | Create | bot fixture |
| `tybotRoute/test/conversation-invite_human_test.js` | Create | conversation tests (mock API) |

---

### Task 1: Members resolution

**Files:**
- Create: `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js` (static helpers only in this task)
- Create: `tybotRoute/test/invite_human_members_test.js`

**Interfaces:**
- Produces:
  - `DirInviteHuman.resolveMembers(rawMembers: string|Array|undefined, variables: Object, filler: {fill(text, params): string}): string[]` — ordered, trimmed, de-duplicated list.
  - `DirInviteHuman.lookup(variables: Object, path: string): any` — dotted path lookup (`payload.oncall`).
  - `DirInviteHuman.fixToken(token: string): string` — prefixes `JWT ` when missing.

- [ ] **Step 1: Create the feature branch**

```bash
cd /Users/nicocardone/Desktop/DEV/TILEDESK/tiledesk-chatbot
git fetch origin
git switch -c feature/webhook-chatbot-hitl origin/main
git branch --unset-upstream
```

- [ ] **Step 2: Write the failing tests**

Create `tybotRoute/test/invite_human_members_test.js`:

```js
var assert = require('assert');
const { DirInviteHuman } = require('../tiledeskChatbotPlugs/directives/DirInviteHuman');
const { Filler } = require('../tiledeskChatbotPlugs/Filler');

describe('DirInviteHuman.resolveMembers', function () {

  const filler = new Filler();

  it('returns an empty list for empty values', () => {
    assert.deepStrictEqual(DirInviteHuman.resolveMembers(undefined, {}, filler), []);
    assert.deepStrictEqual(DirInviteHuman.resolveMembers(null, {}, filler), []);
    assert.deepStrictEqual(DirInviteHuman.resolveMembers('', {}, filler), []);
    assert.deepStrictEqual(DirInviteHuman.resolveMembers('  , ;\n ', {}, filler), []);
  });

  it('splits on comma, semicolon and newline, trims and removes duplicates', () => {
    const members = DirInviteHuman.resolveMembers(' a@acme.it, b@acme.it;c@acme.it\nb@acme.it ', {}, filler);
    assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'c@acme.it']);
  });

  it('expands a variable holding an array', () => {
    const members = DirInviteHuman.resolveMembers('{{oncall}}, ops@acme.it', { oncall: ['a@acme.it', 'b@acme.it'] }, filler);
    assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'ops@acme.it']);
  });

  it('expands a dotted variable path and a comma-separated string variable', () => {
    const variables = { payload: { oncall: ['a@acme.it'] }, backup: 'b@acme.it, c@acme.it' };
    const members = DirInviteHuman.resolveMembers('{{payload.oncall}};{{ backup }}', variables, filler);
    assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it', 'c@acme.it']);
  });

  it('expands a variable holding a JSON array string', () => {
    const members = DirInviteHuman.resolveMembers('{{oncall}}', { oncall: '["a@acme.it","b@acme.it"]' }, filler);
    assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it']);
  });

  it('fills placeholders embedded in text and drops unknown variables', () => {
    const members = DirInviteHuman.resolveMembers('team-{{team}}@acme.it, {{unknown}}', { team: 'sre' }, filler);
    assert.deepStrictEqual(members, ['team-sre@acme.it']);
  });

  it('accepts an array of members', () => {
    const members = DirInviteHuman.resolveMembers(['a@acme.it', '{{oncall}}'], { oncall: 'b@acme.it' }, filler);
    assert.deepStrictEqual(members, ['a@acme.it', 'b@acme.it']);
  });
});

describe('DirInviteHuman.fixToken', function () {
  it('prefixes JWT only when missing', () => {
    assert.strictEqual(DirInviteHuman.fixToken('abc'), 'JWT abc');
    assert.strictEqual(DirInviteHuman.fixToken('JWT abc'), 'JWT abc');
  });
});
```

- [ ] **Step 3: Run the tests to verify they fail**

Run (from `tybotRoute/`): `npx mocha test/invite_human_members_test.js --exit`
Expected: FAIL with `Cannot find module '../tiledeskChatbotPlugs/directives/DirInviteHuman'`.

- [ ] **Step 4: Implement the helpers**

Create `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`:

```js
const SEPARATORS = /[,;\n]/;
const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;

class DirInviteHuman {

  constructor(context) {
    if (!context) {
      throw new Error('context object is mandatory.');
    }
    this.context = context;
  }

  /**
   * Resolves the "members" field of the action into a list of ids/emails.
   * A token that is exactly one {{variable}} is replaced by the raw variable value
   * (arrays are expanded); other tokens containing {{...}} are rendered with the Filler.
   */
  static resolveMembers(rawMembers, variables, filler) {
    const vars = variables || {};
    const result = [];

    const push = (value) => {
      if (value === undefined || value === null) {
        return;
      }
      if (Array.isArray(value)) {
        value.forEach(push);
        return;
      }
      if (typeof value === 'string') {
        const trimmed = value.trim();
        if (trimmed.startsWith('[')) {
          try {
            const parsed = JSON.parse(trimmed);
            if (Array.isArray(parsed)) {
              parsed.forEach(push);
              return;
            }
          } catch (err) {
            // not a JSON array: treat as plain text
          }
        }
        trimmed.split(SEPARATORS).map((s) => s.trim()).filter((s) => s.length > 0).forEach((s) => {
          if (!result.includes(s)) {
            result.push(s);
          }
        });
        return;
      }
      push(String(value));
    };

    if (rawMembers === undefined || rawMembers === null) {
      return result;
    }
    const tokens = Array.isArray(rawMembers) ? rawMembers : String(rawMembers).split(SEPARATORS);
    for (const token of tokens) {
      if (typeof token !== 'string') {
        push(token);
        continue;
      }
      const trimmed = token.trim();
      if (!trimmed) {
        continue;
      }
      const placeholder = trimmed.match(SINGLE_PLACEHOLDER);
      if (placeholder) {
        push(DirInviteHuman.lookup(vars, placeholder[1]));
      } else if (trimmed.includes('{{') && filler) {
        push(filler.fill(trimmed, Object.assign({}, vars)));
      } else {
        push(trimmed);
      }
    }
    return result;
  }

  static lookup(variables, path) {
    return path.split('.').reduce((obj, key) => (obj !== undefined && obj !== null ? obj[key] : undefined), variables);
  }

  static fixToken(token) {
    if (!token) {
      return token;
    }
    return token.startsWith('JWT ') ? token : 'JWT ' + token;
  }
}

module.exports = { DirInviteHuman };
```

- [ ] **Step 5: Run the tests to verify they pass**

Run (from `tybotRoute/`): `npx mocha test/invite_human_members_test.js --exit`
Expected: PASS (8 passing).

- [ ] **Step 6: Commit**

```bash
git add tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js tybotRoute/test/invite_human_members_test.js
git commit -m "feat(directives): resolve invite_human members from flow variables

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```

---

### Task 2: `invite_human` directive, registration and conversation tests

**Files:**
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`
- Modify: `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js` (after `static ADD_TAGS = 'add_tags'`)
- Modify: `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js` (require after line 51 `DirIfOnlineAgentsV2`; handlers map `:250-314`)
- Create: `tybotRoute/test/conversation-invite_human_bot.js`
- Create: `tybotRoute/test/conversation-invite_human_test.js`

**Interfaces:**
- 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)`.
- Produces: `Directives.INVITE_HUMAN === 'invite_human'`; handler registered in `DirectivesChatbotPlug`.

- [ ] **Step 1: Create the bot fixture**

Create `tybotRoute/test/conversation-invite_human_bot.js`:

```js
function replyV2(actionId, text, buttons) {
  const message = { type: "text", text: text };
  if (buttons) {
    message.attributes = { attachment: { type: "template", buttons: buttons } };
  }
  return {
    "_tdActionType": "replyv2",
    "_tdActionId": actionId,
    "attributes": {
      "disableInputMessage": false,
      "commands": [
        { "type": "wait", "time": 10 },
        { "type": "message", "message": message }
      ]
    }
  };
}

const intents = [
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "defaultFallback", "intent_id": "fallback-id",
    "actions": [replyV2("fallback-action", "fallback")]
  },
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "invite", "intent_id": "invite-id",
    "actions": [{
      "_tdActionType": "invite_human",
      "_tdActionId": "invite-action",
      "departmentId": "dep-sre",
      "members": "{{oncall}}, ops@acme.it",
      "trueIntent": "#invited-id",
      "falseIntent": "#noone-id"
    }]
  },
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "invited", "intent_id": "invited-id",
    "actions": [replyV2("ask-approval", "invited {{invited_humans_count}}: restart?", [
      { "uid": "b1", "type": "action", "value": "Approve", "link": "", "target": "blank", "action": "#approved-id", "attributes": "", "show_echo": true },
      { "uid": "b2", "type": "action", "value": "Reject", "link": "", "target": "blank", "action": "#rejected-id", "attributes": "", "show_echo": true }
    ])]
  },
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "noone", "intent_id": "noone-id",
    "actions": [replyV2("noone-action", "no human available")]
  },
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "approved", "intent_id": "approved-id",
    "actions": [replyV2("approved-action", "approved by {{lastUserMessage.sender}}")]
  },
  {
    "webhook_enabled": false, "enabled": true, "language": "en",
    "intent_display_name": "rejected", "intent_id": "rejected-id",
    "actions": [replyV2("rejected-action", "rejected")]
  }
];

const bot = {
  "webhook_enabled": false,
  "language": "en",
  "name": "Invite human",
  "type": "tilebot"
};

let intents_dict_by_display_name = {};
for (let i = 0; i < intents.length; i++) {
  intents_dict_by_display_name[intents[i].intent_display_name] = intents[i];
}
let intents_dict_by_intent_id = {};
for (let i = 0; i < intents.length; i++) {
  intents_dict_by_intent_id[intents[i].intent_id] = intents[i];
}

bot.intents = intents_dict_by_display_name;
bot.intents_by_intent_id = intents_dict_by_intent_id;
bot.questions_intent = {};

const bots_data = { "bots": {} };
bots_data.bots["botID"] = bot;

module.exports = { bots_data: bots_data };
```

- [ ] **Step 2: Write the failing conversation tests**

Create `tybotRoute/test/conversation-invite_human_test.js`:

```js
var assert = require('assert');
const tybot = require("..");
const tybotRoute = tybot.router;
var express = require('express');
var app = express();
const winston = require('../utils/winston');
app.use("/", tybotRoute);
app.use((err, req, res, next) => {
  winston.error("General error", err);
});
require('dotenv').config();
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
const bots_data = require('./conversation-invite_human_bot.js').bots_data;
const tilebotService = require('../services/TilebotService');

const PROJECT_ID = "projectID";
const BOT_ID = "botID";
const CHATBOT_TOKEN = "XXX";
const SERVER_PORT = 10001;
const API_PORT = 10002;

function supportRequestId() {
  return "support-group-" + PROJECT_ID + "-" + uuidv4().replace(/-/g, "");
}

function automationRequestId() {
  return "automation-request-" + PROJECT_ID + "-" + uuidv4().replace(/-/g, "");
}

function userMessage(requestId, text, extra) {
  return {
    "payload": Object.assign({
      "_id": uuidv4(),
      "senderFullname": "guest#367e",
      "type": "text",
      "sender": "A-SENDER",
      "recipient": requestId,
      "text": text,
      "id_project": PROJECT_ID,
      "metadata": "",
      "request": { "request_id": requestId }
    }, extra || {}),
    "token": CHATBOT_TOKEN
  };
}

const ONCALL_PAYLOAD = { attributes: { payload: { oncall: ['a@acme.it', 'b@acme.it'] } } };

function replyText(message) {
  const commands = message.attributes && message.attributes.commands;
  const messageCommand = commands && commands.find((c) => c.type === "message");
  return messageCommand ? messageCommand.message.text : message.text;
}

/** Starts the mock Tiledesk API; handlers receive (req, res, finish) where finish(err?) closes it and ends the test. */
function mockApi(done, handlers) {
  const endpointServer = express();
  endpointServer.use(bodyParser.json());
  let listener;
  const finish = (err) => listener.close(() => done(err));
  endpointServer.post('/:projectId/requests/:requestId/participants/invite', (req, res) => {
    try {
      handlers.invite(req, res, finish);
    } catch (err) {
      res.status(500).send({});
      finish(err);
    }
  });
  endpointServer.post('/:projectId/requests/:requestId/messages', (req, res) => {
    res.send({ success: true });
    try {
      handlers.message(replyText(req.body), finish);
    } catch (err) {
      finish(err);
    }
  });
  return new Promise((resolve) => {
    listener = endpointServer.listen(API_PORT, '0.0.0.0', () => resolve(listener));
  });
}

describe('Conversation for Invite human test', async () => {

  let app_listener;

  before(() => {
    return new Promise((resolve) => {
      tybot.startApp({
        bots: bots_data,
        TILEBOT_ENDPOINT: process.env.TILEBOT_ENDPOINT,
        API_ENDPOINT: process.env.API_ENDPOINT,
        REDIS_HOST: process.env.REDIS_HOST,
        REDIS_PORT: process.env.REDIS_PORT,
        REDIS_PASSWORD: process.env.REDIS_PASSWORD
      }, () => {
        app_listener = app.listen(SERVER_PORT, () => resolve());
      });
    });
  });

  after(function (done) {
    app_listener.close(() => done());
  });

  it('invites the resolved members and continues in the invited block', (done) => {
    const REQUEST_ID = supportRequestId();
    let inviteCalled = false;
    mockApi(done, {
      invite: (req, res) => {
        inviteCalled = true;
        assert.strictEqual(req.params.projectId, PROJECT_ID);
        assert.strictEqual(req.params.requestId, REQUEST_ID);
        assert.strictEqual(req.headers.authorization, 'JWT ' + CHATBOT_TOKEN);
        assert.strictEqual(req.body.department_id, 'dep-sre');
        assert.deepStrictEqual(req.body.members, ['a@acme.it', 'b@acme.it', 'ops@acme.it']);
        res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [{ id_user: 'agent-1', fullname: 'Agent One', already_participant: false }] });
      },
      message: (text, finish) => {
        assert.strictEqual(text, 'invited 1: restart?');
        assert.strictEqual(inviteCalled, true);
        finish();
      }
    }).then(() => {
      tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
    });
  });

  it('goes to the "no human available" block when nobody is invited', (done) => {
    const REQUEST_ID = supportRequestId();
    mockApi(done, {
      invite: (req, res) => {
        res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [], reason: 'no_available_agents' });
      },
      message: (text, finish) => {
        assert.strictEqual(text, 'no human available');
        finish();
      }
    }).then(() => {
      tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
    });
  });

  it('goes to the "no human available" block when the server fails', (done) => {
    const REQUEST_ID = supportRequestId();
    mockApi(done, {
      invite: (req, res) => {
        res.status(500).send({ success: false, error: 'boom' });
      },
      message: (text, finish) => {
        assert.strictEqual(text, 'no human available');
        finish();
      }
    }).then(() => {
      tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
    });
  });

  it('does not call the server for automation runs', (done) => {
    const REQUEST_ID = automationRequestId();
    mockApi(done, {
      invite: () => {
        throw new Error('invite endpoint must not be called for automation runs');
      },
      message: (text, finish) => {
        assert.strictEqual(text, 'no human available');
        finish();
      }
    }).then(() => {
      tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
    });
  });

  it('resumes with the human answer after the invite (HITL round trip)', (done) => {
    const REQUEST_ID = supportRequestId();
    mockApi(done, {
      invite: (req, res) => {
        res.send({ request_id: REQUEST_ID, department_id: 'dep-sre', invited: [{ id_user: 'agent-1', fullname: 'Agent One', already_participant: false }] });
      },
      message: (text, finish) => {
        if (text === 'invited 1: restart?') {
          tilebotService.sendMessageToBot(userMessage(REQUEST_ID, 'Approve', { sender: 'agent-1', senderFullname: 'Agent One' }), BOT_ID, () => {});
        } else {
          assert.strictEqual(text, 'approved by agent-1');
          finish();
        }
      }
    }).then(() => {
      tilebotService.sendMessageToBot(userMessage(REQUEST_ID, '/invite', ONCALL_PAYLOAD), BOT_ID, () => {});
    });
  });
});
```

- [ ] **Step 3: Run the conversation tests to verify they fail**

Run (from `tybotRoute/`):
```bash
API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
  npx mocha test/conversation-invite_human_test.js --timeout 60000 --exit
```
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).

- [ ] **Step 4: Implement the directive**

In `tybotRoute/tiledeskChatbotPlugs/directives/DirInviteHuman.js`, replace the header and constructor:

```js
const SEPARATORS = /[,;\n]/;
const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;

class DirInviteHuman {

  constructor(context) {
    if (!context) {
      throw new Error('context object is mandatory.');
    }
    this.context = context;
  }
```

with:

```js
const { DirIntent } = require('./DirIntent');
const { TiledeskChatbot } = require('../../engine/TiledeskChatbot');
const { Filler } = require('../Filler');
const httpUtils = require('../../utils/HttpUtils');
const winston = require('../../utils/winston');
const { Logger } = require('../../Logger');

const SEPARATORS = /[,;\n]/;
const SINGLE_PLACEHOLDER = /^\{\{\s*([\w.]+)\s*\}\}$/;
const AUTOMATION_PREFIX = 'automation-request-';

class DirInviteHuman {

  constructor(context) {
    if (!context) {
      throw new Error('context object is mandatory.');
    }
    this.context = context;
    this.chatbot = context.chatbot;
    this.requestId = context.requestId;
    this.projectId = context.projectId;
    this.token = context.token;
    this.tdcache = context.tdcache;
    this.API_ENDPOINT = context.API_ENDPOINT;
    this.intentDir = new DirIntent(context);
    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 });
  }

  execute(directive, callback) {
    winston.verbose("Execute InviteHuman directive");
    if (!directive || !directive.action) {
      this.logger.error("[Invite Human] Incorrect action for ", directive?.name, directive);
      winston.warn("(DirInviteHuman) Incorrect directive: ", directive);
      callback();
      return;
    }
    this.go(directive.action, (stop) => {
      callback(stop);
    });
  }

  async go(action, callback) {
    const trueIntent = action.trueIntent;
    const falseIntent = action.falseIntent;

    if (!trueIntent && !falseIntent) {
      this.logger.error("[Invite Human] missing both action.trueIntent & action.falseIntent");
      winston.error("(DirInviteHuman) missing both action.trueIntent & action.falseIntent");
      callback();
      return;
    }

    if (this.requestId && this.requestId.startsWith(AUTOMATION_PREFIX)) {
      this.logger.error("[Invite Human] requires a conversation");
      await this.setParameter("flowError", "(Invite human) requires a conversation");
      this.jump(falseIntent, action.falseIntentAttributes, callback);
      return;
    }

    let members = [];
    try {
      const variables = this.tdcache ? await TiledeskChatbot.allParametersStatic(this.tdcache, this.requestId) : {};
      members = DirInviteHuman.resolveMembers(action.members, variables, new Filler());
    } catch (err) {
      winston.error("(DirInviteHuman) error resolving members: ", err);
    }

    let result;
    try {
      result = await this.invite({ department_id: action.departmentId || undefined, members: members });
    } catch (err) {
      const message = (err && err.message) ? err.message : String(err);
      this.logger.error("[Invite Human] Error: " + message);
      winston.error("(DirInviteHuman) invite error: ", err);
      await this.setParameter("flowError", "(Invite human) An error occurred: " + message);
      this.jump(falseIntent, action.falseIntentAttributes, callback);
      return;
    }

    const invited = (result && Array.isArray(result.invited)) ? result.invited : [];
    await this.setParameter("invited_humans", invited);
    await this.setParameter("invited_humans_count", invited.length);

    if (invited.length > 0) {
      this.logger.native("[Invite Human] Invited: " + invited.map((i) => i.fullname || i.id_user).join(', '));
      this.jump(trueIntent, action.trueIntentAttributes, callback);
    } else {
      this.logger.native("[Invite Human] No human available");
      this.jump(falseIntent, action.falseIntentAttributes, callback);
    }
  }

  jump(intent, attributes, callback) {
    if (!intent) {
      callback();
      return;
    }
    const intentDirective = DirIntent.intentDirectiveFor(intent, attributes);
    this.intentDir.execute(intentDirective, () => {
      callback(true);
    });
  }

  async setParameter(name, value) {
    try {
      if (this.chatbot) {
        await this.chatbot.addParameter(name, value);
      } else if (this.tdcache) {
        await TiledeskChatbot.addParameterStatic(this.tdcache, this.requestId, name, value);
      }
    } catch (err) {
      winston.error("(DirInviteHuman) error setting parameter " + name, err);
    }
  }

  invite(body) {
    return new Promise((resolve, reject) => {
      const HTTPREQUEST = {
        url: `${this.API_ENDPOINT}/${this.projectId}/requests/${this.requestId}/participants/invite`,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': DirInviteHuman.fixToken(this.token)
        },
        json: body,
        method: 'POST'
      };
      httpUtils.request(HTTPREQUEST, (err, resbody) => {
        if (err) {
          reject(err);
        } else {
          resolve(resbody);
        }
      });
    });
  }
```

(The static `resolveMembers`, `lookup`, `fixToken` methods and `module.exports` from Task 1 stay below, unchanged.)

- [ ] **Step 5: Register the directive**

In `tybotRoute/tiledeskChatbotPlugs/directives/Directives.js`, replace:

```js
  static ADD_TAGS = 'add_tags'
```

with:

```js
  static ADD_TAGS = 'add_tags'
  static INVITE_HUMAN = "invite_human";
```

In `tybotRoute/tiledeskChatbotPlugs/DirectivesChatbotPlug.js`, after:

```js
const { DirIfOnlineAgentsV2 } = require('./directives/DirIfOnlineAgentsV2');
```

add:

```js
const { DirInviteHuman } = require('./directives/DirInviteHuman');
```

and in the `handlers` map replace:

```js
      [Directives.DATA_TABLES]: DirDataTables,
    };
```

with:

```js
      [Directives.DATA_TABLES]: DirDataTables,
      [Directives.INVITE_HUMAN]: DirInviteHuman,
    };
```

- [ ] **Step 6: Run the tests to verify they pass**

Run (from `tybotRoute/`):
```bash
npx mocha test/invite_human_members_test.js --exit
API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
  npx mocha test/conversation-invite_human_test.js --timeout 60000 --exit
```
Expected: PASS (8 passing, then 5 passing).

- [ ] **Step 7: Run neighbouring suites for regressions**

Run (from `tybotRoute/`):
```bash
API_ENDPOINT=http://localhost:10002 TILEBOT_ENDPOINT=http://localhost:10001 REDIS_HOST=localhost REDIS_PORT=6379 \
  npx mocha test/conversation-replyv2_button_match_test.js test/conversation-replyv2_noinput_test.js test/conversation-capture_test.js --timeout 60000 --exit
```
Expected: same results as on `origin/main` (run the same command on a clean checkout of `origin/main` if any failure appears).

- [ ] **Step 8: Commit**

```bash
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
git commit -m "feat(directives): add invite_human action to bring platform users into the conversation

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>"
```
