1How do I keep a person in charge of the actions that cannot be undone?
The agent does the routine work alone. When it proposes an action from a list you wrote, such as a payment or a deletion, the run pauses and its state is saved. A named person sees the exact call and approves, edits or rejects it. The run then resumes from the saved state, hours later if needed.
You may need it if
- Most of the agent's steps are harmless, but a few move money, delete data or contact customers.
- Policy or regulation says a named person must sign off on certain actions.
- The person who can decide is not watching the run and may answer hours later.
2When does asking a person stop being a control?
Use it when
- A short written list separates the few actions that need a person from the many that do not.
- Someone with the authority to decide can be reached, and waiting minutes or hours for them is acceptable.
- You can store a paused run durably and start it again from where it stopped.
- The approver may need to correct the call, not only say yes or no.
Avoid it when
- People would approve nearly every request. A gate that almost always says yes turns into clicking through.
Use Trusted Monitoring instead - The effects can be previewed and a written policy is enough to judge them. No person has to answer for the action.
Use Dry Run instead - The risk lies in what an answer says, not in an action on a system.
Use Metacognitive Triage instead - The run is unattended or must finish in seconds. Nobody is there to answer, so every gated action ends as a timeout.
What it costs
- Model calls
- The agent's own calls. The gate adds none, only waiting time.
- Latency
- high
- Complexity
- medium
3What happens to the run while the person decides?
A tool loop with a checkpoint on one branch. A rule sorts each proposed call. Routine calls run at once. A gated call saves the run and waits for a person, who approves, edits or rejects. Approved calls run and the loop goes on. A rejection ends the run through a separate exit.
- Step 1 of 7
Routine calls run without a person
A customer asks for a refund of 380 euros on order 4417. The agent first looks up the order. Reading is not on the approval list, so the call runs at once and the result comes back.
- Step 2 of 7
The agent proposes a gated call
It now proposes a refund of 380 euros. The rule finds refunds on the list. The rule is plain code. The agent does not choose whether to ask.
- Step 3 of 7
The run is saved and stops
The task, the lookup already made and the pending refund are written to the checkpoint. The process can end. The approver receives the exact call with its arguments.
- Step 4 of 7
The person decides, three hours later
The approver sees that 30 euros of shipping are not refundable. She changes the amount to 350 and approves. She could also have approved the call as it was.
- Step 5 of 7
The run resumes from the checkpoint
A new process reloads the saved state and issues the refund with the approved amount. The result goes back to the agent, which carries on where it stopped.
- Step 6 of 7
The work ends with a record
The agent writes the confirmation and finishes. The record lists each call and, for the refund, who approved it and what she changed.
- Step 7 of 7
Or the person says no
Had she rejected the refund, the run would end there with her reason. The lookup stays in the record. No refund was issued.
What each part does
- Task
- What the user wants done, or an action or plan already written by an earlier stage.
- Agent
- Works on the task and proposes tool calls one at a time. It cannot run a gated call itself.
- Needs approval?
- Compares each proposed call with the approval list. Applied outside the agent, so the agent cannot skip it.
- Checkpoint
- Durable copy of the paused run: the task, the calls made so far and the pending call.
- Approver
- A named person with the authority to decide. Approves the call, edits its arguments or rejects it.
- Tools
- Runs routine calls at once, and gated calls only with the arguments the approver accepted.
- Executed
- The record of the calls that ran, with who approved each gated one.
- Rejected
- The refusal, with the approver's reason. The refused call did not run.
- Agent → Needs approval?: proposes a call
- Agent → Executed: work finished
- Needs approval? → Tools: routine call
- Needs approval? → Approver: gated call, run pauses
- Needs approval? → Checkpoint: saves the paused run
- Checkpoint → Tools: state reloaded on resume
- Approver → Tools: approves or edits
- Approver → Rejected: rejects
- Tools → Agent: result
Where it connects
A task whose steps may include consequential actions, or an action or plan written by an earlier stage. The approval list is already configured.
When: The agent finished, and every gated call that ran was approved by a person.
The calls that ran with their results. For each gated call, the approver, the time of the decision and any change to the arguments.
When: The approver rejected a gated call, or no decision came before the deadline.
The refused call, the approver and the reason, plus the calls that ran before the gate. Confirms the refused call did not run.
The paused run, made of the task, the calls already made and the pending call. Kept in durable storage until the decision arrives, then no longer needed.
4What do I ask my assistant to set up?
The agents to launch
Worker
Carry out the task with the listed tools. Propose one call at a time with complete arguments. Some calls are held for a person's approval. When a call comes back with changed arguments, accept the change and continue. When the work is done, report what was done.
Sees: The task, the tool list and the results of the calls that ran. Not the approval list, and not the approver's identity.
Gatekeeper
Compare one proposed call with the approval list. Answer "needs approval" or "routine", and name the rule that matched. If no rule matches, answer "needs approval". Do not judge whether the action is a good idea. When the list is a plain set of tool names, replace this agent with code.
Sees: The proposed call with its arguments, and the approval list. Not the task and not the worker's reasoning.
A prompt you can paste
Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.
You are the orchestrator of a multi-agent workflow that follows the "Human Approval Gate" architecture. Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it. # Task [Describe your task here] # Human Approval Gate Pause before a consequential action until a named person decides. Input: the task above. It must provide: A task whose steps may include consequential actions, or an action or plan written by an earlier stage. The approval list is already configured. If something essential is missing, ask for it before starting. Agents to launch: - Worker: Carry out the task with the listed tools. Propose one call at a time with complete arguments. Some calls are held for a person's approval. When a call comes back with changed arguments, accept the change and continue. When the work is done, report what was done. Context for this agent: The task, the tool list and the results of the calls that ran. Not the approval list, and not the approver's identity. - Gatekeeper: Compare one proposed call with the approval list. Answer "needs approval" or "routine", and name the rule that matched. If no rule matches, answer "needs approval". Do not judge whether the action is a good idea. When the list is a plain set of tool names, replace this agent with code. Context for this agent: The proposed call with its arguments, and the approval list. Not the task and not the worker's reasoning. Procedure: 1. Write the approval list, made of the tools, or the conditions on their arguments, that need a person. Name who may approve each kind. 2. Launch the worker on the task. If the input already contains an exact action, treat it as the first proposed call. 3. For each proposed call, have the gatekeeper compare it with the list. Run routine calls at once and return the result to the worker. 4. For a gated call, save the task, the calls made so far and the pending call. Show the approver the exact call with its arguments, then stop. 5. When the decision arrives, reload the saved state. Run the call as approved or as edited, record who decided, and continue the worker from there. 6. On a rejection, or after 24 hours without a decision, end the run with the refused call and the reason. Execute nothing more. Stop rule: Stop when the worker finishes, at the first rejection, or after 8 tool calls. A request left unanswered for 24 hours counts as a rejection. Exits: - `executed`, when: The agent finished, and every gated call that ran was approved by a person. Deliver: The calls that ran with their results. For each gated call, the approver, the time of the decision and any change to the arguments. - `rejected`, when: The approver rejected a gated call, or no decision came before the deadline. Deliver: The refused call, the approver and the reason, plus the calls that ran before the gate. Confirms the refused call did not run. # Final deliverable Either the record of the calls that ran, with the approver and any edit for each gated call, or the refusal with the call, who rejected it and why. Label it executed or rejected.
The same thing in code
import operator
import time
import uuid
from typing import Annotated, Literal, TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt
from pydantic import BaseModel
MAX_CALLS = 8
TTL_SECONDS = 24 * 3600
GATED = {"issue_refund"} # the approval list: applied by code, never by the agent
ASKED_AT: dict[str, float] = {}
WORKER = ("Carry out the task with the tools lookup_order and issue_refund. Propose one call at a time with "
"complete arguments. Some calls are held for a person's approval. When the work is done, set action "
"to finish and report what was done.")
class Step(BaseModel):
action: Literal["call", "finish"]
tool: Literal["lookup_order", "issue_refund"]
order_id: str
amount: float # issue_refund only
text: str # finish: the report
class State(TypedDict):
task: str
step: dict
log: Annotated[list[str], operator.add]
status: str
reasons: str
model = init_chat_model("anthropic:claude-sonnet-5-5")
def execute(call: dict) -> str:
if call["tool"] == "lookup_order":
return "stub: order summary" # plug in a read-only client
return "stub: refund issued" # the only code holding write credentials
async def agent(state: State) -> dict:
prompt = f"Task: {state['task']}\n\nCalls so far:\n" + "\n".join(state["log"])
raw = await model.with_structured_output(Step).ainvoke([SystemMessage(WORKER), HumanMessage(prompt)])
step = Step.model_validate(raw)
if step.action == "finish" or len(state["log"]) >= MAX_CALLS:
return {"step": step.model_dump(), "status": "executed"}
return {"step": step.model_dump()}
def approval(state: State) -> dict:
call = state["step"]
if call["tool"] not in GATED:
return {} # routine call: no person needed
# the run stops here; the checkpointer keeps the state under the thread id until someone resumes it
decision = interrupt({"question": "Approve this call?", "call": call, "calls_so_far": state["log"]})
if decision["action"] == "reject":
return {"status": "rejected", "reasons": f"{decision['approver']}: {decision.get('reason', '')}"}
if decision["action"] == "edit":
call = {**call, "amount": decision["amount"]}
return {"step": {**call, "approved_by": decision["approver"]}}
def tools(state: State) -> dict: # side effects live here, after the decision
call = state["step"]
by = f" [approved by {call['approved_by']}]" if "approved_by" in call else ""
return {"log": [f"{call['tool']}({call['order_id']}, {call['amount']}) -> {execute(call)}{by}"]}
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("approval", approval)
builder.add_node("tools", tools)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", lambda s: END if s["status"] else "approval", ["approval", END])
builder.add_conditional_edges("approval", lambda s: END if s["status"] else "tools", ["tools", END])
builder.add_edge("tools", "agent")
graph = builder.compile(checkpointer=InMemorySaver()) # use a database-backed checkpointer in production
def report(state: dict, thread_id: str) -> dict:
pending = state.get("__interrupt__")
if pending: # paused at the gate: show the request to the approver, then call resume()
ASKED_AT[thread_id] = time.time()
return {"status": "pending", "thread_id": thread_id, "request": pending[0].value}
if state["status"] == "rejected":
return {"status": "rejected", "refused": state["step"], "reasons": state["reasons"], "calls": state["log"]}
return {"status": "executed", "report": state["step"]["text"], "calls": state["log"]}
async def run(task: str) -> dict:
thread_id = str(uuid.uuid4())
start: State = {"task": task, "step": {}, "log": [], "status": "", "reasons": ""}
return report(await graph.ainvoke(start, {"configurable": {"thread_id": thread_id}}), thread_id)
async def resume(thread_id: str, decision: dict) -> dict:
# decision: {"action": "approve" | "edit" | "reject", "approver": name, "amount": ..., "reason": ...}
if time.time() - ASKED_AT.pop(thread_id, 0.0) > TTL_SECONDS:
decision = {"action": "reject", "approver": "deadline", "reason": "no decision within 24 hours"}
state = await graph.ainvoke(Command(resume=decision), {"configurable": {"thread_id": thread_id}})
return report(state, thread_id)
run() returns a pending request when the gate is hit; resume() continues the same thread. The approval node runs again from its start on resume, so it holds no side effect.
import time
import uuid
from typing import Literal
from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, query
from pydantic import BaseModel
MAX_CALLS = 8
TTL_SECONDS = 24 * 3600
GATED = {"issue_refund"} # the approval list: applied by code, never by the agent
CHECKPOINTS: dict[str, dict] = {} # use a database: the process may end while the person decides
WORKER = ("Carry out the task with the tools lookup_order and issue_refund. Propose one call at a time with "
"complete arguments. Some calls are held for a person's approval. When the work is done, set action "
"to finish and report what was done.")
class Step(BaseModel):
action: Literal["call", "finish"]
tool: Literal["lookup_order", "issue_refund"]
order_id: str
amount: float # issue_refund only
text: str # finish: the report
def execute(step: Step) -> str:
if step.tool == "lookup_order":
return "stub: order summary" # plug in a read-only client
return "stub: refund issued" # the only code holding write credentials
async def next_step(task: str, log: list[str]) -> Step:
# the worker only proposes; it holds no tool that can execute
options = ClaudeAgentOptions(
system_prompt=WORKER,
output_format={"type": "json_schema", "schema": Step.model_json_schema()},
)
async for msg in query(prompt=f"Task: {task}\n\nCalls so far:\n" + "\n".join(log), options=options):
if isinstance(msg, ResultMessage):
return Step.model_validate(msg.structured_output)
raise RuntimeError("no result")
async def advance(task: str, log: list[str]) -> dict:
while len(log) < MAX_CALLS:
step = await next_step(task, log)
if step.action == "finish":
return {"status": "executed", "report": step.text, "calls": log}
if step.tool in GATED: # the gate: save the run and stop; nothing waits in memory
run_id = str(uuid.uuid4())
CHECKPOINTS[run_id] = {"task": task, "log": log, "pending": step.model_dump(), "asked_at": time.time()}
return {"status": "pending", "run_id": run_id, "request": step.model_dump()} # show this to the approver
log.append(f"{step.tool}({step.order_id}) -> {execute(step)}") # routine call: runs at once
return {"status": "executed", "report": "Call limit reached before the work was finished.", "calls": log}
async def run(task: str) -> dict:
return await advance(task, [])
async def resume(run_id: str, approver: str, decision: Literal["approve", "edit", "reject"],
amount: float | None = None, reason: str = "") -> dict:
saved = CHECKPOINTS.pop(run_id) # reload the paused run
step = Step.model_validate(saved["pending"])
if time.time() - saved["asked_at"] > TTL_SECONDS:
decision, reason = "reject", "no decision within 24 hours"
if decision == "reject": # the refused call never runs
return {"status": "rejected", "refused": saved["pending"], "by": approver, "reasons": reason, "calls": saved["log"]}
if decision == "edit" and amount is not None:
step = step.model_copy(update={"amount": amount}) # the person corrected the arguments
done = f"{step.tool}({step.order_id}, {step.amount}) -> {execute(step)} [approved by {approver}]"
return await advance(saved["task"], saved["log"] + [done])
The gate is plain code around a worker that only proposes. The SDK's can_use_tool callback can also ask a person, but it holds the run open while they decide.
import time
import uuid
from typing import Literal
from agents import Agent, Runner
from pydantic import BaseModel
MAX_CALLS = 8
TTL_SECONDS = 24 * 3600
GATED = {"issue_refund"} # the approval list: applied by code, never by the agent
CHECKPOINTS: dict[str, dict] = {} # use a database: the process may end while the person decides
class Step(BaseModel):
action: Literal["call", "finish"]
tool: Literal["lookup_order", "issue_refund"]
order_id: str
amount: float # issue_refund only
text: str # finish: the report
worker = Agent(
name="Worker", output_type=Step,
instructions="Carry out the task with the tools lookup_order and issue_refund. Propose one call at a time "
"with complete arguments. Some calls are held for a person's approval. When the work is done, "
"set action to finish and report what was done.")
def execute(step: Step) -> str:
if step.tool == "lookup_order":
return "stub: order summary" # plug in a read-only client
return "stub: refund issued" # the only code holding write credentials
async def advance(task: str, log: list[str]) -> dict:
while len(log) < MAX_CALLS:
# the worker only proposes; it holds no tool that can execute
out = await Runner.run(worker, f"Task: {task}\n\nCalls so far:\n" + "\n".join(log))
step = out.final_output_as(Step)
if step.action == "finish":
return {"status": "executed", "report": step.text, "calls": log}
if step.tool in GATED: # the gate: save the run and stop; nothing waits in memory
run_id = str(uuid.uuid4())
CHECKPOINTS[run_id] = {"task": task, "log": log, "pending": step.model_dump(), "asked_at": time.time()}
return {"status": "pending", "run_id": run_id, "request": step.model_dump()} # show this to the approver
log.append(f"{step.tool}({step.order_id}) -> {execute(step)}") # routine call: runs at once
return {"status": "executed", "report": "Call limit reached before the work was finished.", "calls": log}
async def run(task: str) -> dict:
return await advance(task, [])
async def resume(run_id: str, approver: str, decision: Literal["approve", "edit", "reject"],
amount: float | None = None, reason: str = "") -> dict:
saved = CHECKPOINTS.pop(run_id) # reload the paused run
step = Step.model_validate(saved["pending"])
if time.time() - saved["asked_at"] > TTL_SECONDS:
decision, reason = "reject", "no decision within 24 hours"
if decision == "reject": # the refused call never runs
return {"status": "rejected", "refused": saved["pending"], "by": approver, "reasons": reason, "calls": saved["log"]}
if decision == "edit" and amount is not None:
step = step.model_copy(update={"amount": amount}) # the person corrected the arguments
done = f"{step.tool}({step.order_id}, {step.amount}) -> {execute(step)} [approved by {approver}]"
return await advance(saved["task"], saved["log"] + [done])
The gate is plain code around a worker that only proposes. The SDK also documents built-in tool approvals with a serialisable run state; this skeleton does not use them.
import { anthropic } from '@ai-sdk/anthropic';
import { generateText, Output } from 'ai';
import { z } from 'zod';
const MAX_CALLS = 8;
const TTL_MS = 24 * 3600 * 1000;
const GATED = new Set(['issue_refund']); // the approval list: applied by code, never by the agent
const model = anthropic('claude-sonnet-5-5');
const stepSchema = z.object({
action: z.enum(['call', 'finish']),
tool: z.enum(['lookup_order', 'issue_refund']),
orderId: z.string(),
amount: z.number().describe('issue_refund only'),
text: z.string().describe('finish: the report'),
});
type Step = z.infer<typeof stepSchema>;
type Paused = { task: string; log: string[]; pending: Step; askedAt: number };
type Decision = { action: 'approve' | 'edit' | 'reject'; approver: string; amount?: number; reason?: string };
const checkpoints = new Map<string, Paused>(); // use a database: the process may end while the person decides
async function execute(step: Step): Promise<string> {
if (step.tool === 'lookup_order') return 'stub: order summary'; // plug in a read-only client
return 'stub: refund issued'; // the only code holding write credentials
}
async function advance(task: string, log: string[]) {
while (log.length < MAX_CALLS) {
// the worker only proposes; it holds no tool that can execute
const { output: step } = await generateText({
model,
instructions:
'Carry out the task with the tools lookup_order and issue_refund. Propose one call at a time with ' +
"complete arguments. Some calls are held for a person's approval. When the work is done, set action " +
'to finish and report what was done.',
prompt: `Task: ${task}\n\nCalls so far:\n${log.join('\n')}`,
output: Output.object({ schema: stepSchema }),
});
if (step.action === 'finish') return { status: 'executed', report: step.text, calls: log };
if (GATED.has(step.tool)) { // the gate: save the run and stop; nothing waits in memory
const runId = crypto.randomUUID();
checkpoints.set(runId, { task, log, pending: step, askedAt: Date.now() });
return { status: 'pending', runId, request: step }; // show this to the approver
}
log.push(`${step.tool}(${step.orderId}) -> ${await execute(step)}`); // routine call: runs at once
}
return { status: 'executed', report: 'Call limit reached before the work was finished.', calls: log };
}
export async function run(task: string) {
return advance(task, []);
}
export async function resume(runId: string, decision: Decision) {
const saved = checkpoints.get(runId); // reload the paused run
if (!saved) throw new Error(`unknown run: ${runId}`);
checkpoints.delete(runId);
const late = Date.now() - saved.askedAt > TTL_MS;
if (late || decision.action === 'reject') { // the refused call never runs
const reasons = late ? 'no decision within 24 hours' : decision.reason ?? '';
return { status: 'rejected', refused: saved.pending, by: decision.approver, reasons, calls: saved.log };
}
const amount = decision.action === 'edit' && decision.amount !== undefined ? decision.amount : saved.pending.amount;
const step = { ...saved.pending, amount }; // the person may have corrected the arguments
const done = `${step.tool}(${step.orderId}, ${step.amount}) -> ${await execute(step)} [approved by ${decision.approver}]`;
return advance(saved.task, [...saved.log, done]);
}
The gate is plain code around a worker that only proposes. The SDK also documents a tool approval setting; this skeleton does not use it.
Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.
What goes wrong
- Gating too much trains approvers to click yes. Keep the list short and check how often each entry is ever rejected.
- If the agent decides when to ask, it can also decide not to. The list is applied by code outside the agent.
- A summary written by the agent lets it frame its own request. Show the approver the exact call and its arguments.
- In some frameworks, the step that paused runs again from its start on resume. Keep side effects after the decision, or make them safe to repeat.
- A checkpoint held in memory is lost when the process ends, and the pending approval with it. Store it in a database.