# 5. A policy, and approval by a person

**At the end you can:** put a policy of your own in front of the agent's tools, and have a
run stop for a person's approval and continue from their answer.

**What you will learn:** how to write a real tool **policy**, how a run stops and waits for a
person's approval without blocking anything, what happens when a call is approved, denied or
forbidden, and how a reply holding several calls is judged and approved call by call.

**Before this:** [4. Adding a tool](adding-a-tool.md).

**Time:** about 15 minutes for the main idea (steps 1 to 7), and 10 more for "Going further".

## Where this sits in the big picture

This page completes the loop of the quickstart's
[big picture](../quickstart.md#the-big-picture) with its last participant: **a person who
approves**. Tutorial 4 gave the Governor a policy fulfiller that cleared everything. Here the
policy can answer "a person must approve this", and that request goes to no fulfiller at
all: the Governor returns, and the person's answer comes back later as an event.

```mermaid
flowchart LR
    agent["<b>Agent</b>"]
    governor["<b>Governor</b>"]
    policy["PolicyFulfiller<br/>your RefundPolicy"]
    person(["A person"])
    agent -- "consult_policy" --> governor
    governor --> policy
    policy -- "needs_approval" --> governor
    agent -- "request_approval" --> governor
    governor -.->|"returns: waiting"| person
    person -- "approved / denied" --> governor
```

## Where you are

At the end of tutorial 4 the help desk agent could look orders up, under a policy that
allowed everything.

**Start a new file for this page, and begin it with the block below.** The block holds
everything from the earlier pages that this page uses, imports included. That is the same
first step whether you have just finished tutorial 4 or are starting here. Then add each
block of the page below it, in order.

??? example "The agent and its tool from tutorial 4"

    ```python
    import asyncio
    import typing

    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 Journal, Model, Reply
    from gvn.harness.tools import Invocation, Tool, Toolbox
    from gvn.kernel.decision import Decision
    from gvn.kernel.schema import Record, Text
    from gvn.kernel.symbols import Alphabet, Symbol
    from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


    class OrderBook:
        def __init__(self, orders: dict[str, dict[str, typing.Any]]) -> None:
            self._orders = {order_id: dict(order) for order_id, order in orders.items()}

        def find(self, order_id: str) -> dict[str, typing.Any]:
            return dict(self._orders[order_id])


    class LookUpOrder(Tool):
        def __init__(self, order_book: OrderBook) -> None:
            self._order_book = order_book

        def name(self) -> str:
            return "look_up_order"

        def description(self) -> str:
            return "Look up one order by its id. Returns its status and total."

        def arguments(self) -> Record:
            return Record({"order_id": Text()})

        async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
            return self._order_book.find(arguments["order_id"])


    order_book = OrderBook(
        orders={
            "A-17": {"status": "shipped", "total": 40.0},
            "B-22": {"status": "delivered", "total": 120.0},
        }
    )
    ```

## The problem: some tools need a person

Looking an order up is harmless. Refunding money is not: the help desk wants a person to
approve every refund, and refunds above 100.00 must not happen through the agent at all. In
many frameworks this is a callback that blocks until someone clicks "approve", which ties up
a process for as long as the person takes.

In gvn, waiting for a person is a **state** of the agent (`awaiting_approval`), and the
person's answer is the next **event**. Nothing is blocked while you wait.

## Step 1: a refund tool

Refunds are recorded in a `Ledger`, the outside world this tool changes:

```python
from gvn.kernel.schema import Number


class Ledger:
    """The refunds the shop has paid. The world the refund tool changes."""

    def __init__(self) -> None:
        self._refunds = []

    def refund(self, order_id: str, amount: float) -> int:
        self._refunds.append({"order_id": order_id, "amount": amount})
        return len(self._refunds)

    def refunds(self) -> list[dict[str, typing.Any]]:
        return [dict(refund) for refund in self._refunds]


class IssueRefund(Tool):
    def __init__(self, ledger: Ledger) -> None:
        self._ledger = ledger

    def name(self) -> str:
        return "issue_refund"

    def description(self) -> str:
        return "Refund an amount on an order. Money leaves the shop."

    def arguments(self) -> Record:
        return Record({"order_id": Text(), "amount": Number()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        number = self._ledger.refund(order_id=arguments["order_id"], amount=arguments["amount"])
        return {"refund": number}


ledger = Ledger()
look_up_order = LookUpOrder(order_book=order_book)
issue_refund = IssueRefund(ledger=ledger)
toolbox = Toolbox([look_up_order, issue_refund])
print([tool.name() for tool in toolbox.tools()])  # ['issue_refund', 'look_up_order']
```

`Number()` is a schema for an int or a float. As in tutorial 4, each tool is built once, as
an object; the toolbox, the agent and the policy below all get that same object.

## Step 2: the policy

The policy is a Decision over a **consultation**: one tool call the model just asked for
(`calls()`, a tuple holding that one call, and `identities()`, the
[identity](../concepts/tools.md#two-names-the-short-name-and-the-identity) of its tool), the
name of the agent that asked (`origin()`) and its run context (`context()`, trusted data
about the run; see [Run context](../concepts/run-context.md)). The policy picks out calls by
tool, not by name: `consultation.calls_to(issue_refund)` is the tuple of judged calls to
that tool object, matched by identity, so a same-named tool from another package never
passes for it. It answers one of the three `VERDICTS` for that call:

```python
REFUND_LIMIT = 100.0


class RefundPolicy(Decision):
    """Look-ups are cleared, refunds need a person, large refunds are forbidden."""

    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        refunds = consultation.calls_to(issue_refund)
        if not refunds:
            return VERDICTS.named("cleared")
        (call,) = refunds  # the one call being judged
        amount = call.arguments().get("amount")
        if not isinstance(amount, (int, float)) or amount > REFUND_LIMIT:
            return VERDICTS.named("forbidden")
        return VERDICTS.named("needs_approval")
```

Two details matter:

- The policy is asked *before* the arguments are checked against the tool's schema, and the
  arguments come from a model. Treat them as untrusted: the policy checks that `amount` is a
  number before comparing it, and forbids anything it cannot read.
- The policy judges **one call at a time**. A model may put several calls in one reply; the
  policy is then asked once per call, and each call gets its own verdict. Step 8 shows what
  that means for a reply that mixes a look-up and a refund.

A Decision is plain code, so you can test it without running anything:

```python
from gvn.harness.tools import Consultation

small_refund = ToolCall(
    call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": 40.0}
)
consultation = Consultation(
    calls=[small_refund], identities=[issue_refund.identity()], origin="helpdesk"
)
print(RefundPolicy().decide(consultation))
# Symbol('needs_approval')
```

## Step 3: tell the Governor who answers approvals

When the agent needs approval it makes a `request_approval` request. No code in the process
should fulfil it: a person does. You say so with `external=[...]`, the request kinds answered
from outside. `build_governor` from tutorial 4 gains that line, and now also takes the
journal, so you can read it at the end:

```python
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result


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

## Step 4: run until a person is needed

The model looks the order up, then asks to refund it. A small helper, `asks_for`, builds a
model reply that calls one tool by its short name (a model only ever writes short names), so
the script stays readable. The agent is given its tools with `tools=toolbox`: an agent takes
a `Toolbox` as well as the list of tool objects tutorial 4 used, and stores the same
identities from either.

```python
def asks_for(
    short_name: str, arguments: dict[str, typing.Any], call_id: str = "call-1"
) -> Reply:
    call = ToolCall(call_id=call_id, name=short_name, arguments=arguments)
    return Reply(message=Message.assistant(calls=[call]))


model = ScriptedModel(
    script=[
        asks_for("look_up_order", {"order_id": "A-17"}),
        asks_for("issue_refund", {"order_id": "A-17", "amount": 40.0}, call_id="call-2"),
        Reply(message=Message.assistant(text="I refunded 40.00 on order A-17.")),
    ]
)
journal = MemoryJournal()
governor = build_governor(model=model, policy=RefundPolicy(), journal=journal)
refunds_agent = Agent(
    name="refunds",
    instructions="Help customers with damaged orders. Look the order up before refunding.",
    tools=toolbox,
)
broken = Event(name="started", payload={"prompt": "Order A-17 arrived broken. Refund me."})
result = asyncio.run(governor.deliver(actor=refunds_agent, event=broken))

print(result.status(), refunds_agent.state())  # waiting State('awaiting_approval')
approval = result.pending()[0]
print(approval.request_id(), approval.kind().name())  # refunds/13 request_approval
for call in approval.payload()["calls"]:
    print("wants", call["name"], call["arguments"])
# wants issue_refund {'order_id': 'A-17', 'amount': 40.0}
```

The look-up ran without asking, because the policy cleared it. The refund is waiting. The
`deliver` call has **returned**: no task is blocked on your answer. The result's `pending()`
holds the request, with the calls to show the person. Because every event so far is in the
journal, this run could wait for days and continue in another process; that is tutorial 6.

## Step 5: approve

You are the person. Your answer is an event, `approved`, delivered with
`governor.answer(actor=..., request=..., event=...)`. `answer` ties the event to the request
it answers, and refuses it if that request is no longer pending.

```mermaid
sequenceDiagram
    participant G as Governor
    participant App as Your program
    participant P as The person
    G-->>App: Result: waiting, with the pending request
    App->>P: Show the calls
    P-->>App: Approve or deny
    App->>G: answer(actor, request, event)
    alt The request is still pending
        G->>G: Record the answer and continue the run
        G-->>App: Result of continuing
    else The request is no longer pending
        G-->>App: Refuse the answer
    end
```

On this page your program and the person are the same Python session. A real application
also checks who is answering:
[Humans and interruption](../concepts/human-in-the-loop.md#who-answered) and
[Trust](../concepts/trust.md) show how, and the
[complete approval recipe](../recipes.md#approve-a-tool-call) is a runnable example.

```python
result = asyncio.run(
    governor.answer(actor=refunds_agent, request=approval, event=Event(name="approved"))
)
print(result.outcome().payload()["text"])  # I refunded 40.00 on order A-17.
print(ledger.refunds())  # [{'order_id': 'A-17', 'amount': 40.0}]
print([attempt["status"] for attempt in result.outcome().payload()["attempts"]])
# ['ok', 'ok']
```

The attempts list both calls: the look-up and the refund. An attempt's status says what
became of the call: `ok` here. The next steps show `forbidden`, `denied` and `skipped`; the
[reference agent](../concepts/reference-agent.md#what-became-of-each-call) lists them all.

## Step 6: a forbidden call

Now the model tries to refund 120.00. The policy forbids it, so nobody is asked and the tool
never runs. The agent answers the call with a failed result that explains why, and asks the
model again, which can choose something else:

```python
model = ScriptedModel(
    script=[
        asks_for("issue_refund", {"order_id": "B-22", "amount": 120.0}),
        Reply(message=Message.assistant(text="That refund is too large for me; finance will call.")),
    ]
)
too_large = Agent(name="refunds-2", instructions="Help customers.", tools=toolbox)
result = asyncio.run(
    build_governor(model=model, policy=RefundPolicy(), journal=journal).deliver(
        actor=too_large,
        event=Event(name="started", payload={"prompt": "Refund B-22 in full."}),
    )
)
print(too_large.transcript()[2].results()[0].content())  # not run: the policy forbade this call
print(result.outcome().payload()["attempts"][0]["status"])  # forbidden
print(len(ledger.refunds()))  # 1
```

## Step 7: a denial, with a reason

Finally, say no. A `denied` event may carry a `reason`, and the model sees it:

```python
model = ScriptedModel(
    script=[
        asks_for("issue_refund", {"order_id": "B-22", "amount": 60.0}),
        Reply(message=Message.assistant(text="Our team could not approve a refund, sorry.")),
    ]
)
half_refund = Agent(name="refunds-3", instructions="Help customers.", tools=toolbox)
governor = build_governor(model=model, policy=RefundPolicy(), journal=journal)


async def ask_and_deny() -> Result:
    waiting = await governor.deliver(
        actor=half_refund,
        event=Event(name="started", payload={"prompt": "Refund half of B-22."}),
    )
    return await governor.answer(
        actor=half_refund,
        request=waiting.pending()[0],
        event=Event(name="denied", payload={"reason": "B-22 was delivered in good condition"}),
    )


result = asyncio.run(ask_and_deny())
print(half_refund.transcript()[2].results()[0].content())
# not run: approval was denied: B-22 was delivered in good condition
print(len(ledger.refunds()))  # 1
```

Wrapping the two calls in one `async def` and one `asyncio.run` is just a convenience; the
two `asyncio.run` calls of steps 4 and 5 work as well.

## You have the main idea

You can now write a policy, have a run return `waiting` when a call needs a person, and
answer it with `approved` or `denied`. You have seen each verdict end: a cleared call runs,
an approved call runs, a forbidden or denied call becomes a failed result the model reads.
That is all the next tutorial needs.

## Going further

The two steps below are about model replies that hold more than one tool call:

- **Step 8, two calls in one reply.** You need it once you use a real model, which often
  asks for several calls at once: what the person is shown, and in which order calls run.
- **Step 9, deny one call and approve the rest.** You need it when a person is asked about
  several calls and should be able to answer each one.

### Step 8: two calls in one reply, one needs a person

So far every model reply asked for one call. Real models often put several calls in one
reply: here the model looks the order up *and* refunds the shipping in the same breath. The
policy judges each call on its own, so the look-up is cleared and the refund needs a person.
The person is asked only about the refund:

```python
look_up = ToolCall(call_id="call-1", name="look_up_order", arguments={"order_id": "A-17"})
shipping = ToolCall(
    call_id="call-2", name="issue_refund", arguments={"order_id": "A-17", "amount": 15.0}
)
model = ScriptedModel(
    script=[
        Reply(message=Message.assistant(text="Checking A-17.", calls=[look_up, shipping])),
        Reply(message=Message.assistant(text="I refunded the 15.00 shipping on A-17.")),
    ]
)
shipping_agent = Agent(name="refunds-4", instructions="Help customers.", tools=toolbox)
governor = build_governor(model=model, policy=RefundPolicy(), journal=journal)
waiting = asyncio.run(
    governor.deliver(
        actor=shipping_agent,
        event=Event(name="started", payload={"prompt": "Refund the shipping on A-17."}),
    )
)
question = waiting.pending()[0].payload()
print([call["name"] for call in question["calls"]])  # ['issue_refund']
print(question["positions"])  # [1]
for other in question["beside"]:
    print("beside:", other["position"], other["verdict"], other["call"]["name"])
# beside: 0 cleared look_up_order
```

The approval request's `calls` holds only the call that needs a person. Because the reply had
other calls too, the payload says where the asked call sits in the reply (`positions`) and
shows the others as context (`beside`, each with its position and verdict), so the person sees
the whole reply but is asked about one call.

Nothing has run yet: the calls of a reply run in the order the model gave them, after the
answer. Approve, and both run:

```python
result = asyncio.run(
    governor.answer(
        actor=shipping_agent, request=waiting.pending()[0], event=Event(name="approved")
    )
)
print([attempt["status"] for attempt in result.outcome().payload()["attempts"]])
# ['ok', 'ok']
print(len(ledger.refunds()))  # 2
```

### Step 9: deny one call, approve the rest

When a person is asked about several calls, they may say yes to some and no to others. The
answer is still `approved`, with a payload naming the calls denied, each with an optional
reason: `{"denied": [{"call_id": ..., "reason": ...}]}`, where `call_id` is the
`call_id` of a call in the request. Here the model asks for two refunds; the
person approves the first and denies the second:

```python
model = ScriptedModel(
    script=[
        Reply(
            message=Message.assistant(
                calls=[
                    ToolCall(
                        call_id="call-1",
                        name="issue_refund",
                        arguments={"order_id": "A-17", "amount": 10.0},
                    ),
                    ToolCall(
                        call_id="call-2",
                        name="issue_refund",
                        arguments={"order_id": "B-22", "amount": 60.0},
                    ),
                ]
            )
        ),
        Reply(message=Message.assistant(text="I refunded 10.00 on A-17; B-22 was declined.")),
    ]
)
two_refunds = Agent(name="refunds-5", instructions="Help customers.", tools=toolbox)
governor = build_governor(model=model, policy=RefundPolicy(), journal=journal)


async def approve_all_but_one() -> Result:
    waiting = await governor.deliver(
        actor=two_refunds,
        event=Event(name="started", payload={"prompt": "Refund A-17 and B-22."}),
    )
    partly = Event(
        name="approved",
        payload={"denied": [{"call_id": "call-2", "reason": "B-22 arrived intact"}]},
    )
    return await governor.answer(actor=two_refunds, request=waiting.pending()[0], event=partly)


result = asyncio.run(approve_all_but_one())
print([attempt["status"] for attempt in result.outcome().payload()["attempts"]])
# ['ok', 'denied']
print(two_refunds.transcript()[2].results()[1].content())
# not run: approval was denied: B-22 arrived intact
print(len(ledger.refunds()))  # 3
```

The approved refund ran; the denied one did not run but still got a failed result, so the
model reads why. Compare the three answers:

- `approved` with no payload: every call asked about runs.
- `approved` with `{"denied": [...]}`: the calls named are denied. Other calls are eligible
  to run, subject to the ordering rule below.
- `denied` (step 7): every call asked about is denied and **nothing** in the reply runs. A
  cleared call beside them is answered `abandoned`.

One more rule protects you when a call is refused (forbidden or denied): every **later** call
in the same reply is `skipped`, not run, because the model may have meant it to depend on the
refused one (an edit, then a test of that edit). Only tools that declare themselves
independent, pure reads, still run. [Humans and
interruption](../concepts/human-in-the-loop.md#several-calls-in-one-reply) shows it.

## What you did not have to build

- No approval callback, no "before tool" hook. The approval gate is the `vetting` (waiting
  for the policy's verdicts) and `awaiting_approval` states of the
  [reference agent](../concepts/reference-agent.md), and
  your only code for it is a Decision.
- No special waiting mechanism. A run that needs a person returns `waiting` with the request
  in `pending()`; the answer is an ordinary event.
- No transcript bookkeeping. Forbidden and denied calls are answered with failed results
  automatically, so the conversation stays valid for any model vendor.
- Every event is in the journal, in order:

```python
records = asyncio.run(journal.read("refunds"))
print([record["event"]["name"] for record in records])
# ['started', 'model_replied', 'cleared', 'tools_returned', 'model_replied',
#  'needs_approval', 'approved', 'tools_returned', 'model_replied']
```

## Change it and run again

Predict the answer first, then run the code and open the block.

**1. Raise the refund limit.** Step 6 forbade a refund of 120.00. Set the limit to 200.00
and ask the policy about the same call. Which verdict does it give?

```python
REFUND_LIMIT = 200.0

large_refund = ToolCall(
    call_id="call-1", name="issue_refund", arguments={"order_id": "B-22", "amount": 120.0}
)
large = Consultation(
    calls=[large_refund], identities=[issue_refund.identity()], origin="helpdesk"
)
print(RefundPolicy().decide(large))
```

??? note "What happens"

    ```text
    Symbol('needs_approval')
    ```

    The refund is no longer forbidden, and it is not cleared either: every refund still
    needs a person. Run step 6 again with this limit and the run returns `waiting`
    instead of finishing.

**2. An amount the policy cannot read.** A model may send the amount as text. What does the
policy answer for `"40"`?

```python
text_amount = ToolCall(
    call_id="call-1", name="issue_refund", arguments={"order_id": "A-17", "amount": "40"}
)
unreadable = Consultation(
    calls=[text_amount], identities=[issue_refund.identity()], origin="helpdesk"
)
print(RefundPolicy().decide(unreadable))
```

??? note "What happens"

    ```text
    Symbol('forbidden')
    ```

    `"40"` is not a number, and the policy forbids what it cannot read. That is the first
    of the two details of step 2: the policy sees the arguments before the tool's schema
    checks them.

## Recap

- A **policy** is a Decision over a `Consultation` that answers `cleared`, `needs_approval`
  or `forbidden` for one call. A reply's calls are judged one by one. It picks calls out by
  tool, with `consultation.calls_to(tool)`, never by name. Treat the arguments it sees as
  untrusted.
- `external=["request_approval"]` tells the Governor that a person answers approvals. The run
  returns `waiting` and holds no process. The person is asked only about the calls that need
  them; `positions` and `beside` show the rest of the reply.
- `governor.answer(actor=..., request=..., event=Event(name="approved"))` delivers the
  answer; `approved` with `{"denied": [...]}` denies some calls and approves the rest;
  `denied` refuses the whole reply and can carry a `reason` the model will read.
- [Humans and interruption](../concepts/human-in-the-loop.md) covers interrupting a run and
  approval in more depth.

**Next:** [6. The journal: crash and resume](durability.md) stores the journal in a file,
ends the process while the refund waits for approval, and finishes the run in a new one.
