Skip to content

Human-in-the-Loop

The analyst plans to run a query on the analytics replica, and its run_query tool needs approval. Then it has a question: does Alice want churn by logo or by revenue? Alice is in a meeting for the next three hours, and somewhere in that window the host is redeployed.

Both pauses are durable. The request comes back after the restart still waiting, and when Alice answers in the thread, execution continues from where it paused, whether that takes seconds or a day. This post covers the ways an agent pauses for a person and the one mechanism underneath them.

The tool contract

The contract between a Mash agent and its tools is four attributes and a method:

# src/mash/tools/base.py
class Tool(Protocol):
    name: str
    description: str
    parameters: Dict[str, Any]   # JSON schema
    requires_approval: bool

    async def execute(self, args: Dict[str, Any]) -> ToolResult: ...

requires_approval is the human-in-the-loop entry point. A tool that touches a database or sends messages gets gated behind user consent with one flag:

tools.register(FunctionTool(
    name="run_query",
    description="Run a read-only SQL query on the analytics replica.",
    parameters={...},
    requires_approval=True,
    _executor=run_query,
))

After each plan step, the loop checks the planned tool calls against registry.tools_requiring_approval(names). If any match, the action carries an approval interaction and the engine pauses durably before the tool phase. The user answers approve, deny, or skip.

On a denial, the loop synthesizes an error result for each pending call and hands it back to the model like any other tool outcome, and the request keeps going:

# src/mash/runtime/engine/loop.py (trimmed)
denied = {
    "tool_call_id": tool_call.id,
    "tool_name": tool_call.name,
    "result": {
        "content": f"Tool execution denied by user ({response})",
        "is_error": True,
        "metadata": {"denied": True},
    },
}

The agent observes the denial in its next think phase and can adjust or propose something else, the same way it would react to any failed tool call.

AskUser never executes

The second pause is agent-initiated. AskUser is a built-in tool the agent calls when it needs information to continue, and in the hosted runtime the loop recognizes the call by name and never runs its execute().

# src/mash/runtime/engine/loop.py (trimmed)
if name == "AskUser":
    return await self._ask_user(state, tool_call=tool_call, loop_index=loop_index)

The interception exists for durability. The tool's purpose is to wait for a human, and a plain await inside execute() would hold that wait in process memory, where one restart would lose the question. The loop translates the call into a durable interaction instead, and when the answer arrives, it hands the agent an ordinary ToolResult whose content is the user's response. As far as the model is concerned, AskUser is a tool that works like any other. (Outside a hosted runtime, calling it returns an error result saying it only works hosted.)

Interaction types

Every interaction is one of four types, each with a defined answer shape and a timed-out answer:

Type Created by Response shape On timeout
approval a planned tool call with requires_approval "approve" / "deny" / "skip" "deny"
info AskUser(question=...) with no options free-form string ""
choice AskUser(question=..., options=[...]) selected option(s) []
browser browser_handoff, for a sign-in "done" the handoff fails

An approval waits 300 seconds and an AskUser question 3600 seconds. A browser handoff has no timeout of its own. The request's policy caps all of them with wait_max_seconds, which the policies post covers, so an unanswered approval is a denial at the earlier of the two.

The companion uses the same types. When the classifier answers unclear, it asks the user to pick an agent with a choice interaction, and when a workflow input is missing a required field, it asks with an info interaction.

The pause machinery

The whole flow is visible in RequestRun._run_interaction. The loop opens the interaction under an id derived from its place in the request, then waits for the answer:

# src/mash/runtime/engine/loop.py (trimmed)
step_name = f"{step_prefix}.open.{loop_index}.{attempt}"
opened = await self._open_interaction(
    interaction_id=derive_interaction_id(f"{self.request_id}:{step_name}"),
    ...,                               # appends interaction.create, or finds it stored
)
response, timed_out = await self._await_answer(
    opened["interaction_id"], deadline=opened["deadline"], ...
)

The answer is an event: the interaction's mash.interaction.end, keyed interaction.ack.<id>. _await_answer waits in process until the deadline, then reads the log. At the deadline it appends the default answer itself (deny for an approval), under the same key, so an answer and a timeout that race leave one row, and both sides read it.

The process can die and restart any number of times while the request waits. The recovered loop derives the same id and finds the interaction already open; its deadline is the stored open time plus its stored timeout. The loop reads the answer from the log if one arrived while it was down, and otherwise waits out the rest of that deadline.

On the wire, the bot sees the pause as a pair of frames on the event's stream, as the events post covered:

event: request.interaction.create   ← interaction_id, type, prompt, options, timeout
... (seconds or days) ...
event: request.interaction.ack      ← interaction_id, the response

While the interaction is open, the event reports waiting. The stream is read from the event log, so a bot that connects while the request is paused still gets the create frame and can render the pending question.

Delivering the answer

The response travels back through the same endpoint the message came in on, naming the event that is waiting:

curl -X POST http://127.0.0.1:8000/api/v1/sessions/slack:C42:1731864100.0001/events \
  -H "Authorization: Bearer $MASH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"event_id": "1731864100.0001", "interaction_id": "itr_a1b2c3d4e5f6", "response": "approve"}'

The host finds which of the event's requests opened the interaction, the companion's or the routed agent's, and forwards the answer to that agent's process, which appends it as the ack event and wakes the waiting loop, which continues into the tool phase. An answer to an interaction that already has one, a timeout or a cancel gets 409 INTERACTION_CLOSED. An answer the interaction's schema doesn't list gets 400 INVALID_INTERACTION_RESPONSE, and the interaction stays open. A new message sent while the event waits is a new event, and it queues behind this one.

sequenceDiagram
    participant User
    participant API as mash.api
    participant WF as request loop
    participant Log as event log

    WF->>Log: request.interaction.create
    Log-->>User: SSE frame (prompt, options)
    Note over WF: waits until the deadline.<br/>A restart reads the log.
    User->>API: POST .../events {event_id, interaction_id, response}
    API->>Log: request.interaction.ack
    API->>WF: wake
    Note over WF: loop continues

What the agent gets back

For an approval, the answer steers the tool phase: approve lets execution proceed, while deny or skip produces the synthesized error results above, and the model reasons about the refusal on its next think.

For AskUser, the answer comes back as the tool result:

{
  "content": "by revenue",
  "is_error": false,
  "metadata": {"interaction_id": "itr_a1b2c3d4e5f6", "timed_out": false}
}

The timed_out flag is worth checking. A timed-out info interaction hands the agent an empty string, which is indistinguishable from a user who pressed enter except for that flag. An agent that asks questions should handle the timeout case explicitly, for example by falling back to a stated default instead of treating silence as an answer, and the system prompt is the right place to set that expectation.

One mechanism

Approval gating, AskUser and the browser handoff are one mechanism in the runtime: a request.interaction.create / request.interaction.ack pair in the log, a loop waiting on the interaction's id, and an answer posted to the event. They differ in who opens the pause: the runtime before a flagged tool, or the agent through a tool call.

A Slack bot that can render a prompt with buttons and post the click back handles every pause Mash has.

Everything so far runs in a conversation, one event at a time. Work that should run the same way every time is a workflow, and that's the next post.

Next: Workflows.