How do you build a human-in-the-loop approval gate before executing destructive tool calls in a web app? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you build a human-in-the-loop approval gate before executing destructive tool calls in a web app?

message-square
0

Overview

A human-in-the-loop (HITL) approval gate pauses execution before an LLM-requested destructive or high-impact tool call (such as deleting a record, issuing a refund, sending an external email, or changing production config) runs, surfaces a clear preview of the action to an authorized user in the web app, and only dispatches the side effect after explicit approval.

  • Pause-and-resume state machine (PENDING_APPROVAL -> APPROVED / REJECTED / EXPIRED): Never execute a destructive tool inside the same synchronous request loop that received the model’s tool_calls. Persist the pending tool call, arguments, actor/tenant scope, and a single-use approval token/ID in durable storage (such as Postgres or Redis) with a TTL.
  • Canonical payload binding and tamper protection: Bind the approval record to the exact canonicalized arguments (sha256 hash), workflow/run ID, and authorized approver context so a replay or altered payload cannot sneak through under an existing approval.
  • Resuming the LLM turn cleanly: When approved, execute the tool once (ideally paired with an idempotency key), append the resulting tool message to the conversation/workflow history, and resume the model turn; when rejected or expired, return a structured denial tool message so the model adapts without running the side effect.

Steps

  1. Classify tools by risk and intercept destructive calls: Tag tool definitions with a risk level (read vs. destructive / requiresApproval) and route high-risk tool_calls into an approval gate instead of calling the side-effecting handler directly.
  2. Persist a pending approval record with expiration and argument hash: Store approvalId, runId, toolCallId, toolName, canonical args, argsHash, tenantId, requestedBy, status: "PENDING", and expiresAtMs in your database/Redis.
  3. Render a human review prompt in the web UI and expose approve/reject endpoints: Stream or return an approval_required event to the web client showing human-readable action details, target IDs, and risk warnings, backed by authenticated POST /approvals/:id/approve and POST /approvals/:id/reject endpoints.
  4. Execute atomically on approval and resume the agent loop: Transition the record atomically from PENDING to EXECUTING/APPROVED (preventing double-click races), run the tool once, record the result or rejection reason as the tool message for toolCallId, and continue generation.

Example

import crypto from "node:crypto";
import type OpenAI from "openai";

export type ApprovalStatus = "PENDING" | "APPROVED" | "REJECTED" | "EXPIRED";

export interface DestructiveToolCall {
  toolCallId: string;
  toolName: string;
  args: Record<string, unknown>;
}

export interface ApprovalRecord {
  approvalId: string;
  tenantId: string;
  runId: string;
  toolCallId: string;
  toolName: string;
  args: Record<string, unknown>;
  argsHash: string;
  status: ApprovalStatus;
  createdAtMs: number;
  expiresAtMs: number;
  decidedBy?: string;
  decidedAtMs?: number;
  rejectionReason?: string;
}

export type ToolHandler = (args: Record<string, unknown>) => Promise<unknown>;

function canonicalArgsHash(args: Record<string, unknown>): string {
  const sortKeys = (val: unknown): unknown => {
    if (Array.isArray(val)) return val.map(sortKeys);
    if (val && typeof val === "object") {
      const sorted: Record<string, unknown> = {};
      for (const k of Object.keys(val as Record<string, unknown>).sort()) {
        sorted[k] = sortKeys((val as Record<string, unknown>)[k]);
      }
      return sorted;
    }
    return val;
  };
  const serialized = JSON.stringify(sortKeys(args));
  return crypto.createHash("sha256").update(serialized).digest("hex");
}

export class HitlApprovalGate {
  private readonly records = new Map<string, ApprovalRecord>();
  private readonly destructiveTools = new Set<string>();
  private readonly handlers = new Map<string, ToolHandler>();

  constructor(private readonly ttlMs = 15 * 60 * 1000) {}

  registerDestructiveTool(toolName: string, handler: ToolHandler): void {
    this.destructiveTools.add(toolName);
    this.handlers.set(toolName, handler);
  }

