# Errands

**What you will learn:** how to make a fixed batch of tool calls safely (past the policy,
past a person when needed, once, durably) without a model in the loop.

**Read first:** [the reference agent](reference-agent.md), [run context](run-context.md) and
[Humans and interruption](human-in-the-loop.md). **Time:** about 15 minutes.

## Where this sits

An errand is one more **actor** in the harness layer ([the big picture](index.md#picture-1-the-loop-that-runs)):
a verified machine plus its data, driven by the Governor like any other. It is the
[reference agent](reference-agent.md) with the model taken out. The agent asks a model which
tools to call; an errand is handed its tool calls by your code when it is built. From there
the two walk the same path through the same fulfillers: the policy fulfiller vets the calls,
a person approves them when the policy says so, and the tool fulfiller runs them. So
everything you learned about policies, approvals, interrupts and the journal applies here
unchanged.

## The problem: effects a model has no business choosing

Not every effect needs a model to decide on it. A data backfill knows exactly which
partitions to copy. A release knows which tag to push. A step of a larger job often knows
exactly which tool calls it must make (publish these partitions, tag this release, page this
team) and only needs them made safely: past the policy, past a person when the policy says so, once,
durably.

You could call the tools directly from your own code, but then you lose what the agent gives you
for free: the policy check, the approval, the journal, and a clean answer to "did this
already happen?" after a crash.

`gvn.harness.errand.Errand` is that step: a batch of tool calls fixed by code, with no
model. Your code fixes each call as a **`FixedCall`**: a call id, the tool object itself and
its arguments. As everywhere in gvn, the tool is passed as an object, never by name; the
errand keeps its short name and its identity ([Tools](tools.md) explains the two names).

## Step 1: build an errand

Here an errand copies two partitions of the `sales` dataset. A `StubTool`, the test tool
from `gvn.testing.fakes`, stands in for the copy tool:

```python
from gvn.harness.errand import Errand
from gvn.harness.events import Event
from gvn.harness.tools import FixedCall
from gvn.kernel.schema import Record, Text
from gvn.testing.fakes import StubTool

copy_partition = StubTool("copy_partition", Record({"partition": Text()}))
copy_calls = [
    FixedCall("c1", copy_partition, {"partition": "2026-11-01"}),
    FixedCall("c2", copy_partition, {"partition": "2026-11-02"}),
]
backfill = Errand(
    name="backfill/stage",
    calls=copy_calls,
    context={"dataset": "sales", "partitions": ["2026-11-01", "2026-11-02"]},
    text="Copy two partitions of sales.",
)
print(backfill.state(), len(backfill.calls()))
print(backfill.calls()[0])
print(backfill.tool_identities())
```

```text
State('idle') 2
ToolCall(call_id='c1', name='copy_partition', arguments={'partition': '2026-11-01'})
frozenset({'gvn.testing.fakes.copy_partition'})
```

- `name`: the errand's address, which also prefixes its request ids (see
  [durability and repeats](#deeper-durability-and-repeats)).
- `calls`: a non-empty sequence of `FixedCall`s with distinct ids, fixed for the errand's
  life. `calls()` returns them as `ToolCall`s (the call id, the tool's short name, the
  arguments), as a model's reply would hold them; `identities()` is the identity of each
  call's tool, in call order, and `tool_identities()` the set of them, which the Governor
  checks against its toolbox before the run starts.
- `context`: the [run context](run-context.md), trusted data handed to the policy and to every
  tool, exactly as for an agent.
- `text`: what a person asked to approve the batch is shown.

## Step 2: the machine

The errand walks the same safety path as the agent's tool calls: vet, maybe ask, act, check.

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> vetting : started
    vetting --> acting : cleared
    vetting --> awaiting_approval : needs_approval
    vetting --> refused : forbidden
    vetting --> suspended : interrupted
    awaiting_approval --> acting : approved
    awaiting_approval --> declined : denied
    awaiting_approval --> suspended : interrupted
    acting --> checking : tools_returned
    acting --> suspended : interrupted
    checking --> done : succeeded
    checking --> failed : call_failed
    checking --> refused : call_refused
    suspended --> vetting : resumed
    done --> [*]
    failed --> [*]
    refused --> [*]
    declined --> [*]
```

`vetting`, `awaiting_approval` and `acting` ask for `consult_policy`, `request_approval` and
`invoke_tools`: the reference agent's request kinds, with the agent's payloads. One request
carries the whole batch, and the standard `PolicyFulfiller` and `ToolFulfiller` serve it
unchanged. `suspended` is where an `interrupted` event parks the errand until `resumed`
([Humans and interruption](human-in-the-loop.md)). `checking` is an internal decision over what became of each call: `failed` when a
call that ran reported failure; else `refused` when some call did not run because the policy
forbade it or a person denied it (or it was skipped after such a refusal); else `done`, every
call ran and succeeded. A failure wins over a refusal. `refused` is also where a batch the
policy forbade outright ends, straight from `vetting`, with nothing run.

You can watch the requests by handing the errand events yourself, without a Governor. Here
it starts, and the policy answers `needs_approval`:

```python
for event_name in ("started", "needs_approval"):
    (request,) = backfill.handle(Event(event_name)).requests()
    print(request.kind().name(), sorted(request.payload()))
```

```text
consult_policy ['calls', 'context', 'identities']
request_approval ['calls', 'context', 'identities', 'text']
```

## Step 3: the outcome

Every final state reports an **outcome** (the result an actor hands back when it finishes;
see [the agent's outcomes](reference-agent.md#outcomes)) with the payload `{"attempts": [...]}`, one entry per call in the order given, each
`{"name", "identity", "arguments", "status", "detail"}`, with
the [agent's statuses](reference-agent.md#what-became-of-each-call): `ok` and `failed` (the
tool ran), `forbidden` (the policy refused the call), `denied` (a person refused it),
`skipped` (it came after a refused call) and `abandoned` (see
[a batch with mixed verdicts](#deeper-a-batch-with-mixed-verdicts)). When the policy gives the
whole batch one verdict, they are simple: every call `ok` in `done`, every call `forbidden`
in `refused`, every call `denied` in `declined`.

Approve the batch, then report both tool results. They may come back in any order:

```python
from gvn.harness.messages import ToolResult

backfill.handle(Event("approved"))
results = [
    ToolResult(call_id="c2", content={"copied": "2026-11-02"}),
    ToolResult(call_id="c1", content={"copied": "2026-11-01"}),
]
backfill.handle(Event("tools_returned", {"results": [r.to_dto().to_plain() for r in results]}))
print(backfill.state())
attempts = backfill.outcome().payload()["attempts"]
print([(attempt["arguments"]["partition"], attempt["status"]) for attempt in attempts])
```

```text
State('done')
[('2026-11-01', 'ok'), ('2026-11-02', 'ok')]
```

The attempts are listed in the order the calls were given, not the order the results came
back. `tools_returned` must answer every call exactly once, in any order; anything else is a
`ValueError` that changes nothing.

That is the 80% you need. The rest explains why an errand is safe to repeat.

## Deeper: durability and repeats

An Errand's request ids are stable for its whole life: `"<name>/consult_policy"`,
`"<name>/request_approval"` and `"<name>/invoke_tools"`. The batch is fixed when the errand is
built, so the same work always carries the same identity, and `ToolFulfiller` gives each tool
the same key (`"<name>/invoke_tools#<call id>"`) every time the batch is run.

```python
vendor_payment = Errand(name="pay/vendor-7", calls=copy_calls)
print([request.request_id() for request in vendor_payment.handle(Event("started")).requests()])
```

```text
['pay/vendor-7/consult_policy']
```

Stable keys let a tool deduplicate its effect after either disruption. A tool is
**idempotent by key** when a repeat returns the earlier result without applying the effect
again. The tool or the service performing the effect must enforce that guarantee.
[At least once](governor.md#at-least-once-and-request-ids) explains the crash boundary.

- **A crash.** Recovery ([the Governor](governor.md)) re-issues the request the errand still wants, with the same id.
- **An interrupt.** `interrupted` drops the batch in flight (a late `tools_returned` is
  rejected while suspended), and `resumed` goes back to `vetting` and asks for the same batch
  again. A tool that had already acted sees the same key a second time and returns what it
  returned before instead of acting again.

What does not carry over is a decision: a verdict or an approval given before the interrupt.
Resuming vets the batch again and, if the policy says so, asks a person again. Answer the
current pending request with `Governor.answer`. Its ID is stable, and its payload describes
the calls that need approval under the new verdicts. That is why
an interrupt never leaves an Errand's call `abandoned`: either the batch ran and returned, or
it was refused, or it is asked for again. (The one `abandoned` an Errand reports is a cleared
call in a batch a person answered `denied`, below.)

## Deeper: a batch with mixed verdicts

The policy judges each call of the batch on its own, exactly as for the
[agent](reference-agent.md#one-verdict-per-call). When the calls get different verdicts, the
person is asked only about the calls that need approval, and the outcome follows from their
answer. Say the policy clears the first partition and wants a person for the second:

```python
mixed = {"verdicts": ["cleared", "needs_approval"]}
all_or_nothing = Errand(name="backfill/declined", calls=copy_calls)
all_or_nothing.handle(Event("started"))
(question,) = all_or_nothing.handle(Event("needs_approval", mixed)).requests()
print([call["call_id"] for call in question.payload()["calls"]], question.payload()["positions"])
all_or_nothing.handle(Event("denied", {"reason": "not today"}))
statuses = [attempt["status"] for attempt in all_or_nothing.outcome().payload()["attempts"]]
print(all_or_nothing.state(), statuses)
```

```text
['c2'] [1]
State('declined') ['abandoned', 'denied']
```

`denied` refuses the whole batch: the asked call is `denied`, and the cleared one, which could
have run, is `abandoned` with it. To refuse only some calls, the person answers `approved`
naming the calls denied. The errand then acts, and the refused call rides along in
`invoke_tools` as `refused`, so the tool fulfiller answers it without running it:

```python
partly = Errand(name="backfill/partly", calls=copy_calls)
partly.handle(Event("started"))
partly.handle(Event("needs_approval", mixed))
denial = {"denied": [{"call_id": "c2", "reason": "not that one"}]}
(running,) = partly.handle(Event("approved", denial)).requests()
print(running.kind().name(), running.payload()["refused"])

results = [
    ToolResult(call_id="c1", content={"copied": "2026-11-01"}),
    ToolResult(call_id="c2", content="not run: approval was denied: not that one", failed=True),
]
partly.handle(Event("tools_returned", {"results": [r.to_dto().to_plain() for r in results]}))
print(partly.state(), [attempt["status"] for attempt in partly.outcome().payload()["attempts"]])
```

```text
invoke_tools [None, {'status': 'denied', 'reason': 'not that one'}]
State('refused') ['ok', 'denied']
```

You played the tool fulfiller here, so you wrote the refused call's failed result yourself;
`ToolFulfiller` writes it for you. The errand ends `refused`: not `done`, because `done` means
every call ran and succeeded, and not `failed`, because no call that ran failed. So a plan
that routes on an errand's final state can tell "a tool failed" (`failed`) from "the policy
or a person refused part of the batch" (`refused`) without reading the attempts. Had `c1`
failed as well, the errand would end `failed`: a failure wins.

## In the harnesses

Most harnesses in [gvn-domains](../domains/index.md) (the sibling package of complete
harnesses) use errands, as stages of their [workflows](workflows.md), for the steps a model has
no business deciding: applying an approved containment plan, issuing an order, deploying the
exact release, each step of a data backfill, a rollout gate.

## Recap

- An `Errand` is a fixed batch of `FixedCall`s (call id, tool object, arguments) with no model: vetted by the policy call by
  call, approved by a person when the policy says so, then run.
- It ends `done` when every call ran and succeeded, `failed` when a call that ran failed,
  `refused` when some call was forbidden or denied and none that ran failed, and `declined`
  when a person answered `denied` for the whole batch.
- It uses the agent's request kinds and payloads, so the standard fulfillers serve it.
- Its outcome lists one attempt per call, in the order given.
- Its request IDs and tool keys are stable. A tool may be called again, and a tool that
  deduplicates by key applies its effect once. Approvals are asked again after an interrupt.

**Next:** [Workflows](workflows.md), which run agents, errands and other actors together as
the stages of one run.
