●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through●CC 2.1.332 — No new Claude Code release over the weekend. 2.1.332 (11/25) is still current●ANALYTICS — A fix to search counts in the Enterprise Analytics API may raise numbers from 11/17 onward●SONNET 4.5 — Today, 11/30, is Sonnet 4.5's last day on the Claude API. Move to claude-sonnet-5-5●USAGE — Some users report weekly usage jumping right after upgrading to a higher plan●NEW — New: Does what a Project remembers carry over into your everyday chats?●BILLING — More readers are looking for what to check when a payment won't go through
Inserting Approval Gates Into Your Agents — A Production Design for Human-in-the-Loop With the Claude API
Once you put an agent in production, the requirement 'please get a human to approve just this specific decision' appears within days. This guide walks through the design patterns for retrofitting approval gates and handling suspend/resume correctly, with working code.
When you hand tools to an agent, it usually works remarkably well. The problem is the small percentage of cases that slip past "usually," where something irreversible happens.
The first time I ran an agent in production, what scared me most wasn't bugs — it was the agent working too correctly. Once you list a payment API, an email sender, or a database DELETE as available tools, Claude will call them without hesitation when it decides they're needed. A flow that behaved perfectly in tests can, under real user edge cases, execute tools in an unexpected order. Before you notice, a wrongly-addressed invoice is sitting in a customer's inbox, or a partial refund has gone through to the wrong account.
What follows is the production design I use for inserting Human-in-the-Loop (HITL) — a human stepping in for specific decisions — into Claude API's standard tool_use / tool_result loop, with working code. Instead of giving up on autonomy entirely, the trick is to decide in advance where you'll stop, who approves, and what they'll see.
I'm writing for someone who already has a tool-using agent running and has just been told "a person needs to look at this one operation." The two things I'd like you to leave with are a complete stop–persist–resume loop and a symptom-first table for the errors that show up on resume. The code assumes Python 3.11 and the anthropic SDK; model IDs and retirement dates were checked against the official docs as of November 2026.
What to Think About Before Your Agent "Just Runs" Something
Before designing HITL, articulate what you actually want to stop. This is not purely a technical question; it's a business-risk question. Teams that skip this step tend to put approval on every single tool call, and approval fatigue sets in until nobody actually reads the requests. The slide is easy to picture: approvals start detailed, then degrade to "looks fine," then become a keyboard reflex.
You can reduce the design axes to three:
Irreversibility: Can the operation be undone? (payments, contract signing, external emails, DNS changes)
Blast radius: Does the impact stay inside one internal user, or does it touch external customers or public systems?
Amount / compliance threshold: Should the gate activate only above certain monetary thresholds, or when personal data, regulated data, or cross-jurisdictional data is involved?
Classify every tool along these axes into Red (always approve), Yellow (approve under conditions), and Green (automatic). Document this before writing code. Red means you always stop, Yellow means threshold logic, Green means run as usual. When the classification is explicit, the human reviewer also has a clear sense of what they're evaluating in each request. Putting this matrix in a shared document also gives you something product managers and legal reviewers can read and challenge, which is far harder to do with raw code.
A Common Misconception — "Approving Everything" Is Not Safer
It feels intuitively correct that more approval gates mean more safety, but in production it increases incidents. Humans who repeatedly receive monotonous approval requests stop reading them and start rubber-stamping — a familiar failure in any system that leans on a human to confirm what a machine has already decided.
I don't have a hard number to offer, but my sense is that once approval requests pile up day after day, reviewers start skimming — and sooner than you'd expect. The courage to remove gates and the quality of your Yellow thresholds determine the quality of production operations. At design time, estimate how many approvals per day each gate will fire. If the real number exceeds the estimate, loosen the threshold or add automation logic instead of burying your reviewers. It helps to track a simple metric: "what percentage of requests are rejected?" If that number is essentially zero for a given gate, the gate is probably providing no value, only cost.
Five Places Where You Can Insert an Approval Gate
Where you place the gate along the agent's lifecycle trades off implementation complexity against safety. I usually choose from these five and combine them per project.
1. Just Before Tool Execution (Most Common)
Insert a gate immediately after Claude returns a tool_use block and before you actually call the tool. A human reviews the input parameters; if acceptable, you execute, otherwise you send back a rejection or correction message. The implementation is the simplest, and you can tune Red/Yellow/Green on a per-tool basis. It's also the easiest to explain to stakeholders, which matters more than it sounds when you're getting buy-in from legal or compliance teams.
2. Before Returning the Tool Result
After the tool runs, check the result before passing it back to Claude. For example, you might filter out personally identifiable information from database query results, or strip out rows that belong to customers outside a permitted region. Because you intercept before Claude uses the data for further reasoning, this suits privacy-sensitive or data-leak-prone cases. It's especially useful when the tool itself is safe to run (it only reads) but the content it returns might steer the agent into regulated territory.
3. Dynamic Gate Based on Parameter Values
The tool itself doesn't require approval, but the gate triggers only for specific inputs — for example, "auto-approve refunds under ¥10,000, require approval above." This is the design that most often balances operations load and safety, and it's almost always my first recommendation for a new project. You can compose several dimensions into the trigger: amount, customer tier, time of day, rate of the same operation within a short window. Each dimension you add is another lever for tuning later.
4. Plan Review at Session Start
Let Claude produce "just the plan" first, have a human review it, then start execution. This is useful for long-running agents or critical business processes, but you need a separate design for what happens when Claude tries to call new tools mid-session. The usual pattern is to allow a pre-approved set of tools to run freely after plan approval, while any tool outside the plan triggers a normal per-call gate. It's more state to track, but the user experience for both the agent and the operator is much smoother.
5. Fallback Gate on Anomaly Detection
The agent runs fully autonomous most of the time, with a human only stepping in when error rates or unexpected tool-call patterns appear. It requires integration with monitoring metrics, so implementation cost is higher, but it's worth adopting when you don't want to drop your automation rate. A simple starting point: if the agent calls the same tool more than N times within M minutes, or if two consecutive tool calls return errors, pause for review. These signals catch runaway loops and regression regressions without affecting normal traffic.
Side by side, the five placements look like this:
Placement
What it stops
Build cost
Approval-fatigue risk
Fits when
1. Right before tool execution
The execution itself
Low
High
Only a few Red tools, low volume
2. Before returning the result
What Claude gets to see
Low
Medium
Lookups may contain personal data
3. Dynamic gate on arguments
Only calls above a threshold
Medium
Low
Risk depends on amount, count, or recipient
4. Plan review at session start
A wrong overall approach
High
Low
Long-running business workflows
5. Anomaly fallback
Unexpected behavior
High
Almost none
You can't lower automation and already have monitoring
If I had to reduce it to one sentence: if risk changes with the arguments, use #3; if the tool name alone decides it, use #1; if neither, you probably don't need a gate yet.
For the first iteration on a project, I recommend starting from #3 (dynamic gate). It's the pattern that fails the least. #1 and #2 are simple but tend to invite approval fatigue. #4 and #5 are more complex. Adding #1 or #5 later is easier because you'll have operations data to calibrate thresholds. This sequencing is the opposite of what looks "safer on paper," and it's the single most common mistake I see in initial HITL designs.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦You'll stop struggling to identify which operations are too risky to automate — you'll have a clear framework with five placement options for approval gates and three decision axes
✦You'll be able to suspend and resume the tool_use / tool_result loop, and you'll have concrete code connecting Claude API with Slack and email approval flows
✦You'll understand how to prevent production-specific incidents like privilege escalation, double execution, and expired approvals, with audit logs and timeout designs that stand up to compliance review
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Designing Suspend and Resume — Persist the Message Loop
The core design of HITL is "pause the agent loop midway and resume later." Claude API is stateless by default, so to resume you need to persist an "awaiting-approval snapshot" yourself. This is not optional — if you try to hold state in memory across an approval request, you'll lose it on deploy, on pod restart, or simply when a request lands on a different instance behind the load balancer.
A minimal data model looks like this:
session_id: Agent session identifier
messages: The full messages array up to this point (JSON)
pending_tool_use: The tool_use block awaiting approval (id, name, input)
The following is the core loop that wires this state machine into the Claude API.
# agent_loop.py# Purpose: Insert an approval gate just before tool calls, and resume from# the same state once approval is granted.# Requires: anthropic>=0.40, Python 3.11+; persistence works with either Redis or Postgres.# Model IDs as of November 2026. claude-sonnet-4-5-20250929 was retired on 2026-11-30, so never hard-code it.import jsonimport osfrom dataclasses import dataclassfrom typing import Any, Callablefrom anthropic import Anthropicclient = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5")# Red list: tool names that always require approvalRED_TOOLS = {"send_money", "delete_user", "send_email_to_customer"}@dataclassclass ApprovalRequired(Exception): session_id: str tool_use_id: str tool_name: str tool_input: dictdef needs_approval(tool_name: str, tool_input: dict) -> bool: """Red/Yellow decision. Example: Yellow uses an amount threshold.""" if tool_name in RED_TOOLS: return True if tool_name == "refund_payment": amount = tool_input.get("amount_jpy", 0) return amount >= 10_000 # approve at or above 10,000 JPY return Falsedef run_tool(tool_name: str, tool_input: dict) -> str: """Real tool execution is swappable by the caller.""" # In production, call Stripe SDK, DB clients, etc. return json.dumps({"ok": True, "tool": tool_name, "input": tool_input})def step_agent( session_id: str, messages: list, tools: list, store: "StateStore", on_approval_required: Callable[[ApprovalRequired], None],) -> dict: """Advance one turn. Raises ApprovalRequired if approval is needed.""" resp = client.messages.create( model=MODEL, max_tokens=1024, tools=tools, messages=messages, ) # Append Claude's response to history (SDK objects aren't JSON-serializable, so store dicts) messages.append({"role": "assistant", "content": [_to_dict(b) for b in resp.content]}) if resp.stop_reason != "tool_use": # Besides end_turn, a turn can stop on max_tokens / pause_turn / refusal. # Appending a user turn with no tool_use to answer sends empty content and gets a 400. done = resp.stop_reason in ("end_turn", "stop_sequence") status = "completed" if done else f"stopped:{resp.stop_reason}" store.save(session_id, messages=messages, pending=None, status=status) return {"status": status, "text": _final_text(resp)} tool_uses = [b for b in resp.content if b.type == "tool_use"] # Decide on every tool_use first; if any needs approval, run nothing and stop the whole turn gated = [b for b in tool_uses if needs_approval(b.name, b.input)] if gated: store.save( session_id, messages=messages, pending={ "gated_ids": [b.id for b in gated], "tool_uses": [ {"id": b.id, "name": b.name, "input": b.input} for b in tool_uses ], }, status="awaiting_approval", ) exc = ApprovalRequired( session_id=session_id, tool_use_id=gated[0].id, tool_name=gated[0].name, tool_input=gated[0].input, ) on_approval_required(exc) raise exc # No approval needed: return a tool_result for every tool_use in this turn tool_results = [ { "type": "tool_result", "tool_use_id": b.id, "content": run_tool(b.name, b.input), } for b in tool_uses ] messages.append({"role": "user", "content": tool_results}) store.save(session_id, messages=messages, pending=None, status="running") return {"status": "running"}def _final_text(resp) -> str: return "".join(b.text for b in resp.content if b.type == "text")def _to_dict(block) -> dict: """model_dump() for SDK blocks, vars() for test fakes.""" if hasattr(block, "model_dump"): return block.model_dump(exclude_none=True) return dict(vars(block))
The key point in this loop is that state is always persisted before raising ApprovalRequired. If you raise first and persist second, a downstream notification failure can leave the session orphaned. Also, when Claude returns multiple tool_use blocks in a single turn, the code classifies all of them before running anything, and stopping the entire turn even if only one needs approval is intentional. The API also expects a tool_result for every tool_use in the turn, so a half-executed turn can't be resumed cleanly. Partial execution risks leaving later tools operating on state the earlier tools assumed — and if approval ends up being rejected, you have partial results that never should have been produced. When in doubt, stop the whole turn and let Claude re-plan on resume; re-planning is cheap compared to cleanup.
My first version had a second hole: it only checked whether stop_reason was end_turn. When a response stopped on max_tokens halfway through, it had no tool_use blocks at all, yet the code fell into the tool branch and sent an empty list of tool_result blocks as the user turn. The official stop-reasons guide is clear that end_turn and tool_use are not the only outcomes. Going into the tool branch only on tool_use, and persisting-then-returning for everything else, keeps the loop intact as new stop reasons appear.
Resuming After Approval — Rejection Handling Is Where Designs Differ
Once approval is granted, resume by appending the tool_result blocks for every tool_use in the stopped turn to the saved messages and calling step_agent again. On rejection, return is_error: true with the reason for the call that was waiting, and a short "skipped" error for the calls that were stopped alongside it.
# resume_agent.pyfrom typing import Callablefrom agent_loop import ApprovalRequired, run_tool, step_agentdef resume_after_approval( session_id: str, decision: str, # "approved" or "rejected" note: str, store: "StateStore", tools: list, notify: Callable[[ApprovalRequired], None],) -> dict: state = store.load(session_id) if state["status"] != "awaiting_approval": raise ValueError(f"session {session_id} is not waiting") pending = state["pending"] messages = state["messages"] # Return a tool_result for every tool_use in the turn (the API errors if any is missing) tool_results = [] for tu in pending["tool_uses"]: if decision == "approved": content, is_error = run_tool(tu["name"], tu["input"]), False elif tu["id"] in pending["gated_ids"]: # Tell Claude why, so it can consider alternative approaches content = f"Human reviewer rejected this tool call. Reason: {note}" is_error = True else: content = "Skipped: another tool call in the same turn was rejected." is_error = True result = {"type": "tool_result", "tool_use_id": tu["id"], "content": content} if is_error: result["is_error"] = True tool_results.append(result) messages.append({"role": "user", "content": tool_results}) store.save(session_id, messages=messages, pending=None, status="running") # If the next turn hits a gate again, it must reach a human through the same channel return step_agent(session_id, messages, tools, store, on_approval_required=notify)
Returning is_error: true nudges Claude toward "accomplish the goal another way" instead of just failing with an exception — this is the real difference from naive exception handling. That said, vague rejection notes cause Claude to retry the same tool. Keep the note field free-form but provide templates for reviewers ("threshold exceeded," "customer identity not verified," "refund requires manager approval," etc.). Repeat-request rates drop noticeably when reasons are specific. A useful advanced pattern: when the rejection reason indicates the approval was fundamentally impossible (e.g. "customer account is frozen"), include a hint like "do not retry this action" so Claude moves on to a different strategy rather than trying again with slightly different inputs.
The notify parameter on the resume function is there because this is exactly where I once got stuck. I had written on_approval_required=lambda e: None, and when Claude reached for a second payment in the turn after an approval, the session paused correctly in awaiting_approval — and nobody was told. A gate that stops silently is a different kind of failure from one that runs unchecked, but it's still a failure. Where you stop and how you notify always travel together. I check that pairing every time I touch a resume path now.
For parallel calls in a single turn and how to handle partial failures, I've written up the patterns in using Parallel Tool Use in production. Deciding how to order parallel results before adding gates keeps the resume code short.
Pin Down the Multi-Call Turn With a Test
Approval-gate bugs tend to show up when one turn contains several calls. If a read-only lookup and a payment tool land in the same turn, a naive loop runs the lookup first and then stops at the payment — leaving a half-finished turn behind.
Here is the test I'd keep next to it. Claude's response is faked, so it runs instantly and never touches the API.
# test_multi_tool_turn.py# Goal: lock in that a turn containing any gated call executes nothing# Run: pytest with a dummy ANTHROPIC_API_KEY set (no real API call is made)from types import SimpleNamespace as NSimport agent_loopclass FakeStore: def __init__(self): self.saved = [] def save(self, session_id, **kw): self.saved.append(kw)def fake_response(): return NS( stop_reason="tool_use", content=[ NS(type="tool_use", id="tu_1", name="lookup_order", input={"order_id": "A-100"}), NS(type="tool_use", id="tu_2", name="send_money", input={"amount_jpy": 50_000}), ], )def test_nothing_runs_when_any_call_is_gated(monkeypatch): executed = [] monkeypatch.setattr(agent_loop, "run_tool", lambda n, i: executed.append(n) or "{}") monkeypatch.setattr(agent_loop.client.messages, "create", lambda **kw: fake_response()) store = FakeStore() try: agent_loop.step_agent("s1", [], [], store, lambda e: None) except agent_loop.ApprovalRequired: pass assert executed == [] # even the read-only tool did not run last = store.saved[-1] assert last["status"] == "awaiting_approval" assert len(last["pending"]["tool_uses"]) == 2 # both calls are saved, so resume can answer both
It checks two things only: the read-only tool didn't run, and both tool_use blocks were saved for resume. Running it whenever you touch the gate logic is the cheapest insurance I know of.
Wiring the Approval UI and Async Notifications — Slack and Email
How you actually notify a human about a pending approval depends on the operations side. In my experience, Slack works for internal operators, while email plus a dedicated UI fits better for customer-facing flows. Mixing both is common; it's also fine for one organization to settle on a single channel as long as that channel is reliably monitored.
Slack Interactive Messages
Slack Block Kit plus Interactive Components lets you send a message with approve/reject buttons and receive the click as a webhook. Here is the sender side.
# notify_slack.py# Purpose: Post an approval request to Slack, embedding the session ID into action_id.import osimport requestsSLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]def send_approval_request(session_id: str, tool_name: str, tool_input: dict) -> None: """Post an approval-request message to Slack.""" text_input = "\n".join(f"• *{k}*: `{v}`" for k, v in tool_input.items()) payload = { "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": f"*Approval needed* — the agent wants to call `{tool_name}`.", }, }, {"type": "section", "text": {"type": "mrkdwn", "text": text_input}}, { "type": "actions", "elements": [ { "type": "button", "text": {"type": "plain_text", "text": "Approve"}, "style": "primary", "action_id": f"approve::{session_id}", }, { "type": "button", "text": {"type": "plain_text", "text": "Reject"}, "style": "danger", "action_id": f"reject::{session_id}", }, ], }, ] } r = requests.post(SLACK_WEBHOOK_URL, json=payload, timeout=5) r.raise_for_status()
For buttons to be clickable, your Slack app needs Interactivity turned on with a Request URL — your own endpoint that receives click payloads. Buttons posted through an incoming webhook that belongs to that app send their clicks to that Request URL.
Before calling resume_after_approval, check two things. First, that the request really came from Slack. Slack signs every request with X-Slack-Signature and X-Slack-Request-Timestamp; recompute the signature with your Signing Secret and compare.
# verify_slack.py# Goal: confirm that a request hitting the Interactivity Request URL came from Slackimport hashlibimport hmacimport osimport timeSIGNING_SECRET = os.environ["SLACK_SIGNING_SECRET"].encode()APPROVERS = set(os.environ["APPROVER_SLACK_IDS"].split(",")) # user_ids allowed to approvedef verify_slack_request(headers: dict, raw_body: bytes) -> bool: ts = headers.get("X-Slack-Request-Timestamp", "0") if abs(time.time() - int(ts)) > 60 * 5: return False # older than five minutes: treat as a replay base = b"v0:" + ts.encode() + b":" + raw_body expected = "v0=" + hmac.new(SIGNING_SECRET, base, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, headers.get("X-Slack-Signature", ""))def can_approve(payload: dict, requested_by: str) -> bool: # The clicker must be on the approver list and must not be the requester user_id = payload["user"]["id"] return user_id in APPROVERS and user_id != requested_by
Second, that the person who clicked is allowed to approve. A button anyone in the channel can press records that "someone pressed it," not that a decision was made. Blocking requesters from approving their own requests is one less thing to explain in an audit.
Then, the timing gotcha: Slack marks a button as failed if you don't return HTTP 200 within three seconds, so push heavy work to an async queue (Celery, BullMQ, SQS, etc.). Acknowledge immediately and let a background worker handle the actual agent resume — the system will be dramatically more stable. Another subtle thing to watch: if Slack retries the webhook because of a transient network blip, you'll receive the same interaction event twice. We'll talk about that shortly in the double-execution failure pattern, but the preventive design lives in your webhook handler, not in the queue.
Email Approval — Two Clicks With a Signed Token
For external approvers, email with an approval URL is the most straightforward option. Embed an HMAC-signed token in the URL so clicking the link is enough to approve.
# email_approval.py# Purpose: Pack session ID and decision into a signed token and generate email URLs.import hmacimport hashlibimport jsonimport base64import osimport timeSIGNING_KEY = os.environ["APPROVAL_SIGNING_KEY"].encode()def _sign(payload: dict) -> str: raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode() sig = hmac.new(SIGNING_KEY, raw, hashlib.sha256).digest() return base64.urlsafe_b64encode(raw + b"." + sig).decode()def build_approval_url(session_id: str, decision: str, ttl_sec: int = 3600) -> str: token = _sign( { "session_id": session_id, "decision": decision, "exp": int(time.time()) + ttl_sec, } ) return f"https://example.com/approve?token={token}"def verify_token(token: str) -> dict: try: blob = base64.urlsafe_b64decode(token.encode()) raw, sig = blob.rsplit(b".", 1) expected = hmac.new(SIGNING_KEY, raw, hashlib.sha256).digest() if not hmac.compare_digest(sig, expected): raise ValueError("bad signature") data = json.loads(raw) if data["exp"] < int(time.time()): raise ValueError("token expired") return data except Exception as e: raise ValueError(f"invalid token: {e}") from e
Two non-negotiables here: tokens must include an expiry, and HMAC comparison must use hmac.compare_digest to avoid timing attacks. One-click approval is convenient, but the URL can leak through email forwarding. For the riskiest operations, consider requiring the user to log into an internal system with 2FA before honoring the click. It's also worth building an endpoint that recognizes already-processed tokens and shows a friendly "this request was already handled" message — it prevents a lot of confused follow-up, especially when multiple approvers are on the same distribution list and two click at once. Treat the signed token as a bearer credential: short TTL, single-use, and revocable through session status.
A Common Misconception — "The Link Was Opened" Doesn't Mean "A Human Approved"
The easiest thing to miss with one-click approval is that the one opening the link may not be a person. Corporate mail-security products and preview features sometimes open links ahead of the recipient. If a plain GET finalizes the approval, a request can end up approved without anyone reading it.
The fix is simple: the link opens a confirmation page showing the request and an Approve button, and only a POST from that page finalizes it. Take the token in the POST body and call verify_token there. It's two clicks instead of one, but the second click is the minimum evidence that a human actually read the request.
Handling Expiration and Timeouts
Approval requests cannot wait forever. Operators go home at 6 PM, requests span weekends, and notifications get missed. You must plan for all three.
My default structure has three layers:
Soft timeout (15 minutes): Re-send a reminder if nobody has responded after 15 minutes.
Hard timeout (4 hours): Auto-reject and tell Claude "this tool call could not be executed due to a timeout."
Escalation (1 hour): Notify the primary operator's manager.
A background job sweeps periodically:
# timeout_worker.py# Purpose: Periodically scan pending approvals and handle reminder / escalation / timeout.import timedef sweep(store, slack_sender, resumer): now = int(time.time()) for session in store.list_awaiting_approval(): age = now - session["created_at"] if age > 4 * 3600 and not session.get("expired"): store.mark_expired(session["id"]) resumer.resume( session["id"], decision="rejected", note="Approval request expired after 4 hours without response.", ) elif age > 3600 and not session.get("escalated"): slack_sender.escalate(session) store.mark_escalated(session["id"]) elif age > 900 and not session.get("reminded"): slack_sender.remind(session) store.mark_reminded(session["id"])
Keep the history of timed-out sessions — don't delete them. Being able to explain afterward "why this transaction was never executed" is critical for compliance. Thresholds are tied to business hours, so extending the Hard timeout to "10 AM the next business day" outside working hours reduces failures substantially. If your operation spans time zones, consider attaching each gate to an on-call rotation rather than a fixed business calendar — the rotation already answers the question "who owns this request right now?"
Three Production Failure Patterns to Know
Below are three failure patterns I have either hit myself or seen during reviews. They are worth memorizing because each one produced real incidents in production, not hypothetical edge cases.
Pattern 1: Privilege Escalation — A Different Tool Fires After Approval
You approve payment A, and when the session resumes, Claude decides to "also" run payment B automatically in the next turn. Claude tends to expand context from the conversation flow, so you need a rule that forbids executing any operation other than the approved tool_use_id within that turn.
The fix is simple but must be enforced: every tool_use returned after resume_after_approval appends a tool_result is re-evaluated by needs_approval. Do not build an implicit "we just approved, so the next one is safe" assumption. Practically, keep needs_approval a pure, stateless function, and do not maintain a per-session set of "already approved tools" that gets carried forward. A related discipline: write a test that specifically tries to trick the function — "we just approved send_money at ¥5,000; does the next call to send_money at ¥6,000 still trigger the gate?" If it doesn't, your implementation has quietly become state-dependent.
Pattern 2: Double Execution — The Approval Button Gets Spammed
If a user double-clicks a Slack button, or a network retry delivers the same approval event twice, you can easily run the same tool twice. For payments or charging, that's fatal — a retried approval event is exactly how one transfer becomes two.
The mitigation combines "idempotency tokens" and "state-transition locks." resume_after_approval transitions from status = awaiting_approval to status = running using CAS (compare-and-swap); subsequent requests do nothing and return 409. In Redis use SET NX; in Postgres use UPDATE ... WHERE status = 'awaiting_approval' RETURNING id. On the Slack side, flipping the button UI to a "processing" state immediately prevents accidental re-clicks and improves the user experience noticeably. For email approval, render the result page server-side so a refresh or a second click on the same link naturally short-circuits on the CAS check rather than reaching the tool.
Pattern 3: State Divergence — The External System Times Out After Approval
Approval comes in, the tool executes, the external API times out on your side, but the server actually completed the operation. Classic example: a payment provider takes over 30 seconds, the client retries after a timeout, and you end up double-charging because the first call succeeded on the server.
This is a distributed-systems problem more than a HITL one, but in agent contexts the rule is absolute: every external API call must carry an idempotency key. Use Stripe's Idempotency-Key header if it's available; otherwise derive your own key from session_id + tool_use_id. Because tool_use_id is assigned by Claude per call, resuming the same approval any number of times yields the same key. One more detail worth internalizing: after a timeout, do not auto-resume; surface "this tool call is in an unknown state" to a human and let them decide, because a blind retry can compound the problem rather than resolve it.
A Symptom-First Triage Table for Resume Errors
Once gates are in place, most bugs show up not where you stop but where you resume. These are the ones I've hit myself or seen in review, ordered so you can look them up by symptom.
Symptom
Likely cause
How to check
Fix
Resume call returns 400 with "tool_use ids were found without tool_result blocks immediately after"
Results returned for only some tool_use blocks in the turn, or a text block placed before the tool_result blocks
Compare the ids in the saved pending.tool_uses against the tool_use_id values you're sending
Return a result for every id in the stopped turn; put tool_result blocks first in the user turn's content
From December 2026, the first call of every session fails
A hard-coded retired model ID (claude-sonnet-4-5-20250929 was retired on 2026-11-30)
Look at the model value on the failing requests in your logs
Move the model ID into configuration, switch to the replacement (such as claude-sonnet-5-5), then rerun the gate tests
Saving fails with TypeError: Object of type ToolUseBlock is not JSON serializable
resp.content (SDK objects) appended to messages as-is
Run json.dumps(messages) on its own
Convert blocks with model_dump() before appending
After a truncated reply, a 400 on an empty user turn
stop_reason was max_tokens but the code took the tool branch
Check stop_reason on the last saved assistant turn
Enter the tool branch only on tool_use; for max_tokens, raise the limit or ask for continuation
Slack shows the button as failed, or the same click arrives twice
Waiting for the work to finish instead of returning 200 within three seconds
Check response times on the Request URL
Return 200 immediately, resume in a queue worker, and gate the state transition with CAS
An email approval is finalized with no one having acted
A mail-security product or preview opened the link first
Compare approval time to delivery time and check the User-Agent
GET shows a confirmation page only; finalize on POST
The session is paused after an approval, but no one was notified
The resume path passes a no-op as on_approval_required
Count awaiting_approval sessions with no notification history
Pass the notifier into the resume function too, so stopping and notifying stay paired
The error in the first row is also covered in the official "Troubleshooting tool use" docs. In my case, that 400 came from returning a result for the rejected call while forgetting the call that had been stopped alongside it.
Designing Audit Logs That Survive Compliance Review
The biggest side benefit of HITL is that you naturally end up with a complete log of "who approved or rejected what, and when." Making that log usable as a compliance artifact requires a small amount of intentional design.
At minimum, record:
The approval target's tool name, input parameters, and Claude's reasoning (the full tool_use block)
The approver's ID and email address (Slack user_id alone is hard to trace later)
The approver's justification (always include a free-form comment field)
Decision timestamp (trust the server-side clock)
Claude's model name and version at the time (so you can correlate behavior changes later)
The trace ID tied to the request (your connection point to distributed tracing)
Ideally, you write these to an append-only store. In PostgreSQL, add rules that logically forbid deletes and updates; in regulated industries, you may need to persist to WORM (Write Once Read Many) storage.
Mask personally identifiable input data or keep encryption keys behind access control. If the approval log itself contains too much of what it reviews, a log leak becomes a secondary incident. Finally, build a weekly auto-summary (counts, approver distribution, per-tool ratios) from day one — it gives auditors and external reviewers a view they can actually use, and it saves you from scrambling when someone asks for a report months later. A small investment here has outsized value when a compliance audit lands with a two-week deadline.
Observability — Can You See That the Gates Are Working?
After adding approval gates, you need to measure whether they're actually doing their job. A common outcome is that the gate is shipped, nobody is watching the numbers, and six months later you discover it hasn't been firing correctly — perhaps a refactor removed a needs_approval check silently, or the threshold got changed for a load test and never reset.
These are the metrics I always track:
Gate firing rate: Of all tool calls, what fraction requested approval?
Approve / reject / timeout distribution: Where do decisions land?
Time to decision (P50 and P95): How quickly do operators respond?
Rejection reasons, categorized: Use frequent reasons to justify threshold adjustments or tool redesigns.
Re-approval requests within the same session: If high, Claude is failing to understand the rejection reasons.
Review these weekly to decide when to revisit Yellow thresholds, what areas can be pushed further toward automation, and whether you need to raise a gate you previously relaxed. Hook an anomaly detector onto the firing rate as a lagging safety net: if that rate suddenly halves from one day to the next, something in your classification logic has probably regressed, even if no code change was intentional.
Start Small — A Three-Step Rollout for Existing Agents
Retrofitting HITL onto a running agent will stall if you try to be perfect from day one. The incremental path I recommend:
Step 1 — Shadow mode: Run the gate logic, but don't actually stop anything. Just log "would this have required approval?" Run for one week to measure real volumes. If you exceed 50 per week, revisit threshold design.
Step 2 — Red-only gate ON: Enable real approval for one or two of your most dangerous tools (payments, outbound emails). Hold sessions during the operator's ramp-up period — budget one to two weeks.
Step 3 — Yellow threshold tuning: Tune amount or count thresholds against real production data. Reviewing one "didn't need approval" and one "should have approved" case per week is enough to sharpen the thresholds quickly.
Going through these three steps surfaces facts like "Shadow mode showed far more approvals than we expected" before they become operational problems. Flipping the gate ON all at once in production tends to create approval fatigue within the first few hours, and the operation grinds to a halt.
When I added a gate to a small helper script that handles Stripe refunds, I started with "every refund is Red." A week of Shadow logs showed that nearly all of them were small reversals of duplicate charges — nothing I'd ever decide differently. It didn't go well: I'd started dreading reading the log at all. These days Yellow is cut on two things, the amount and whether the same customer had a recent refund, and Red is reserved for refunds with an empty reason field. I've written about the counting stage in more depth in measuring accuracy with zero production impact using shadow mode.
If you're on the Agent SDK, you don't need to write this loop yourself. As the official permissions and user-input docs describe, the permission callback that runs before a tool executes (can_use_tool in Python, canUseTool in TypeScript) or a PreToolUse hook can host the same check as needs_approval above. For approvals that may take hours, though, I'd rather persist and exit as shown here than block inside the callback — it survives process restarts far better.
Where You'll Get Stuck Next — Returning an "Approve With Edits"
Once gates are running, a reviewer will almost certainly say, "Just fix the amount and let it through." The temptation is to rewrite tool_use.input in the saved assistant turn. I don't. Rewriting history means the audit log can no longer tell what Claude proposed from what actually ran.
Instead, run the real tool with the edited input and tell Claude what happened in the tool_result body.
# approve_with_edit.py# Goal: tell Claude a reviewer edited the arguments, without rewriting historyimport jsonfrom agent_loop import run_tooldef result_for_edited_approval(tu: dict, edited_input: dict, approver: str) -> dict: output = run_tool(tu["name"], edited_input) changed = {k: {"from": tu["input"].get(k), "to": v} for k, v in edited_input.items() if tu["input"].get(k) != v} return { "type": "tool_result", "tool_use_id": tu["id"], "content": json.dumps({ "executed_with_human_edits": True, "approver": approver, "changed_fields": changed, "output": json.loads(output), }), }
Claude can then write the customer-facing explanation knowing the amount changed, and the audit log keeps both the original and the edited input. Use this only in the approved branch of resume_after_approval when an edit comes in, and the rest of the code barely changes.
To make sure gate decisions don't shift after a model swap, find every caller first — the steps in counting Sonnet 4.5 callers from the Usage CSV work well — and then rerun the multi-call test from earlier.
Your Next Step
Write down every tool your agent can call today and color each one Red, Yellow, or Green along irreversibility, blast radius, and amount. Once that single sheet exists, the comparison table above tells you where the gates go, and the maximum wait time becomes an operating agreement rather than a constant buried in code.
Not stopping, but deciding who resumes and how after you stop — putting that on one sheet before writing code is the one order of work I keep on every project.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.