# Humans and interruption

**What you will learn:** how a run stops to wait for a person's approval, how it survives
days of waiting, how the person's answer gets back in, how to stop a run in the middle, and
where "hooks" fit.

**Read first:** [the reference agent](reference-agent.md) and [The Governor](governor.md).
**Time:** about 20 minutes.

## Where people sit

In the [loop that runs](index.md#picture-1-the-loop-that-runs), most requests go to a
fulfiller inside the process. A few cannot: "may this tool call run?" has to be answered by a
person. For those, the Governor records that the run is waiting and returns at once. The
person's answer, whenever it comes, is delivered to the Governor as an ordinary event, and the
loop continues from where it stopped.

```mermaid
flowchart LR
    agent["Agent"] -- "request_approval" --> governor["Governor"]
    governor -- "records, then returns: WAITING" --> app(["Your application"])
    app -- "shows the request" --> person(["A person"])
    person -- "approved or denied" --> app
    app -- "answer(event)" --> governor
    governor -- "event" --> agent
```

This page covers yes-or-no approval and stopping a run in the middle. The next page,
[Asking a person](asking-a-person.md), covers questions whose answer has content.

## The problem: a person is slow

Picture a janitor agent tidying a workspace. It wants to delete `old.log`. You do not want
it deleting files on its own, so a person must say yes first. That person may answer in ten
seconds, or on Monday.

A common way to bring a person in is a **callback**: a function that blocks until someone
clicks "approve", or a hook that runs before each tool. A blocked function holds a process,
a thread and memory for as long as the person takes, and it dies with the process.

gvn has no callbacks for this. Waiting for a human is a **state** of the machine, and the
human's answer is the next **input event**. Interrupting a run is an input event too. Because
every machine is [formally complete](machines.md#what-verified-means) (every state must say
what every input does there), every state is forced to say what an interrupt does there. You
cannot forget.

## Step 1: the run asks, and returns

The reference agent asks its tool policy about each tool call the model asks for. When a
call needs approval, the agent moves to `awaiting_approval` and requests
`request_approval`. You tell the Governor that this kind of request is **external**: nobody
inside the process fulfils it.

First, the pieces. A policy is a [Decision](decisions.md) whose outcomes are the agent's
`VERDICTS`; this one asks before any deletion:

```python
import asyncio
import json

from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Model, Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.governor import WAITING, Governor, Result
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel, StubTool

delete_tool = StubTool(name="delete_file", arguments=Record({"path": Text()}), result={"deleted": True})
toolbox = Toolbox(tools=[delete_tool])


class AskBeforeDeleting(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        if consultation.calls_to(delete_tool):
            return VERDICTS.named("needs_approval")
        return VERDICTS.named("cleared")
```

`StubTool` is a fake tool from `gvn.testing.fakes`: it records its calls and returns a fixed
result. The policy names the tool object it guards: `consultation.calls_to(delete_tool)` is
the judged calls to that tool, matched by its identity, not by the short name the model
wrote ([Tools](tools.md) explains the two names). Next, a small helper that builds a Governor around a given model. The one new
argument is `external`:

```python
def janitor_governor(model: Model) -> Governor:
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=AskBeforeDeleting()),
        },
        external=["request_approval"],
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )
```

Now run it. The scripted model asks to delete `old.log`:

```python
DELETE_OLD_LOG = ToolCall(call_id="call-1", name="delete_file", arguments={"path": "old.log"})
model = ScriptedModel(script=[Reply(message=Message.assistant(text="", calls=[DELETE_OLD_LOG]))])
janitor = Agent(name="janitor", instructions="Tidy the workspace.", tools=[delete_tool])

result = asyncio.run(
    janitor_governor(model).deliver(actor=janitor, event=Event("started", {"prompt": "Tidy up."}))
)
print(result.status() == WAITING)
request = result.pending()[0]
print(request.kind(), request.payload())
```

```text
True
Symbol('request_approval') {'calls': [{'call_id': 'call-1', 'name': 'delete_file', 'arguments': {'path': 'old.log'}}], 'identities': ['gvn.testing.fakes.delete_file'], 'text': '', 'context': {}}
```

The call returned. Nothing is running and nothing is blocked. The request's payload holds the
tool calls (with, in `identities`, the identity of each call's tool), so you can show the person exactly what the model wants to do, the `text` of the
model's reply that asked for them (its explanation, empty here), and the agent's run
`context` (empty here; see [run context](run-context.md)).

## Step 2: waiting costs nothing

While it waits, the agent is just data. Store it in its plain-data form (its [Dto](durable-objects.md)), end the process, and come
back days later:

```python
stored = json.dumps(janitor.to_dto().to_plain())
del janitor  # the process can end here

janitor_later = Agent.from_dto(Agent.Dto.from_plain(json.loads(stored)))
print(janitor_later.state())
```

```text
State('awaiting_approval')
```

In a real deployment, use a persistent journal. The Governor has recorded the events,
so `Recovery` can rebuild the waiting agent from its journal using the latest snapshot
when one exists. See [Crash and resume](../tutorials/durability.md).

## Step 3: the person answers

The person's answer is an event, delivered with `answer` together with the request it
answers. The Governor checks that the agent is still waiting on that request (otherwise
`ValueError`, and nothing is recorded) and addresses the event to whoever asked, which
matters inside a [workflow](workflows.md) (an actor that runs other actors, explained later). `approved` runs the calls:

```python
model = ScriptedModel(script=[Reply(message=Message.assistant(text="Deleted old.log."))])
result = asyncio.run(
    janitor_governor(model).answer(actor=janitor_later, request=request, event=Event("approved"))
)
print(result.outcome().payload())
print(delete_tool.calls())
```

```text
{'text': 'Deleted old.log.', 'tools': [{'name': 'delete_file', 'identity': 'gvn.testing.fakes.delete_file', 'arguments': {'path': 'old.log'}, 'content': {'deleted': True}}], 'attempts': [{'name': 'delete_file', 'identity': 'gvn.testing.fakes.delete_file', 'arguments': {'path': 'old.log'}, 'status': 'ok', 'detail': {'deleted': True}}], 'reductions': {'trimmed': 0, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}, 'recalls': {'asked': 0, 'found': 0, 'failed': 0}, 'readings': {'taken': 0, 'failed': 0, 'blocked': 0, 'latest': {}}}
({'path': 'old.log'},)
```

The tool ran once, with the arguments the person saw.

`denied` refuses every call the person was asked about, and nothing in that reply runs. It
may carry a reason, which the model sees as the failed result of each refused call. This time
the whole exchange happens in one Governor:

```python
janitor = Agent(name="janitor", instructions="Tidy the workspace.", tools=[delete_tool])
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(text="", calls=[DELETE_OLD_LOG])),
        Reply(message=Message.assistant(text="Understood, I left it.")),
    ]
)
driver = janitor_governor(model)


async def ask_then_deny() -> Result:
    waiting = await driver.deliver(actor=janitor, event=Event("started", {"prompt": "Tidy up."}))
    (approval,) = waiting.pending()
    return await driver.answer(
        actor=janitor, request=approval, event=Event("denied", {"reason": "keep the logs"})
    )


result = asyncio.run(ask_then_deny())
print(janitor.transcript()[2].results()[0].content())
print(result.outcome().payload())
```

```text
not run: approval was denied: keep the logs
{'text': 'Understood, I left it.', 'tools': [], 'attempts': [{'name': 'delete_file', 'identity': 'gvn.testing.fakes.delete_file', 'arguments': {'path': 'old.log'}, 'status': 'denied', 'detail': 'not run: approval was denied: keep the logs'}], 'reductions': {'trimmed': 0, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}, 'recalls': {'asked': 0, 'found': 0, 'failed': 0}, 'readings': {'taken': 0, 'failed': 0, 'blocked': 0, 'latest': {}}}
```

If a caller answers the same request a second time, `answer()` raises `ValueError` because
the request is no longer pending. The actor is unchanged.

Approval is not special. Any request kind you list in `external` works the same way, so the
same pattern serves "ask a person to review this draft" or "wait for the payment system to
confirm". When you need a person's *content* rather than a yes or no, use an
[Inquiry](asking-a-person.md), the next page.

## Step 4: stopping a run in the middle

`governor.interrupt(name)` stops an actor the Governor is driving. It cancels and awaits all
work in flight and delivers an `interrupted` event in its place. In the reference agent,
`interrupted` is declared in every state with a request outstanding and leads to
`suspended`. Any tool calls that were pending are answered with failed results, so the
transcript stays well formed.

To have something to interrupt, the first model call is held open: `ScriptedModel` waits on
an `asyncio.Event` entry, and this one is never set.

```python
async def interrupt_then_resume() -> None:
    hold = asyncio.Event()  # never set: the first model call hangs
    model = ScriptedModel(script=[hold, Reply(message=Message.assistant(text="Back."))])
    driver = janitor_governor(model)
    janitor = Agent(name="janitor", instructions="Tidy the workspace.", tools=[delete_tool])

    driving = asyncio.create_task(
        driver.deliver(actor=janitor, event=Event("started", {"prompt": "Hi."}))
    )
    while janitor.state().name() != "thinking":
        await asyncio.sleep(0)  # let the run start; no real time passes
    print(driver.interrupt(name="janitor"))
    suspended = await driving
    print(suspended.status(), janitor.state())

    finished = await driver.deliver(actor=janitor, event=Event("resumed"))
    print(finished.outcome().payload())


asyncio.run(interrupt_then_resume())
```

```text
True
waiting State('suspended')
{'text': 'Back.', 'tools': [], 'attempts': [], 'reductions': {'trimmed': 0, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}, 'recalls': {'asked': 0, 'found': 0, 'failed': 0}, 'readings': {'taken': 0, 'failed': 0, 'blocked': 0, 'latest': {}}}
```

`interrupt` returned `True` because the Governor was driving the janitor. The pending
`deliver` then returned normally, with the agent `suspended`. `resumed` takes the agent back
through `admitting` (the state that checks its budget of model turns), so a resumed agent
still respects its budget.

If the actor is not being driven at the moment, for example because it is waiting for
approval, `interrupt` returns `False`. Deliver `Event("interrupted")` yourself instead; it is
handled the same way.

## Hooks

What about hooks: code that runs before or after each step? gvn splits them in two:

- **Read-only hooks** (log this, count that, show progress) are
  [outputs](streaming-and-observability.md). They see every signal and cannot change the run.
- **Hooks that can change behaviour** (block a tool, ask a person, rewrite a request) are
  states with a [Decision](decisions.md), like the agent's `vetting` (asking the policy) and
  `awaiting_approval`. They live in the machine,
  where the verifier checks them and the journal records them.

That is the 80% you need. The rest of this page covers a reply with several calls and an
approval that stands on its own.

## Deeper: several calls in one reply {#several-calls-in-one-reply}

A model may ask for several calls in one reply. The policy judges each call on its own, the
person is asked only about the calls that need them, and they may deny some and approve the
rest (you did this in [tutorial 5](../tutorials/agent-with-approval.md#step-9-deny-one-call-approve-the-rest)).
Here is the case that tutorial only mentions: what happens to the calls **after** a refused one.

The janitor gets a second tool, `compress_logs`, which the policy clears. Its model asks to
delete two files and then compress the logs, all in one reply:

```python
compress_tool = StubTool(name="compress_logs", arguments=Record({}), result={"compressed": 3})
janitor_tools = Toolbox(tools=[delete_tool, compress_tool])
model = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(
                text="Two deletions, then compress what is left.",
                calls=[
                    ToolCall(call_id="call-1", name="delete_file", arguments={"path": "old.log"}),
                    ToolCall(call_id="call-2", name="delete_file", arguments={"path": "app.db"}),
                    ToolCall(call_id="call-3", name="compress_logs", arguments={}),
                ],
            )
        ),
        Reply(message=Message.assistant(text="Deleted old.log; kept app.db.")),
    ]
)
tidy_driver = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=janitor_tools),
        "invoke_tools": ToolFulfiller(toolbox=janitor_tools),
        "consult_policy": PolicyFulfiller(decision=AskBeforeDeleting()),
    },
    external=["request_approval"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
```

The person is asked about the two deletions. They approve the reply but deny deleting
`app.db`:

```python
tidy_janitor = Agent(
    name="janitor-2", instructions="Tidy the workspace.", tools=janitor_tools
)


async def tidy() -> Result:
    waiting = await tidy_driver.deliver(
        actor=tidy_janitor, event=Event("started", {"prompt": "Tidy up."})
    )
    question = waiting.pending()[0]
    print([call["arguments"]["path"] for call in question.payload()["calls"]])
    answer = Event("approved", {"denied": [{"call_id": "call-2", "reason": "app.db is live"}]})
    return await tidy_driver.answer(actor=tidy_janitor, request=question, event=answer)


result = asyncio.run(tidy())
for attempt in result.outcome().payload()["attempts"]:
    print(attempt["name"], attempt["status"], attempt["detail"])
print(compress_tool.calls())
```

```text
['old.log', 'app.db']
delete_file ok {'deleted': True}
delete_file denied not run: approval was denied: app.db is live
compress_logs skipped not run: an earlier call in this reply was refused
()
```

`compress_logs` was cleared, yet it did not run. The calls of a reply run in the order the
model gave them, because a later call often depends on an earlier one; once a call is refused
(forbidden or denied), every later call is `skipped`. The exception is a tool that declares
itself `independent()`, a pure read with no effect on anything else, which still runs. This
rule assumes that order means dependence, so it can skip a call that would have been
harmless; the model reads why and can ask again.

Three answers are possible, then:

| Answer | Effect |
|---|---|
| `approved` | every call asked about runs |
| `approved` with `{"denied": [{"call_id", "reason"}, ...]}` | the calls named (by `call_id`) are denied, the other asked calls run; a call id that was not asked about is a `ValueError`, with nothing journaled |
| `denied`, optionally `{"reason": str}` | every call asked about is denied and nothing in the reply runs; a cleared call beside them is `abandoned` |

The [reference agent](reference-agent.md#what-became-of-each-call) lists every status, and
[its payload tables](reference-agent.md#deeper-request-payloads) show `positions`, `beside`
and `refused`. A reply whose calls all had the same verdict looks exactly as it did before
verdicts were per call.

## Deeper: an approval on its own {#an-approval-on-its-own}

Sometimes a person must approve something that is not a tool call a model asked for: the go
for a rollout after a canary (a first, small trial of the change), a signature, a budget. `gvn.harness.approval.Approval(name,
label, text="", context=None)` is that step on its own. It makes no tool call and runs
nothing: it asks `request_approval` and ends `approved` or `declined`. `label` names what is
being approved; it travels in the request payload as `approve`.

```python
from gvn.harness.approval import Approval

rollout_gate = Approval(
    name="rollout/gate", label="rollout", text="Canary: 3 of 3 repositories changed."
)
approvals = Governor(
    fulfillers={},
    external=["request_approval"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
waiting = asyncio.run(approvals.deliver(actor=rollout_gate, event=Event("started")))
(asked,) = waiting.pending()
print(asked.request_id(), asked.payload())
```

```text
rollout/gate/request_approval {'calls': [], 'identities': [], 'text': 'Canary: 3 of 3 repositories changed.', 'context': {}, 'approve': 'rollout'}
```

The request's payload is the standard approval payload with no calls and an `"approve"`
label, so an approval channel shows it like any other, and the `ApprovedFirst` check (a rule checked over recorded runs; see
[evaluation](../guides/replay-and-evaluation.md#checks)) can require that it was granted
before some tool ran. The id is stable, so an answer tied to it stays valid across an
interrupt or a crash.

An answer is tied to its request with `Governor.answer(actor, request, event)`. It refuses,
with nothing journaled, an answer to a request the actor is not waiting on, and an event the
request's kind does not admit: a `request_approval` admits only `approved` and `denied`.

```python
async def answer_wrongly_then_rightly() -> Result:
    try:
        await approvals.answer(
            actor=rollout_gate, request=asked, event=Event("answered", {"text": "sure"})
        )
    except ValueError:
        print("refused")
    return await approvals.answer(actor=rollout_gate, request=asked, event=Event("approved"))


print(asyncio.run(answer_wrongly_then_rightly()).outcome())
```

```text
refused
Outcome('approved', {'approve': 'rollout', 'reason': None})
```

A denial may carry `{"reason": str}`. The reason is untrusted text from a person: it is kept
in the outcome and must never route or be copied into a [run context](run-context.md).

## Deeper: who answered {#who-answered}

In a deployment, the answer arrives through an **entry point**: the web handler, chat
integration or command line that received the person's click. It has authenticated the
person, and it says who they are with `Governor.answer(..., by=principal)`, where the
principal is a `gvn.harness.events.Principal(subject, issuer, claims)`. The Governor
journals the answering event with the principal, and an `Approval` keeps it in its outcome
as `"answered_by"`. Unlike the reason, it is trusted: it comes from the entry point, never
from the answer's payload.

```python
from gvn.harness.events import Principal

ana = Principal("ana@example.com", issuer="corp-sso", claims={"groups": ["release"]})
second_gate = Approval(name="rollout/gate-2", label="rollout")


async def approve_as_ana() -> Result:
    (asked,) = (await approvals.deliver(actor=second_gate, event=Event("started"))).pending()
    return await approvals.answer(
        actor=second_gate, request=asked, event=Event("approved"), by=ana
    )


print(asyncio.run(approve_as_ana()).outcome().payload()["answered_by"])
```

```text
{'subject': 'ana@example.com', 'issuer': 'corp-sso', 'claims': {'groups': ['release']}}
```

The reference agent's own approvals record who answered in the journal, with the event,
rather than in the agent's outcome. A Governor built with `entitlement=` also decides whether
the principal may answer at all, and refuses the answer, with nothing journaled, when not.
[Trust](trust.md) covers both.

## Recap

- Waiting for a person is a state; the answer is an event. Nothing blocks while you wait.
- List the request kind in `external`; the Governor parks the run and returns a `WAITING`
  result with the request in `pending()`.
- A waiting actor is plain data: store it, or let `Recovery` rebuild it from the journal.
- Deliver the answer with `Governor.answer(actor=..., request=..., event=...)`; answers to
  requests nobody is waiting on are refused.
- The person is asked only about the calls that need them, and may deny some and approve the
  rest. After a refused call, later calls of the same reply that are not independent are
  `skipped`.
- `interrupt(name=...)` stops a driven actor; `resumed` continues it.
- Read-only hooks are outputs; hooks that change behaviour are states with a Decision.
- `Approval` is a yes/no step with no tool call.
- The entry point says who answered with `answer(..., by=principal)`; the principal is
  journaled with the answer, and an `Approval` keeps it as `"answered_by"`.

**Next:** [Asking a person](asking-a-person.md), for when you need an answer with content.
