# Runnable recipes

You have a specific problem and want to see it solved before you read any theory. Each
recipe here is one Python file that solves one problem. It runs offline in seconds,
with no API key, so you can run it first and adapt it afterwards.

| Your problem | Recipe |
|---|---|
| An agent can change something, and a person has to agree before it does | [Stop a tool call until a person approves](#approve-a-tool-call) |
| A run is waiting on a person, and your process may restart before they answer | [Keep a waiting run across a restart](#park-and-recover-with-sqlite) |
| Your agent is waiting for an approval, and another process has to pick it up and answer | [Keep an agent's pending approval across a restart](#agent-approval-across-a-restart) |
| You want tests that prove your agent does nothing before approval, with no API key | [Test an agent offline](#test-an-agent-offline) |
| An agent should assess a case, and a fixed payment should follow only after a person agrees | [A two-stage workflow: an agent assesses, a person approves the payment](#a-two-stage-workflow) |

Each recipe needs Python 3.12 or newer and `gvn` [installed](install.md#install-gvn), and
nothing else. If you have not run gvn yet, start with the
[first agent](start.md#run-the-example), which is simpler than any of these.

## What the recipes rely on {#what-both-recipes-rely-on}

All five problems have the same shape: a run reaches a point where it cannot go on until
someone outside the program answers. gvn handles that with five parts.

- An **actor** is the thing that runs: an agent, a single question to a person, or a
  workflow made of other actors. The agent you ran in the
  [first agent](start.md#run-the-example) is an actor.
- The **Governor** is the runtime. It drives an actor forward one event at a time, and it
  holds the model, the tools and the policy the actor needs.
- A **policy** looks at every tool call before it runs and says whether it may run, needs a
  person's approval, or is forbidden.
- The **journal** is the Governor's record of every event, in order.
- A **request** is a question the Governor cannot answer itself, such as an approval. The
  run **parks** on it: it stops and waits.

```mermaid
sequenceDiagram
    participant C as Your code
    participant G as Governor
    participant J as Journal
    participant P as A person
    C->>G: deliver the first event
    G->>J: record each event
    G-->>C: waiting, with a pending request
    P->>C: decides, now or days later
    C->>G: answer the request
    G->>J: record the answer and who gave it
    G-->>C: finished, with the outcome
```

Each recipe looks at one part of this picture.

1. [Stop a tool call until a person approves](#approve-a-tool-call) shows what happens
   around the pending request.
2. [Keep a waiting run across a restart](#park-and-recover-with-sqlite) shows what happens
   to it when the process goes away.
3. [Keep an agent's pending approval across a restart](#agent-approval-across-a-restart)
   puts the first two together for an agent with tools.
4. [Test an agent offline](#test-an-agent-offline) turns the picture into tests.
5. [A two-stage workflow](#a-two-stage-workflow) puts two actors in one run, with the
   approval inside the second.

The third and fourth recipes start from `run_agent`, the one-call shortcut from the first
agent, which builds a Governor for you. The others build the Governor by hand so that you
can see every part.

## Stop a tool call until a person approves {#approve-a-tool-call}

**The problem.** Your agent has a tool that changes something: it sends an email, issues a
refund, writes to a database. The model decides when to call it, and you want a person to
agree first.

**How gvn solves it.** A **policy** looks at every tool call before it runs. When the policy
says a call needs approval, the run parks on an approval request. The tool runs only after
an entitled person answers, and the journal records who that was.

**Run it.** Save the script as `approve_tool.py` and run `python approve_tool.py`.

```python { .recipe #approve-tool-script data-filename="approve_tool.py" }
import asyncio

from gvn.harness.agent import Agent
from gvn.harness.answering import Authenticated
from gvn.harness.events import Event, Principal
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.schema import Record, Text
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.shortcuts import AskBeforeEveryCall, FunctionTool
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


async def main() -> None:
    saved = []

    def save_note(note: str) -> dict[str, bool]:
        saved.append(note)
        return {"saved": True}

    tool = FunctionTool(
        name="save_note",
        description="Save one note.",
        arguments=Record({"note": Text()}),
        function=save_note,
    )
    toolbox = Toolbox(tools=[tool])
    call = ToolCall(call_id="1", name="save_note", arguments={"note": "Order A-17 checked"})
    model = ScriptedModel(script=[
        Reply(message=Message.assistant(calls=[call])),
        Reply(message=Message.assistant(text="Saved the note.")),
    ])
    journal = MemoryJournal()
    governor = Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=AskBeforeEveryCall()),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
        },
        external=["request_approval"],
        journal=journal,
        clock=ManualClock(),
        output=RecordingOutput(),
        entitlement=Authenticated(issuers=["demo-idp"]),
    )
    agent = Agent(name="notes", instructions="Save the order note.", tools=toolbox)
    waiting = await governor.deliver(
        actor=agent, event=Event("started", {"prompt": "Record that A-17 was checked."})
    )
    (request,) = waiting.pending()
    assert waiting.status() == "waiting" and saved == []
    print(f"Waiting on {request.kind().name()}")

    reviewer = Principal(subject="demo-reviewer", issuer="demo-idp")
    result = await governor.answer(
        actor=agent, request=request, event=Event("approved"), by=reviewer
    )
    assert saved == ["Order A-17 checked"]
    records = await journal.read("notes")
    approval = next(row["event"] for row in records if row["event"]["name"] == "approved")
    assert approval["by"]["subject"] == "demo-reviewer"
    print(result.outcome().payload()["text"])


if __name__ == "__main__":
    asyncio.run(main())
```

It prints:

```text { .expected-output }
Waiting on request_approval
Saved the note.
```

**What each part is for.**

- `save_note` is the tool with an effect. It appends to a list, which stands in for your
  database or email service.
- `ScriptedModel` plays the model, so the recipe runs offline. Its first reply asks for the
  tool and its second gives the final answer.
- `AskBeforeEveryCall()` is the policy. It says every call needs approval.
- `external=["request_approval"]` tells the Governor that approvals are answered from
  outside, so it parks the run instead of answering.
- `Authenticated(issuers=["demo-idp"])` is the rule for who may answer: someone your
  identity provider has vouched for.
- The first `assert` is the point of the recipe. The run is `waiting` and `saved` is still
  empty: nothing happened while nobody had agreed.
- `governor.answer(..., by=reviewer)` is the approval. The tool runs, and the last lines read
  the reviewer's name back from the journal.
- `Event("approved")` is the whole answer. The `approved` event is sent with no payload;
  an empty dict, `Event("approved", {})`, is refused with a `ValueError`.

**Make it yours.**

- Swap `ScriptedModel` for a [vendor model](guides/vendors.md).
- Replace `AskBeforeEveryCall()` with [rules](tools/rules.md) that ask only for the calls
  that matter.
- Build the `Principal` from the person your entry point authenticated. The Governor checks
  it against the rule you configured.
- Use a durable journal, as the next two recipes do.

**Go deeper.** [Approval and denial](tutorials/agent-with-approval.md#step-5-approve) walks
through both answers, and [Trust](concepts/trust.md) covers who may answer.

## Keep a waiting run across a restart {#park-and-recover-with-sqlite}

**The problem.** A run is waiting for a person, and people take hours or days. In that time
your process is deployed again, scaled down, or crashes. The question must still be there
when they answer.

**How gvn solves it.** The journal is the run. Put it in a database, and any process that
opens the same database can rebuild the run from its recorded events and carry on.

**Run it.** Save the script as `recover_inquiry.py` and run `python recover_inquiry.py`.

```python { .recipe #recover-inquiry-script data-filename="recover_inquiry.py" }
import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory

from gvn.adapters.sqlite import SqliteJournal
from gvn.harness.events import Event
from gvn.harness.inquiry import Inquiry
from gvn.runtime.governor import Governor
from gvn.runtime.recovery import Recovery
from gvn.testing.fakes import ManualClock, RecordingOutput


def build_governor(journal: SqliteJournal) -> Governor:
    return Governor(
        fulfillers={}, external=["request_input"], journal=journal,
        clock=ManualClock(), output=RecordingOutput(),
    )


async def park(path: Path) -> None:
    journal = SqliteJournal(path=path)
    try:
        inquiry = Inquiry(name="shipping", audience="operator", choices=("hold", "ship"))
        result = await build_governor(journal).deliver(
            actor=inquiry, event=Event("started", {"question": "Ship the replacement?"})
        )
        assert result.status() == "waiting"
        print(f"Parked on {result.pending()[0].kind().name()}")
    finally:
        await journal.close()


async def recover_and_answer(path: Path) -> None:
    journal = SqliteJournal(path=path)
    try:
        inquiry = await Recovery(journal=journal).recover(run_id="shipping", actor_class=Inquiry)
        (request,) = inquiry.pending()
        result = await build_governor(journal).answer(
            actor=inquiry, request=request,
            event=Event("answered", {"text": "Ship it.", "choice": "ship"}),
        )
        print(f"Recovered answer: {result.outcome().payload()['choice']}")
    finally:
        await journal.close()


if __name__ == "__main__":
    with TemporaryDirectory() as directory:
        path = Path(directory) / "journal.db"
        asyncio.run(park(path))
        asyncio.run(recover_and_answer(path))
```

It prints:

```text { .expected-output }
Parked on request_input
Recovered answer: ship
```

**What each part is for.**

- `Inquiry` is a ready-made actor that asks a person one question with fixed choices.
- `SqliteJournal(path=path)` keeps the journal in a file instead of in memory.
- `park` is the first process. It starts the run, sees it `waiting`, and closes the journal,
  which is all a process that exits would leave behind.
- `recover_and_answer` is the second process. It opens the same file, and
  `Recovery(...).recover(...)` rebuilds the `Inquiry` from the recorded events, pending
  request included.
- A new Governor answers that request. The first one is gone and was never needed again.
- The database sits in a temporary directory so you can run the script repeatedly.

**Make it yours.**

- Point `SqliteJournal` at a path that outlives the process.
- For several workers sharing one journal, use PostgreSQL and leases, as
  [Running as a service](guides/running-as-a-service.md) shows.
- If a tool call can be in flight when the process stops, follow
  [Crash and resume](tutorials/durability.md) to see where to deduplicate its effect.
- For an agent with tools instead of a single question, use the next recipe.

## Keep an agent's pending approval across a restart {#agent-approval-across-a-restart}

**The problem.** Your agent runs with `run_agent` and has a tool that needs approval. The
person who approves answers hours later, through another process: a web handler, a queue
worker, a command you run by hand. That process has to find the waiting agent and answer
it.

**How gvn solves it.** The two processes share one journal file and nothing else.

```mermaid
sequenceDiagram
    participant A as Process 1
    participant J as Journal file
    participant B as Process 2
    A->>J: run_agent records the run
    A-->>A: Unanswered: the agent is parked
    Note over A: exits
    B->>J: Recovery reads the run
    J-->>B: the agent, waiting, with its request
    B->>J: a new Governor answers and finishes the run
```

What each process brings is the part people usually have to guess, so here it is in full.

| | Comes from the journal | Process 2 builds it again |
|---|---|---|
| The agent's name, instructions and conversation so far | yes | |
| The pending tool call and the request to approve it | yes | |
| The names of the tools the agent was offered | yes | |
| The actor class, `Agent` | | yes, for `Recovery` |
| The tools themselves, the model and the policy | | yes, for the Governor |

So you do not pass the instructions or the prompt again. You do build the tools again,
because a journal stores a tool's name and never its code. The new Governor checks that it
holds every tool the recovered agent was offered before it runs anything.

**Run it.** Save the script as `resume_approval.py` and run `python resume_approval.py`.

```python { .recipe #resume-approval-script data-filename="resume_approval.py" }
import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory

from gvn.adapters.sqlite import SqliteJournal
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.kernel.schema import Record, Text
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.runtime.recovery import Recovery
from gvn.shortcuts import AskBeforeEveryCall, FunctionTool, Unanswered, run_agent
from gvn.testing.fakes import ManualClock, RecordingOutput, ScriptedModel

RUN = "refund-A-17"
refunds = []


def refund_order(order_id: str) -> dict[str, bool]:
    refunds.append(order_id)
    return {"refunded": True}


refund = FunctionTool(
    name="refund_order",
    description="Refund one order.",
    arguments=Record({"order_id": Text()}),
    function=refund_order,
    namespace="shop",
)
call = ToolCall(call_id="1", name="refund_order", arguments={"order_id": "A-17"})
ASKS_FOR_THE_REFUND = Reply(message=Message.assistant(calls=[call]))
FINAL_ANSWER = Reply(message=Message.assistant(text="Order A-17 is refunded."))


async def park(path: Path) -> None:
    journal = SqliteJournal(path=path)
    try:
        await run_agent(
            instructions="Refund the order the customer names.",
            prompt="Please refund order A-17.",
            model=ScriptedModel(script=[ASKS_FOR_THE_REFUND, FINAL_ANSWER]),
            tools=[refund],
            policy=AskBeforeEveryCall(),
            journal=journal,
            name=RUN,
        )
    except Unanswered as waiting:
        (request,) = waiting.pending()
        print(f"Parked on {request.kind().name()}, refunds so far: {refunds}")
    finally:
        await journal.close()


async def recover_and_answer(path: Path) -> None:
    journal = SqliteJournal(path=path)
    try:
        agent = await Recovery(journal=journal).recover(run_id=RUN, actor_class=Agent)
        (request,) = agent.pending()
        asked = request.payload()["calls"][0]
        print(f"Recovered in {agent.state().name()}: {asked['name']} {asked['arguments']}")
        toolbox = Toolbox(tools=[refund])
        governor = Governor(
            fulfillers={
                "invoke_model": ModelFulfiller(
                    model=ScriptedModel(script=[FINAL_ANSWER]), toolbox=toolbox
                ),
                "consult_policy": PolicyFulfiller(decision=AskBeforeEveryCall()),
                "invoke_tools": ToolFulfiller(toolbox=toolbox),
            },
            external=["request_approval"],
            journal=journal,
            clock=ManualClock(),
            output=RecordingOutput(),
        )
        result = await governor.answer(actor=agent, request=request, event=Event("approved"))
        print(f"Refunds after approval: {refunds}")
        print(result.outcome().payload()["text"])
    finally:
        await journal.close()


if __name__ == "__main__":
    with TemporaryDirectory() as directory:
        path = Path(directory) / "journal.db"
        asyncio.run(park(path))
        asyncio.run(recover_and_answer(path))
```

It prints:

```text { .expected-output }
Parked on request_approval, refunds so far: []
Recovered in awaiting_approval: refund_order {'order_id': 'A-17'}
Refunds after approval: ['A-17']
Order A-17 is refunded.
```

**What each part is for.**

- `park` is the first process. `run_agent` is given a policy that asks before every call and
  no `approve` function, so nobody there can answer. It raises `Unanswered`, which carries
  the pending request. The run is already in the journal, and the refund list is still
  empty.
- `recover_and_answer` is the second process. `Recovery(...).recover(run_id=RUN,
  actor_class=Agent)` needs the run's name and the actor class. It returns the agent in the
  state it parked in, `awaiting_approval`, and `agent.pending()` is the same request.
- The Governor in the second process is the one `run_agent` built in the first, written out:
  a model, the policy and the tools. It is given the policy again because the agent may ask
  for another tool call after this one.
- `namespace="shop"` gives the tool a fixed full name, `shop.refund_order`. The journal
  stores that full name, and the second process must build a tool with the same one. Without
  `namespace`, the full name starts with the name of the module that defines the function,
  which differs when two different files build the tool. [Tools](concepts/tools.md#two-names-the-short-name-and-the-identity)
  explains the two names.
- The scripted model in the second process holds only `FINAL_ANSWER`. The model's first
  reply, the one that asked for the refund, is in the journal and is not asked for again. A
  scripted model in the answering process therefore holds only the replies that are still
  to come. A real model needs nothing special: it is called with the recovered
  conversation.
- `governor.answer(...)` sends `Event("approved")` with no payload. The refund runs once,
  in the second process, and the agent finishes.

**Make it yours.**

- Put `park` and `recover_and_answer` in two programs that import the tool from one shared
  module, and point `SqliteJournal` at a path both can open.
- To refuse, answer with `Event("denied", {"reason": "..."})`. The tool does not run, and
  the model is told why.
- Pass `entitlement=` and `by=` as the [first recipe](#approve-a-tool-call) does, so the
  journal records who approved.
- Swap both `ScriptedModel`s for one [vendor model](guides/vendors.md).

**Go deeper.** [Asking a person](guides/shortcuts.md#step-4-asking-a-person) covers
`approve=` and `Unanswered`, and [Crash and resume](tutorials/durability.md) covers a
process that stops while a tool is running.

## Test an agent offline {#test-an-agent-offline}

**The problem.** You have an agent with a tool that needs approval, and you want tests that
prove three things: the tool does nothing before a person agrees, a denied call never runs,
and the run ends the way you expect. The tests must run in CI with no API key and no
network.

**How gvn solves it.** Every part that touches the outside world has a stand-in in
`gvn.testing.fakes`. The agent, the policy and the Governor in the test are the real ones.

| The real part | The stand-in | What the test reads from it |
|---|---|---|
| The model | `ScriptedModel`, which returns the replies you list | |
| The tool with an effect | `StubTool`, which records each call and returns a fixed result | `calls()`: every call that ran |
| The person | the `approve` function you pass to `run_agent` | what was true at the moment it was asked |
| The database | `MemoryJournal` | the events of the run, in order |
| The clock | `ManualClock` | |

**Run it.** Save the script as `check_agent_offline.py`. Run it as a script with
`python check_agent_offline.py`, or as tests with `pytest check_agent_offline.py` if you
have pytest installed.

```python { .recipe #check-agent-offline-script data-filename="check_agent_offline.py" }
import asyncio

from gvn.harness.events import Request
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import AgentRun, AskBeforeEveryCall, run_agent
from gvn.testing.fakes import ManualClock, MemoryJournal, ScriptedModel, StubTool

CALL = ToolCall(call_id="1", name="send_email", arguments={"to": "ana@example.com"})


def stub_email() -> StubTool:
    return StubTool(name="send_email", arguments=Record({"to": Text()}), result={"sent": True})


def run_harness(email: StubTool, approve) -> AgentRun:
    model = ScriptedModel(script=[
        Reply(message=Message.assistant(calls=[CALL])),
        Reply(message=Message.assistant(text="Done.")),
    ])
    return asyncio.run(run_agent(
        instructions="Email the customer when asked.",
        prompt="Tell Ana her order shipped.",
        model=model,
        tools=[email],
        policy=AskBeforeEveryCall(),
        approve=approve,
        journal=MemoryJournal(),
        clock=ManualClock(),
        name="email-ana",
    ))


def event_names(run: AgentRun) -> list[str]:
    records = asyncio.run(run.journal().read("email-ana"))
    return [record["event"]["name"] for record in records]


def test_nothing_is_sent_before_approval() -> None:
    email = stub_email()
    sent_when_asked = []

    def approve(request: Request) -> bool:
        sent_when_asked.append(email.calls())
        return True

    run = run_harness(email, approve)
    assert sent_when_asked == [()]
    assert email.calls() == ({"to": "ana@example.com"},)
    assert run.outcome().payload()["text"] == "Done."


def test_a_denied_email_is_never_sent() -> None:
    email = stub_email()
    run = run_harness(email, lambda request: False)
    assert email.calls() == ()
    assert run.state().name() == "completed"
    assert "denied" in event_names(run) and "tools_returned" not in event_names(run)


def test_the_journal_records_the_approval() -> None:
    run = run_harness(stub_email(), lambda request: True)
    assert event_names(run) == [
        "started", "model_replied", "needs_approval", "approved",
        "tools_returned", "model_replied",
    ]


if __name__ == "__main__":
    for check in (
        test_nothing_is_sent_before_approval,
        test_a_denied_email_is_never_sent,
        test_the_journal_records_the_approval,
    ):
        check()
        print(f"ok  {check.__name__}")
```

Run as a script, it prints:

```text { .expected-output }
ok  test_nothing_is_sent_before_approval
ok  test_a_denied_email_is_never_sent
ok  test_the_journal_records_the_approval
```

**What each part is for.**

- `run_harness` is the code under test: one `run_agent` call with a fresh scripted model and
  a fresh journal each time, so no test sees another's leftovers. In your project it is the
  function that builds your agent, with the model and the tool passed in.
- `test_nothing_is_sent_before_approval` looks at the stub from inside `approve`. That is
  the moment a person would be looking at the request, and `email.calls()` is still empty.
  After the run it holds exactly one call, with the arguments the model asked for.
- `test_a_denied_email_is_never_sent` answers `False`. The stub has no calls, the journal
  has a `denied` event and no `tools_returned` event, and the run still ends `completed`,
  because the model was told about the denial and gave its final answer.
- `test_the_journal_records_the_approval` compares the event names with the full list. It
  is the strictest of the three checks: any extra model call or tool call changes the list.
- `run.outcome().payload()["text"]` is the agent's final answer.
- The `__main__` block runs the same functions without pytest and prints one line for each.

**Make it yours.**

- Give `StubTool` a function as `result=` to compute the result from the arguments, or an
  exception to see how your agent handles a tool that fails.
- Replace `AskBeforeEveryCall()` with your own policy, so the test covers the rule you
  ship.
- For a structured answer, script the last reply with `answer_reply(data=...)` and assert
  on `run.answer()`, as [Structured answers](guides/structured-answers.md) shows.

**Go deeper.** The tutorial [Testing your harness](tutorials/testing.md) adds tests of a
policy on its own and a crash matrix, and the concept page
[Testing your harness](concepts/testing.md) covers the stand-ins in detail.

## A two-stage workflow: an agent assesses, a person approves the payment {#a-two-stage-workflow}

**The problem.** An expense claim comes in. A model should read the claim and the spending
limit and decide: approve, reject or escalate. If it approves, the claim must be paid, but
only after a person agrees, and the model must have no say in what is paid.

**How gvn solves it.** A **workflow** is an actor made of other actors. It has its own small
state machine, and each state that does work is a **stage** that runs one child actor. This
workflow has two stages.

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> assessing : started
    assessing --> paying : approve
    assessing --> rejected : reject
    assessing --> escalated : escalate
    assessing --> failed : assessment_failed
    paying --> paid : paid
    paying --> payment_denied : payment_denied
    paying --> failed : payment_failed
    paid --> [*]
    rejected --> [*]
    escalated --> [*]
    payment_denied --> [*]
    failed --> [*]
```

- **`assessing` runs an agent.** It has two read-only tools and must end with a
  **structured answer**: data that fits a schema you give (`decision`, `amount`,
  `reasons`) instead of free text. A **judge**, a small class of yours, reads that answer
  and tells the workflow which way to go.
- **`paying` runs an Errand.** An [Errand](concepts/errands.md) is an agent with the model
  taken out: your code fixes its tool calls when it is built. By this stage nothing is left
  to decide. The claim and the amount are known, so the workflow builds one fixed call to
  `pay_claim` from them. No model can change the amount or add a call. The call still goes
  past the policy and past a person, and it is recorded in the journal, exactly as an
  agent's call is.

The whole workflow is one run with one journal. When the Errand parks on its approval, the
workflow parks with it.

**Run it.** Save the script as `claims_workflow.py` and run `python claims_workflow.py`.

```python { .recipe #claims-workflow-script data-filename="claims_workflow.py" }
import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory

from gvn.adapters.sqlite import SqliteJournal
from gvn.harness.agent import VERDICTS, Agent
from gvn.harness.errand import Errand
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall
from gvn.harness.ports import Reply
from gvn.harness.tools import FixedCall, Toolbox
from gvn.harness.workflow import Host, Memo, Plan, Report, Workflow
from gvn.kernel.blueprint import MooreBlueprint
from gvn.kernel.decision import Decision
from gvn.kernel.schema import ListOf, Number, OneOf, Record, Text
from gvn.kernel.symbols import Alphabet, Symbol
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.runtime.recovery import Recovery
from gvn.shortcuts import FunctionTool
from gvn.testing.fakes import ManualClock, RecordingOutput, ScriptedModel, answer_reply

payments = []


def get_claim(claim_id: str) -> dict[str, object]:
    return {"claim_id": claim_id, "category": "travel", "amount": 120.0}


def get_limit(category: str) -> dict[str, object]:
    return {"category": category, "limit": 500.0}


def pay_claim(claim_id: str, amount: float) -> dict[str, bool]:
    payments.append((claim_id, amount))
    return {"paid": True}


def tool(function, description: str, arguments: Record, independent: bool) -> FunctionTool:
    return FunctionTool(
        name=function.__name__, description=description, arguments=arguments,
        function=function, independent=independent, namespace="claims",
    )


claim_tool = tool(get_claim, "Read one expense claim.", Record({"claim_id": Text()}), True)
limit_tool = tool(get_limit, "Read a category's limit.", Record({"category": Text()}), True)
PAYMENT = Record({"claim_id": Text(), "amount": Number()})
pay_tool = tool(pay_claim, "Pay an expense claim.", PAYMENT, False)
ASSESSMENT = Record({
    "decision": OneOf("approve", "reject", "escalate"),
    "amount": Number(),
    "reasons": ListOf(Text()),
})
DECISIONS = Alphabet.of("approve", "reject", "escalate", "assessment_failed")
MACHINE = (
    MooreBlueprint(name="claim")
    .inputs("started", *DECISIONS.names(), "paid", "payment_denied", "payment_failed")
    .outputs("idle", "assess", "pay", "paid", "rejected", "escalated", "unpaid", "failed")
    .state(name="idle", output="idle")
    .state(name="assessing", output="assess")
    .state(name="paying", output="pay")
    .state(name="paid", output="paid", final=True)
    .state(name="rejected", output="rejected", final=True)
    .state(name="escalated", output="escalated", final=True)
    .state(name="payment_denied", output="unpaid", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="assessing")
    .branch(source="assessing", outcomes=DECISIONS, routes={
        "approve": "paying", "reject": "rejected",
        "escalate": "escalated", "assessment_failed": "failed",
    })
    .on(source="paying", input="paid", target="paid")
    .on(source="paying", input="payment_denied", target="payment_denied")
    .on(source="paying", input="payment_failed", target="failed")
    .otherwise_stay()
    .build()
)


class RouteOnTheDecision(Decision):
    def outcomes(self) -> Alphabet:
        return DECISIONS

    def judge(self, ending: object) -> Symbol:
        outcome = ending.outcome()
        if outcome.state().name() != "completed":
            return Symbol("assessment_failed")
        return Symbol(outcome.payload()["answer"]["decision"])


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

    def judge(self, consultation: object) -> Symbol:
        asks = consultation.calls_to(pay_tool)
        return VERDICTS.named("needs_approval" if asks else "cleared")


def make_assessor(name: str, memo: Memo) -> Agent:
    instructions = "Read the claim and its category's limit, then assess the claim."
    tools = [claim_tool, limit_tool]
    return Agent(name=name, instructions=instructions, tools=tools, answer=ASSESSMENT)


def start_assessor(memo: Memo) -> Event:
    return Event("started", {"prompt": f"Assess claim {memo.input()['claim_id']}."})


def make_payment(name: str, memo: Memo) -> Errand:
    claim_id = memo.input()["claim_id"]
    amount = memo.results("assessing")[0].payload()["answer"]["amount"]
    return Errand(
        name=name,
        calls=[FixedCall("pay", pay_tool, {"claim_id": claim_id, "amount": amount})],
        text=f"Pay {amount} for claim {claim_id}.",
    )


class ClaimWorkflow(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return Plan(
            definition=MACHINE,
            stages={
                "assessing": Host(
                    actor_class=Agent, make=make_assessor, start=start_assessor,
                    judge=RouteOnTheDecision(),
                ),
                "paying": Host(
                    actor_class=Errand, make=make_payment,
                    start=lambda memo: Event("started"),
                    routes={
                        "done": "paid", "declined": "payment_denied",
                        "refused": "payment_denied", "failed": "payment_failed",
                    },
                ),
            },
            tools=[claim_tool, limit_tool, pay_tool],
        )


def build_governor(journal: SqliteJournal, model: ScriptedModel) -> Governor:
    toolbox = Toolbox(tools=[claim_tool, limit_tool, pay_tool])
    return Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=PaymentsNeedApproval()),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
        },
        external=["request_approval"], journal=journal,
        clock=ManualClock(), output=RecordingOutput(),
    )


def assessor_script(decision: str) -> ScriptedModel:
    reads = [
        ToolCall(call_id="1", name="get_claim", arguments={"claim_id": "C-1"}),
        ToolCall(call_id="2", name="get_limit", arguments={"category": "travel"}),
    ]
    answer = {"decision": decision, "amount": 120.0, "reasons": ["within the travel limit"]}
    asks_to_read = Reply(message=Message.assistant(calls=reads))
    return ScriptedModel(script=[asks_to_read, answer_reply(data=answer)])


async def run_claim(path: Path, run_id: str, decision: str, answer: Event | None) -> None:
    payments.clear()
    journal = SqliteJournal(path=path)
    try:
        result = await build_governor(journal, assessor_script(decision)).deliver(
            actor=ClaimWorkflow(name=run_id), event=Event("started", {"claim_id": "C-1"})
        )
        if result.status() == "waiting":
            print(f"{run_id}: waiting, asked: {result.pending()[0].payload()['text']}")
    finally:
        await journal.close()
    journal = SqliteJournal(path=path)
    try:
        run = await Recovery(journal=journal).recover(run_id=run_id, actor_class=ClaimWorkflow)
        if run.pending():
            (request,) = run.pending()
            nothing_left_to_say = ScriptedModel(script=[])
            governor = build_governor(journal, nothing_left_to_say)
            await governor.answer(actor=run, request=request, event=answer)
        assessed = Report(run.outcome()).results("assessing")[0].payload()["answer"]
        print(f"{run_id}: assessed {assessed['decision']}, "
              f"ended {run.state().name()}, payments {payments}")
    finally:
        await journal.close()


if __name__ == "__main__":
    with TemporaryDirectory() as directory:
        path = Path(directory) / "claims.db"
        asyncio.run(run_claim(path, "claim-1", "approve", Event("approved")))
        asyncio.run(run_claim(path, "claim-2", "approve", Event("denied", {"reason": "duplicate"})))
        asyncio.run(run_claim(path, "claim-3", "reject", None))
```

It prints:

```text { .expected-output }
claim-1: waiting, asked: Pay 120.0 for claim C-1.
claim-1: assessed approve, ended paid, payments [('C-1', 120.0)]
claim-2: waiting, asked: Pay 120.0 for claim C-1.
claim-2: assessed approve, ended payment_denied, payments []
claim-3: assessed reject, ended rejected, payments []
```

The three claims are: approved and paid, approved by the agent but denied by the person,
and rejected by the agent.

**What each part is for.**

- `MACHINE` is the diagram above as code. `started` is delivered by you. Every other input
  is produced by a stage.
- `RouteOnTheDecision` is the judge. It reads the agent's structured answer from the outcome
  payload, `outcome.payload()["answer"]`, and returns its `decision` as the next input of
  the machine. The answer was already checked against `ASSESSMENT`, so the judge reads plain
  data.
- `PaymentsNeedApproval` is the policy. One policy serves both stages: the two read-only
  tools are cleared, and a call to `pay_tool` needs approval.
- `make_assessor` and `make_payment` build each stage's child when the workflow enters the
  stage. Both get a `Memo`, the workflow's notes so far: `memo.input()` is the payload of
  the `started` event, and `memo.results("assessing")` holds the finished agent's outcome.
  `make_payment` takes the amount from there, again under `["answer"]`.
- `routes` on the `paying` stage turns the Errand's final state into the machine's next
  input. An Errand ends `done` when its call ran, `declined` when a person denied it,
  `refused` when the policy forbade it and `failed` when the tool failed.
- `Plan(..., tools=[...])` lists every tool any stage uses, so the Governor can check it
  holds them all before the run starts.

**How the workflow parks, and how the answer reaches the Errand.**

- A workflow's pending requests are its children's. When the Errand asks for approval,
  `deliver` returns `waiting` and the request's text is the Errand's `text`.
- The request's id starts with the child's name: `claim-1/paying.1/request_approval`.
  You answer the workflow, with `governor.answer(actor=run, request=request, ...)`. The
  Governor addresses your event to `claim-1/paying.1`, and the workflow hands it to that
  child. You never hold the Errand yourself.
- `run_claim` closes the journal after the first half and opens it again, as a second
  process would. `Recovery` rebuilds the whole workflow, children included, from the one
  run id.
- The Governor that answers gets a scripted model with no replies. Paying needs no model
  call, so none is made.
- `claim-3` never parks. It is recovered already finished, and its outcome is read the
  same way.
- `Report(run.outcome())` reads a finished workflow's outcome. `results("assessing")[0]`
  is the agent's outcome, and its structured answer is under `payload()["answer"]`.

**Make it yours.**

- Replace `get_claim`, `get_limit` and `pay_claim` with calls to your own systems, and
  swap the scripted model for a [vendor model](guides/vendors.md).
- Add `entitlement=` to the Governor and `by=` to the answer, as the
  [first recipe](#approve-a-tool-call) does, so only finance may approve a payment.
- Test it with the stand-ins from [Test an agent offline](#test-an-agent-offline): assert
  that `payments` is empty while the run is `waiting`.

**Go deeper.** [Compose two actors](tutorials/workflow.md) builds a workflow step by step,
[Workflows](concepts/workflows.md) explains stages, judges and the memo,
[Errands](concepts/errands.md) covers the Errand's states and outcome, and
[Structured answers](guides/structured-answers.md) covers the answer schema.

## Where to go next

- [Add tool approval to your own agent](tutorials/agent-with-approval.md), step by step.
- [Compose two actors](tutorials/workflow.md) into a workflow of your own.
- [Connect a real model](guides/vendors.md) in place of the scripted one.
- [Run it as a service](guides/running-as-a-service.md) when several workers share one
  journal.
- Read complete harnesses with their offline tests in the [domain examples](domains/index.md).
