8 min readRishi

Approval Sits Between tool_use and tool_result

Approval Sits Between tool_use and tool_result

The agent emitted bash with rm -rf tmp/export. Your UI froze the call and asked the operator. The operator typed "don't". Your loop appended that string as a user message, then later sent a tool_result for the bash id. The next messages.create was a 400. The branch that "cancelled" by dropping the assistant turn was quieter: the request succeeded, the model had no record of the denial, and it emitted the same rm on the following turn. Approval is not a chat message. It is a pause inside an already-open tool_use / tool_result pair. The pair closes only when every id from that turn has a result — including the ids you refused to run.

The basic loop already tells you to return failures as tool_result with is_error. The pairing rule already tells you not to orphan an id. This post is the gap those two assume is empty: a human, a process restart, or a timeout sitting between the call and the result.

The pair is already open

stop_reason is tool_use. You have appended the assistant message. The next user message the API will accept is the results for every tool_use block in that message, and only those ids. Nothing else is legal in that slot: not the operator's "don't", not the user's next question, not a system reminder. Local work is fine — inspect arguments, run the safe tools, wait on a button, write the pending turn to disk. None of that is a Messages API call.

If that assistant turn also carried thinking blocks, they stay on the assistant message you persist. Pausing for a human does not let you strip thinking or redacted_thinking. The signature still has to round-trip on the request that finally includes the results.

Do not execute from a partial stream. Streaming can show a tool_use name before input is valid JSON. An approval UI that fires on content_block_start asks a human to bless arguments you do not have yet. Wait for content_block_stop or message_stop before you treat the call as real.

Split the tools. Do not split the user turn.

One assistant message can mix a cheap read with a gated write. Parallel tool use is on by default:

# two blocks, one response
# read_file  id=toolu_01Read  path=tmp/export/manifest.json
# bash       id=toolu_01Bash  command=rm -rf tmp/export

read_file can run immediately. bash waits on the operator. That split is a local schedule. It is not two user messages.

from dataclasses import dataclass, field

SAFE = {"read_file", "grep", "list_dir"}
GATED = {"bash", "write_file", "delete_file"}

@dataclass
class PendingTurn:
    assistant_content: list
    results: dict = field(default_factory=dict)
    waiting: set = field(default_factory=set)

    def close(self) -> list:
        missing = [
            b["id"] for b in self.assistant_content
            if b.get("type") == "tool_use" and b["id"] not in self.results
        ]
        if missing:
            raise RuntimeError(f"unclosed tool ids: {missing}")
        return [
            self.results[b["id"]]
            for b in self.assistant_content
            if b.get("type") == "tool_use"
        ]

def start_pending(assistant_content: list) -> PendingTurn:
    pending = PendingTurn(assistant_content=assistant_content)
    for block in assistant_content:
        if block.get("type") != "tool_use":
            continue
        if block["name"] in SAFE:
            pending.results[block["id"]] = {
                "type": "tool_result",
                "tool_use_id": block["id"],
                "content": run_tool(block["name"], block["input"]),
            }
        elif block["name"] in GATED:
            pending.waiting.add(block["id"])
        else:
            pending.results[block["id"]] = deny(
                block["id"], f"Unknown tool {block['name']}. Do not retry it."
            )
    return pending

close() is the only path that appends a user message. If bash is still waiting, you do not call messages.create. Sending the read_file result now, "so the model can keep working," orphans toolu_01Bash. Sending bash later as a second user message does not repair that.

Unknown tools belong in deny, not in an exception that aborts the whole turn. An exception leaves the pair open. A result closes it.

A denial is a result, not a missing result

def deny(tool_use_id: str, reason: str) -> dict:
    return {
        "type": "tool_result",
        "tool_use_id": tool_use_id,
        "is_error": True,
        "content": reason,
    }

def on_operator_decision(pending: PendingTurn, tool_use_id: str, approved: bool) -> None:
    block = next(b for b in pending.assistant_content if b.get("id") == tool_use_id)
    if approved:
        pending.results[tool_use_id] = {
            "type": "tool_result",
            "tool_use_id": tool_use_id,
            "content": run_tool(block["name"], block["input"]),
        }
    else:
        pending.results[tool_use_id] = deny(
            tool_use_id,
            "Denied by the operator. Do not retry this command. "
            "Ask for a narrower command, or explain which files you need read-only.",
        )
    pending.waiting.discard(tool_use_id)

