# Run context

**What you will learn:** how to give an agent trusted facts about its job (which alert, which
customer) that its tools and its tool policy can check, and that the model can neither read
nor change.

**Read first:** [The reference agent](reference-agent.md), which introduces tools, the tool
policy and the agent's outcome, and [The Governor](governor.md), which runs it.
**Time:** about 15 minutes.

## Where run context sits

In the [loop that runs](index.md#picture-1-the-loop-that-runs), run context is part of the
**actor**'s data: a few facts your code fixes when it builds an agent. The agent copies them
onto each **request** it makes, and the Governor hands each request to its fulfiller. Two
fulfillers pass the context on, to the tool policy and to the tools; the one that calls the
model holds it back.

```mermaid
flowchart LR
    code(["Your code"]) -- "context=" --> agent["Agent<br/>holds the context"]
    agent -- "every request carries it" --> governor["Governor"]
    governor --> policy["Policy fulfiller<br/>context in the Consultation"]
    governor --> tools["Tool fulfiller<br/>context in the Invocation"]
    governor --> model["Model fulfiller<br/>context never sent"]
```

## The problem: the model should not say whose job this is

An agent works on one job at a time: one alert, one customer's case, one release. The code
that starts the job knows which alert, which customer, which release. The model does not,
and must not be the one to say so. If a tool takes the customer's id as an argument, a
confused or manipulated model can name another customer.

Picture an on-call agent sent to fix alert `A-17`, which is about host `web-1`. The model
reads the alert, notices that `db-1` "looks odd too", and asks to restart it. Nothing in the
model's request is wrong in form. What is wrong is that `db-1` is not part of this job, and
only your code knows that.

gvn separates the two kinds of fact. Facts that come from your code travel as the agent's
**run context**: trusted plain JSON, fixed for the run, that tools and the tool policy can
read and the model never sees. Arguments still come from the model, and are checked against
that context before anything happens.

## Step 1: give the agent its context

The on-call agent has one tool, `restart`, which restarts the service on one host. Here it
is; [Step 3](#step-3-the-tool-checks-again-at-the-moment-of-the-effect) comes back to what
its `run` checks. A list stands in for the outside world, so you can see what was restarted:

```python
import asyncio
import typing

from gvn.harness.tools import Invocation, Tool
from gvn.kernel.schema import Record, Text


class Restart(Tool):
    def __init__(self, restarted: list[str]) -> None:
        self._restarted = restarted  # the outside world, for this example

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

    def description(self) -> str:
        return "Restart the service on one host."

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

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        host = arguments["host"]
        if host not in invocation.context().get("hosts", []):
            raise PermissionError(f"{host} is not one of this alert's hosts")
        self._restarted.append(host)  # the side effect
        return {"restarted": host}


restarted = []
restart_tool = Restart(restarted)
```

You give an agent its context when you build it, with the `context` parameter, next to the
tools it is offered (passed as objects; [Tools](tools.md) explains why):

```python
from gvn.harness.agent import Agent

oncall_agent = Agent(
    name="oncall",
    instructions="Fix the alert.",
    tools=[restart_tool],
    context={"alert": "A-17", "hosts": ["web-1"]},
)
print(oncall_agent.context())
```

```text
{'alert': 'A-17', 'hosts': ['web-1']}
```

Three rules apply:

- It must be `None` or a dict of plain JSON. Anything else is a `TypeError` or `ValueError`
  when the agent is built.
- It is copied when the agent is built, and `context()` returns a fresh copy each time.
  Changing the dict you passed in, or the one you got back, changes nothing.
- It is fixed for the agent's life and stored in the agent's
  [Dto](durable-objects.md) (the plain-data form it is saved in), so a run recovered after a
  crash has the same context it started with.

## Step 2: the policy checks each call against it

The rule "only this alert's hosts may be restarted" can be enforced in two places, and a
careful harness does both. The first is the **tool policy**: it sees each tool call before
anything runs and can forbid it. A forbidden call never reaches a tool, and the model is told
why.

A policy is a [Decision](decisions.md) over a `Consultation` (in `gvn.harness.tools`): the
thing a policy decides on. `calls()` is a tuple holding the `ToolCall` to judge (in a run,
`PolicyFulfiller` asks about each call of a reply on its own; see
[one verdict per call](reference-agent.md#one-verdict-per-call)), and `identities()` the
identity of its tool. `calls_to(tool)` picks the judged calls to one tool, matched by
identity, so a policy names the tool object it guards. `origin()` names the agent that
asked, and `context()` is a copy of its run context.

```python
from gvn.harness.agent import VERDICTS
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol


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

    def judge(self, consultation: object) -> Symbol:
        hosts = consultation.context().get("hosts", [])
        for call in consultation.calls_to(restart_tool):
            if call.arguments().get("host") not in hosts:
                return VERDICTS.named("forbidden")
        return VERDICTS.named("cleared")


restart_db = ToolCall(call_id="c1", name="restart", arguments={"host": "db-1"})
consultation = Consultation(
    calls=[restart_db],
    identities=[restart_tool.identity()],
    origin=oncall_agent.name(),
    context=oncall_agent.context(),
)
print(OnlyThisAlertsHosts().decide(consultation))
```

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

The host came from the model, as an argument. The allowed hosts came from the context. The
policy compared the two and said no.

## Step 3: the tool checks again at the moment of the effect

The second place is the tool itself. It checks again just before it acts, and raises rather
than act outside the context. That holds even if the tool is wired under a different policy,
or called by code of your own.

A tool receives two things in `run(arguments, invocation)`: the `arguments` the model sent,
and an `Invocation` with the trusted values. `invocation.key()` is an [idempotency key](#idempotency-keys) (a key that stays the same when
the same call is repeated after a crash, explained below),
`invocation.origin()` names the agent that asked, and `invocation.context()` is a copy of its
run context. `Restart.run` above reads the allowed hosts from `invocation.context()`, never
from its arguments.

Call it directly, once inside the job and once outside it:

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

invocation = Invocation(key="oncall/3#c1", origin="oncall", context=oncall_agent.context())

print(asyncio.run(restart_tool.run(arguments={"host": "web-1"}, invocation=invocation)))
try:
    asyncio.run(restart_tool.run(arguments={"host": "db-1"}, invocation=invocation))
except PermissionError as refused:
    print("refused:", refused)
print(restarted)
```

```text
{'restarted': 'web-1'}
refused: db-1 is not one of this alert's hosts
['web-1']
```

`web-1` was restarted; `db-1` was not touched.

## Step 4: the whole run

Now put the pieces in a real run, driven by the [Governor](governor.md) with the same three
fulfillers and fakes as on that page. A scripted model plays the confused model: it asks to
restart `db-1`, then gives up.

The run below happens twice: once under the real policy, and once under a policy that clears
everything, to show the tool holding the line on its own.

```python
from gvn.harness.events import Event
from gvn.harness.messages import Message
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel


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

    def judge(self, consultation: object) -> Symbol:
        return VERDICTS.named("cleared")


def run_oncall(
    policy: Decision, restarted: list[str]
) -> tuple[list[dict[str, typing.Any]], ScriptedModel]:
    toolbox = Toolbox(tools=[Restart(restarted)])
    model = ScriptedModel(
        script=[
            Reply(message=Message.assistant(calls=[restart_db])),
            Reply(message=Message.assistant(text="I could not restart db-1.")),
        ]
    )
    governor = Governor(
        fulfillers={
            "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
            "invoke_tools": ToolFulfiller(toolbox=toolbox),
            "consult_policy": PolicyFulfiller(decision=policy),
        },
        journal=MemoryJournal(),
        output=RecordingOutput(),
        clock=ManualClock(),
    )
    agent = Agent(
        name="oncall",
        instructions="Fix the alert.",
        tools=toolbox,
        context={"alert": "A-17", "hosts": ["web-1"]},
    )
    started = Event(name="started", payload={"prompt": "web-1 is slow, and db-1 looks odd too."})
    result = asyncio.run(governor.deliver(actor=agent, event=started))
    return result.outcome().payload()["attempts"], model
```

`run_oncall` builds a fresh `Restart` for each run. The policy still sees its calls as calls
to `restart_tool`, because the two are the same tool: every `Restart` has the identity of
its class's module and its short name. First under the real policy, then under the lax one:

```python
restarted = []
attempts, model = run_oncall(policy=OnlyThisAlertsHosts(), restarted=restarted)
print(attempts[0]["status"], attempts[0]["detail"])

attempts, model = run_oncall(policy=AllowEverything(), restarted=restarted)
print(attempts[0]["status"], attempts[0]["detail"]["detail"])

print(restarted)
```

```text
forbidden not run: the policy forbade this call
failed PermissionError: db-1 is not one of this alert's hosts
[]
```

Under the real policy the call was never made: the agent recorded it as `forbidden` and the
model was told. Under the lax policy the tool refused, and the agent recorded a `failed`
attempt. In neither case did the effect happen. The `attempts` list in the agent's outcome
(see [the reference agent](reference-agent.md#outcomes)) records both, so a workflow or an
evaluation can see what the model tried as well as what ran.

## Step 5: the model never sees it

`ModelFulfiller` builds the model's `Exchange` (what is sent to the model) from the
instructions, the messages and the tool specs only. The context is not among them. The
scripted model remembers every exchange it was sent, so you can look:

```python
exchange = model.exchanges()[0]
print([message.text() for message in exchange.messages()])
print("A-17" in repr(exchange))
```

```text
['web-1 is slow, and db-1 looks odd too.']
False
```

That has two consequences. The model cannot read data it was not meant to see (another
customer's id, an internal ticket number), and it cannot supply or overwrite a value that
must be right: a tool that needs the customer reads it from `invocation.context()`, not from its
arguments. If the model needs to know something, put it in the prompt; if a tool needs to
rely on it, put it in the context.

That is the 80% you need. The rest of this page is detail you can come back to.

## Deeper: where the context goes

Every request the agent issues carries the context as `"context"` in its payload. The
built-in fulfillers hand it on, or hold it back:

| Request | Fulfiller | What happens to the context |
|---|---|---|
| `invoke_model` | `ModelFulfiller` | **never sent to the model** |
| `consult_policy` | `PolicyFulfiller` | handed to the policy inside a `Consultation` |
| `request_approval` | (external: a person) | in the request payload, so the approver sees it |
| `invoke_tools` | `ToolFulfiller` | handed to each tool inside an `Invocation` |
| `remember` | `MemoryFulfiller` | read for the memory scope when the scope comes from the context ([Memory](memory.md), a later page) |
| `recall` | `MemoryFulfiller` | read for the memory scope under the same rule |
| `sense` | `SensorFulfiller` | handed to each measuring tool inside an `Invocation` |

## Deeper: where the context comes from in a workflow

In a [workflow](workflows.md) (a later page: a machine that runs several agents as stages),
the stage's `make` function builds each agent, and it usually takes the context from the
run's input: `Agent(name=..., instructions=..., context=memo.input())`, where `memo` is the
workflow's record of its run so far. The input is the payload of the event that started
the workflow. The harnesses in [gvn-domains](../domains/index.md) validate the starting
brief against a schema. A stage can pass its relevant fields to a child or construct a
more specific context from trusted inputs and earlier results.

## Deeper: idempotency keys {#idempotency-keys}

`invocation.key()` is the other trusted value a tool receives. It is `"<request id>#<tool call
id>"`: the same every time the same call of the same run is re-issued after a crash, and
different for every other call. Work in flight when a process dies runs again (at least
once), so a tool with a side effect passes the key to the service it calls as that service's
idempotency key, or remembers the keys it has completed. The key, like the context, comes
from the runtime, never from the model. [The Governor](governor.md#at-least-once-and-request-ids)
has a worked example.

The key does not cover everything. An agent that is interrupted after a tool acted, and then
resumed, asks its model again: the next call is a new call with a new key, even when it asks
for the same thing. An effect that must happen at most once whatever happens to the run (a
payment, a deployment, a signature) should therefore be keyed by what it is, built from the
trusted `invocation.context()` (for example `"promote:<service>:<version>"`), not by `invocation.key()`
alone.

## What belongs in it

- **Identifiers and allowed targets.** The agent saves context in its Dto, so a journal
  snapshot contains it. Requests carry context to fulfillers at runtime. Put the alert ID,
  customer ID and allowed hosts in it. Give credentials to the ports your tools use.
- **Facts fixed for the run.** It cannot change during a run. Data that changes belongs in an
  actor's own durable objects, or in the outside world behind a tool.
- **Whose memory, not the memory.** It lasts as long as the actor and is written only by your
  code. Text that must outlive the run, written by the model or handed over by a context
  budget, belongs in a [memory](memory.md), a later page; the run context can say whose memory
  that is.
- **What arguments are checked against.** A tool's `arguments()` schema still validates what
  the model sends; the context is what those arguments are checked *against*.

## Recap

- The run context is trusted plain JSON your code gives the agent with `context=`. It is
  copied, fixed for the run, and survives a crash.
- The policy sees it in the `Consultation` and can forbid a call before anything runs.
- The tool sees it in the `Invocation` and should refuse to act outside it.
- The model never sees it, so it can neither read nor overwrite it.
- It holds identifiers, not secrets, and works beside argument schemas.

**Next:** [Streaming and observability](streaming-and-observability.md), how you watch a run
while the Governor drives it.