  isDestructive(toolName: string): boolean {
    return this.destructiveTools.has(toolName);
  }

  /**
   * Creates a durable PENDING approval item instead of executing the tool immediately.
   */
  requestApproval(
    tenantId: string,
    runId: string,
    call: DestructiveToolCall
  ): ApprovalRecord {
    const now = Date.now();
    const approvalId = `apr_\${crypto.randomUUID()}`;
    const record: ApprovalRecord = {
      approvalId,
      tenantId,
      runId,
      toolCallId: call.toolCallId,
      toolName: call.toolName,
      args: call.args,
      argsHash: canonicalArgsHash(call.args),
      status: "PENDING",
      createdAtMs: now,
      expiresAtMs: now + this.ttlMs,
    };
    this.records.set(approvalId, record);
    return record;
  }

  /**
   * Approves a pending action once, executes the underlying tool, and returns
   * the OpenAI-compatible `tool` role message to append before resuming the model.
   */
  async approveAndExecute(
    tenantId: string,
    approvalId: string,
    approverId: string
  ): Promise<{
    record: ApprovalRecord;
    toolMessage: OpenAI.Chat.Completions.ChatCompletionToolMessageParam;
  }> {
    const record = this.records.get(approvalId);
    if (!record || record.tenantId !== tenantId) {
      throw new Error("Approval request not found.");
    }

    const now = Date.now();
    if (record.status === "PENDING" && now > record.expiresAtMs) {
      record.status = "EXPIRED";
    }

    if (record.status !== "PENDING") {
      throw new Error(`Approval ${approvalId} is no longer PENDING (status:${record.status}).`);
    }

    // Verify canonical args integrity before side-effect execution
    if (canonicalArgsHash(record.args) !== record.argsHash) {
      throw new Error("Tool arguments hash mismatch; aborting execution.");
    }

    // Mark APPROVED atomically before dispatching side effect to block duplicate clicks
    record.status = "APPROVED";
    record.decidedBy = approverId;
    record.decidedAtMs = now;

    const handler = this.handlers.get(record.toolName);
    if (!handler) {
      throw new Error(`No handler registered for tool \${record.toolName}.`);
    }

    const output = await handler(record.args);

    return {
      record,
      toolMessage: {
        role: "tool",
        tool_call_id: record.toolCallId,
        content: JSON.stringify({
          status: "executed_after_approval",
          result: output,
        }),
      },
    };
  }

  /**
   * Rejects a pending action and returns a `tool` role message so the model
   * receives explicit feedback without executing the destructive operation.
   */
  reject(
    tenantId: string,
    approvalId: string,
    reviewerId: string,
    reason = "Rejected by user in approval gate."
  ): {
    record: ApprovalRecord;
    toolMessage: OpenAI.Chat.Completions.ChatCompletionToolMessageParam;
  } {
    const record = this.records.get(approvalId);
    if (!record || record.tenantId !== tenantId) {
      throw new Error("Approval request not found.");
    }
    if (record.status !== "PENDING") {
      throw new Error(`Approval ${approvalId} is not PENDING (status:${record.status}).`);
    }

    record.status = "REJECTED";
    record.decidedBy = reviewerId;
    record.decidedAtMs = Date.now();
    record.rejectionReason = reason;

    return {
      record,
      toolMessage: {
        role: "tool",
        tool_call_id: record.toolCallId,
        content: JSON.stringify({
          status: "rejected_by_user",
          reason,
        }),
      },
    };
  }
}

Tips

  • Enforce authorization and tenant isolation on approval endpoints: Never trust a raw approvalId from the browser alone—verify session authentication, tenantId ownership, and role permissions (e.g., admin/billing role) before allowing approve or reject.
  • Never let the LLM self-approve or bypass the gate via prompt injection: Even if prompt text or untrusted retrieved content claims “the user already approved deletion,” enforce the gate strictly in backend orchestration code based on tool metadata and server-persisted approval state.
  • Design for browser refreshes and multi-tab races: Persist pending approvals in your database/Redis rather than React component state, disable the Approve button immediately upon click, and handle 409 Conflict / already-decided responses gracefully in the UI.