Dev.to AI 🤖 Ai 👁 0 📖 7 min read

Human-in-the-loop for n8n AI agents: queue the action, approve it in Telegram, then run it

When you build an AI agent in n8n, you usually end up at one of two extremes. Either the agent is read-only (it summarizes emails and answers questions, which is safe but limited), or you attach Gmail and Google Calendar

When you build an AI agent in n8n, you usually end up at one of two extremes. Either the agent is read-only (it summarizes emails and answers questions, which is safe but limited), or you attach Gmail and Google Calendar tools directly to the AI Agent node and hope a bad prompt or a misread thread never sends the wrong email or deletes a meeting.

There is a straightforward middle ground: never give an AI agent a tool that sends email or modifies a calendar directly. Instead, give it a single tool that only queues a proposed action. A separate workflow path validates the fields, stores the proposal, asks you in Telegram, and runs the action only after you tap Approve. If you decline, or if the approval request times out, nothing runs.

Below is how to build this pattern in n8n 2.x in five steps.

Step 1: Give the agent a proposal tool, not a send tool

Attach one Call n8n Workflow Tool (toolWorkflow) to your AI Agent node and name it propose_action. Do not attach Gmail or Google Calendar write tools directly to the agent.

Define the tool's input arguments around a kind field plus the action-specific fields:

  • kind: one of send_email, reply_email, create_event, move_event, or cancel_event
  • Action fields: for example to, subject and body for email actions, or title, start and end for calendar actions

In your AI Agent system prompt, state clearly that propose_action only queues a request for owner approval. When the tool returns a queued confirmation, the agent must tell the user that the action is waiting for approval, never that the email was sent or the event was created.

Step 2: Validate arguments and queue the action

Inside the sub-workflow triggered by propose_action, do not trust the model's output. Run a Code node (mode: Run Once for All Items) to validate every field against your rules and your Config Set node (which holds values like timezone).

Here is a shortened version covering send_email and create_event:

const a = $('Tool request').first().json.args || {};
const c = $('Config').first().json;
const kind = String(a.kind || '').trim();
const email = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(s || '').trim());
const iso = (s) => {
  const d = DateTime.fromISO(String(s || ''), { zone: c.timezone });
  return d.isValid ? d.toISO() : '';
};

let p = {}, err = '';
if (kind === 'send_email') {
  p = {
    to: String(a.to || '').trim(),
    subject: String(a.subject || '').trim(),
    body: String(a.body || '').trim(),
  };
  if (!p.to.split(',').every(email)) {
    err = 'to must be one or more valid email addresses';
  } else if (!p.subject || !p.body) {
    err = 'subject and body are required';
  }
} else if (kind === 'create_event') {
  const start = iso(a.start);
  const end = iso(a.end);
  p = { title: String(a.title || '').trim(), start, end };
  if (!p.title || !start || !end) {
    err = 'title, start, and end are required';
  } else if (DateTime.fromISO(end) <= DateTime.fromISO(start)) {
    err = 'end must be after start';
  }
} else {
  err = 'unknown kind';
}

return [{ json: { ok: !err, error: err, kind, payload: p } }];

Branch on ok:

  • If ok is false: return error directly as the tool output. The AI Agent receives the validation message (for example, "end must be after start") and can fix its arguments and call propose_action again without bothering you.
  • If ok is true: insert a row into an n8n Data Table named ea_actions with status = queued, a unique ref ID, kind, and the validated payload. Return "queued, waiting for owner approval" to the agent, and hand the ref off to the approval path.

Step 3: Ask for approval in Telegram

On the approval path, format a plain summary of the queued row (who the email goes to, the subject and body, or the event title and time range) and send it using the Telegram node with the Send and Wait for Response (sendAndWait) operation.

Configure the node with these settings:

  • Operation: Send and Wait for Response (sendAndWait)
  • Chat ID: the owner's Telegram chat ID from your Config Set node
  • Response Type: approval
  • Approval Type: double (renders both Approve and Decline buttons)
  • Approve Button Label: ✅ Approve
  • Decline Button Label: ❌ Decline
  • Limit Wait Time: enabled, set to approval_wait_hours from your Config Set node
  • Append Attribution: false