The denial has to name the constraint. Denied. teaches the model nothing, so the next turn is the same bash with a space changed. Denied: do not delete tmp/export. List the files you wanted removed. is an error the model can recover from, which is the point of is_error in the tool-use post.

Dropping the assistant turn to "cancel" is the other attractive bug. The transcript is then structurally valid. You did not 400. You also threw away the only evidence of what the model tried, including thinking. The following request looks like the original user question again. Models retry. Close the pair with a denial so the retry has something to read.

Do not execute and then ask. Once rm has returned, the operator's "don't" is a comment on a mutation that already happened. The approval UI is a gate in front of run_tool, not a notification after it. If the workflow must delete, that delete belongs in code after a structured confirm, not in a free-form bash the model invented.

The operator typed during the pause

The UI is a chat box. People type in chat boxes. During a pending turn, incoming text is input to the denial or the queue, not a user message you append.

def on_user_text(pending: PendingTurn | None, messages: list, text: str) -> None:
    if pending is None:
        messages.append({"role": "user", "content": text})
        return
    if len(pending.waiting) == 1:
        tool_use_id = next(iter(pending.waiting))
        pending.results[tool_use_id] = deny(
            tool_use_id,
            f"Denied by the operator: {text}. Do not retry the denied command.",
        )
        pending.waiting.clear()
        return
    raise RuntimeError("bind this text to a specific tool_use_id, or queue it")

If two gated tools are waiting, do not guess which id the sentence belongs to. Require the UI to bind Approve/Deny to a specific tool_use_id. A free-text "don't" with two pending writes is how you deny the wrong one and run the other.

A new question while bash is waiting — "also check the staging folder" — is the same class of event. Queue it. Append it only after the results user turn is on messages and the loop has seen end_turn. The API does not have a side channel for "the human is talking while tools are in flight."

If the operator pasted a ticket body as the denial reason, do not promote that body into the system prompt. It is tool_result content.

The process died in the gap

Approval can take minutes. Your request handler will not. Persist the pending turn before you return 202 to the UI: assistant content, results you already have, waiting ids, and the rest of messages. On boot, if waiting is non-empty, restore the UI from those arguments — show the bash command, not a blank composer. Do not call messages.create until close() succeeds. A restart that "starts a fresh chat" is the dropped-assistant-turn bug with a longer outage in the middle: the model never saw the denial, and the rm is still a tool.

Timeouts are denials you write yourself. An operator who has not clicked in ten minutes has not approved:

def on_timeout(pending: PendingTurn) -> None:
    for tool_use_id in list(pending.waiting):
        pending.results[tool_use_id] = deny(
            tool_use_id,
            "Timed out waiting for operator approval. The command did not run. "
            "Do not retry unless the user asks again.",
        )
        pending.waiting.discard(tool_use_id)

Leaving the pair open "until they come back" means the next event on that session — a new question, a compaction pass, a second tab — hits the same 400. Close it. If they later say "yes, delete it," that is a new user turn with a new tool_use id.

What belongs in the gate

EventAppend to messages?What you do
Safe tool in a mixed turnNo, not yetRun it, store the result on PendingTurn
Gated tool, operator approvesNo, not yetRun it, store the result
Gated tool, operator deniesNo, not yetStore is_error result, same id
Operator types during waitNoBind to an id as a denial, or queue
TimeoutNo, not yetStore a timeout denial for every waiting id
All ids have resultsYes, onceOne user message, close() order
Drop assistant turn to "cancel"Do notYou taught the model nothing; it will retry

The gate is an allowlist of tool names, plus a check on arguments for the tools you do allow. bash with ls tmp/export and bash with rm -rf tmp/export are the same tool name. If your product cannot distinguish those, do not expose bash. Expose list_export_dir and a delete that takes one path, and confirm that path in the UI. A system prompt that says "never delete" is not a gate. The model already emitted the call. Your code is the only thing that can not run it.

When every successful run must ask a human before a mutation, put that confirm in the program. The model can draft the path list; the program shows it, waits, then deletes. That is the workflow-in-code split. This pause is the remaining case: you exposed a gated tool, the model called it, and you now owe the API a result for an id that must not become a side effect.

Keep reading

Newsletter

New posts, straight to your inbox

One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.

Comments

  • No comments yet. Be the first.