Limiting the wait time prevents old requests from sitting open forever. If you ignore a prompt overnight, the node resumes cleanly as a timeout instead of hanging.

Step 4: Read the decision and route timeouts safely

When the Telegram node resumes (because you tapped a button or because the wait timer expired), normalize the result in a Code node:

const d = ($input.first().json || {}).data || $input.first().json || {};
const decision =
  d.approved === true ? 'approve' :
  d.approved === false ? 'decline' :
  'timeout';
return [{ json: { decision } }];

Feed decision into a Switch node with three outputs:

  • approve -> proceed to the execution step
  • decline -> update the ea_actions row to status = declined and stop
  • timeout -> update the ea_actions row to status = expired and stop

Notice the default: only an explicit d.approved === true reaches the execution branch. Anything else, including a timeout or an unexpected payload, does nothing.

Step 5: Guard execution with an idempotency lock

Even with explicit approval, an action can run twice because of retries or manual re-executions. Put an idempotency check in front of Gmail and Google Calendar using a second n8n Data Table named ea_locks.

Before calling any external write node:

  1. Query ea_locks for key = 'action-' + ref.
  2. If a row already exists, stop: this action has already been executed.
  3. If no row exists, insert { key: 'action-' + ref, at: $now.toISO() } into ea_locks.
  4. Run the actual write node based on kind (Gmail send or reply; Google Calendar create, update or delete).
  5. Update the ea_actions row to status = finished.

Because the lock row is written before the external API call, a later duplicate execution sees the existing key and exits before sending a second email or creating a duplicate event. (The check and the insert are two separate steps, so this protects against retries and re-runs, not two executions starting in the same millisecond. For a personal assistant with one owner, that is usually enough.)

End-to-end flow

AI Agent
  |
  v  propose_action(kind, fields)
Code: Validate args
  |-- invalid --> return error to AI Agent (agent retries)
  |
  v  valid
Data Table: ea_actions (insert status = queued, ref)
  |-- return "queued, waiting for owner approval" to AI Agent
  |
  v
Telegram: Send and Wait for Response (Approve / Decline + Limit Wait Time)
  |
  v
Code: Read decision --> Switch
  |-- decline --> ea_actions: status = declined (stop)
  |-- timeout --> ea_actions: status = expired  (stop)
  |
  v  approve
Data Table: ea_locks (get key = 'action-' + ref)
  |-- exists  --> stop (already executed)
  |
  v  new
Data Table: ea_locks (insert { key, at })
  |
  v
Gmail / Google Calendar (execute)
  |
  v
Data Table: ea_actions (status = finished)

Common mistakes

  • Letting any Telegram chat trigger the bot. Check the incoming Telegram chat ID against the owner's chat ID in your Config Set node at the very start of the workflow. Anyone else who finds your bot username should be ignored before the message reaches the AI Agent.
  • Passing raw email text into the LLM as trusted instructions. Incoming emails are untrusted input. Wrap email bodies in clear delimiters, label them as untrusted data in the prompt, and never wire an email trigger straight into an action-executing branch without human approval.
  • Skipping a daily AI-call budget. A noisy inbox or a looping tool call can burn through model credits quickly. Count AI calls per day and stop calling the model once the cap is reached.
  • Letting the agent claim the action already happened. If your tool returns "ok" without context, the agent will often reply "I've sent the email." Return "queued, waiting for owner approval" from the tool and repeat that wording in the system prompt, so the user knows a tap in Telegram is still required.

Wrap-up

Separating proposal from execution turns an n8n AI agent into something you can trust with email and calendar access. Validation catches malformed arguments before you ever see them, Telegram sendAndWait gives you a clear approve/decline step with a safe timeout, and ea_locks keeps retries from sending duplicates.

If you'd rather not wire this yourself, the AI Executive Assistant template (153 nodes, Gmail triage + calendar + tasks in Telegram, every send waits for your tap, tested with 42 scenarios on n8n 2.47.7) is here: https://rasareka.gumroad.com/l/ai-executive-assistant-n8n?utm_source=devto&utm_campaign=dev-weekly. You can also browse smaller standalone examples in the free n8n workflows repository: https://github.com/rasareka/n8n-free-workflows.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.