The reference agent¶
What you will learn: what the agent gvn ships does, state by state; how it uses a tool under a tool policy and a budget; how it keeps its conversation within its model's context window; how it reads its sensors after a tool succeeds; and what it guarantees about its transcript and its result.
Read first: Machines, Decisions, Durable objects, Actors and events, Tools. Time: about 20 minutes.
Where this sits. In the loop that runs, this
page fills in the actor box with the one actor most runs start from: the agent gvn ships.
It lives in the harness layer. Each request it
makes goes to a different part of the loop: invoke_model to the model fulfiller,
consult_policy to the policy fulfiller, invoke_tools to the tool fulfiller, and
request_approval to a person. The next page, The Governor, wires those
fulfillers up; on this page you play all of them by hand.
The problem: a model loop you can reason about¶
The usual agent is a loop: send the transcript to a model; if the reply asks for tools, run them, append the results and loop; otherwise stop. Real agents need more than that. Some tool calls are dangerous and need a policy check, or a person's approval. The loop must stop after some number of model calls. A person must be able to interrupt it. And when any of that cuts a tool call short, the transcript must still make sense to the model vendor.
gvn.harness.agent.Agent is that loop written as a verified machine: a model that may call
tools, under a tool policy and a budget of model turns, with human approval and interruption
built into its machine. It is an actor, so it does no I/O. It emits
requests, and the Governor (the runtime, the next page) fulfils them. On this
page you play the Governor by hand.
Step 1: build an agent¶
An agent is given the tools its model may use as tool objects. Here a StubTool, the test
tool from gvn.testing.fakes, stands in for a real search tool:
from gvn.harness.agent import Agent
from gvn.kernel.schema import Record, Text
from gvn.testing.fakes import StubTool
search = StubTool("search", Record({"query": Text()}))
research_agent = Agent(
name="helper",
instructions="You are a careful research assistant.",
tools=[search],
turns=10,
)
print(research_agent.state(), research_agent.turns_remaining())
print(research_agent.tool_identities())
name: the actor's address. Request ids start with it.instructions: the standing directions sent to the model inthinking(the "system prompt"). A summary request uses its own directions from the context budget.tools: the tools the model may use, as Tool objects or aToolbox, and the only ones it can use: a reply that calls any other tool is refused by the machine itself (see below). The agent keeps only each tool's identity (its namespace, a dot and its short name:gvn.testing.fakes.search), never the object, because it is stored in the journal; the model sees the short name,search. The runtime runs the calls from aToolbox(the tool objects, found by identity, which the Governor's tool fulfiller holds; see The Governor). One agent is offered one tool per short name. Tools explains the two names and why.turns: how many times the agent can enterthinking(default 10). A retry of the same request and a separate summary call use no additional turn.answer: an optionalRecordthe final model reply must satisfy. See Structured answers.context: the run context,Noneor a dict of plain JSON (see below).context_budget: how much of the model's context window (the most a model can read in one call) the agent's conversation may use, and how to make the conversation smaller when it fills.None, the default, reduces nothing. See below.model_role:None(the default), or the name of a role whose model serves this agent's calls. A role is a name your runtime wiring maps to a model, not a vendor's model id; withNonethe wiring's default model answers. See A model per role.recallandrecall_limit: whether to look up memory before the first model call, and the maximum number of entries to ask for. See Memory.sensors: fixed measurements the harness takes after a watched tool succeeds (none by default), each aSensor. See below and Sensors.
instructions(), tool_identities() and context() return the instructions, the
identities of the offered tools (a frozenset) and a copy of the run context ({} when there
is none).
Step 2: the machine¶
This is Agent.definition(), the default control machine, a
Moore machine (each state names its output) with
eighteen states. Each state's output is
shown in the table below it.
stateDiagram-v2
[*] --> idle
idle --> admitting : started
admitting --> measuring : within_budget
admitting --> failed : budget_exhausted
measuring --> recalling : recall_due
measuring --> thinking : context_fits
measuring --> remembering : remember_due
measuring --> measuring : trim_due
measuring --> summarising : summary_due
measuring --> overflowed : context_exhausted
recalling --> measuring : recalled
recalling --> measuring : recall_failed
recalling --> suspended : interrupted
remembering --> measuring : remembered
remembering --> measuring : remember_failed
remembering --> suspended : interrupted
summarising --> measuring : model_replied
summarising --> measuring : model_failed
summarising --> suspended : interrupted
thinking --> interpreting : model_replied
thinking --> diagnosing : model_failed
thinking --> suspended : interrupted
diagnosing --> failed : failure_final
diagnosing --> admitting : context_exceeded
interpreting --> completed : answered
interpreting --> admitting : answered_while_blocked
interpreting --> vetting : requested_tools
interpreting --> admitting : requested_unoffered
vetting --> acting : cleared
vetting --> awaiting_approval : needs_approval
vetting --> admitting : forbidden
vetting --> suspended : interrupted
awaiting_approval --> acting : approved
awaiting_approval --> admitting : denied
awaiting_approval --> suspended : interrupted
acting --> checking_sensors : tools_returned
acting --> suspended : interrupted
checking_sensors --> sensing : sensors_due
checking_sensors --> admitting : nothing_due
sensing --> admitting : sensed
sensing --> admitting : sense_failed
sensing --> suspended : interrupted
suspended --> checking_sensors : resumed
completed --> [*]
failed --> [*]
overflowed --> [*]
Every input not drawn is covered by otherwise: stay, so an unexpected event is rejected
and changes nothing. A test in the docs suite checks this diagram edge by edge against
Agent.definition(). You can also render it yourself with
gvn.kernel.diagram.Mermaid().render(Agent.definition()).
With answer=Record(...), the agent uses Agent.answering_definition(), which adds
an answer_invalid route from interpreting to failed.
| State | Output | Kind of output |
|---|---|---|
idle |
idle |
names no work |
admitting |
check_budget |
internal decision |
measuring |
check_context |
internal decision |
recalling |
recall |
request |
remembering |
remember |
request |
summarising |
invoke_model |
request |
thinking |
invoke_model |
request |
diagnosing |
classify_failure |
internal decision |
interpreting |
classify_reply |
internal decision |
vetting |
consult_policy |
request |
awaiting_approval |
request_approval |
request |
acting |
invoke_tools |
request |
checking_sensors |
check_sensors |
internal decision |
sensing |
sense |
request |
suspended |
suspended |
names no work |
completed (final) |
completed |
names no work |
failed (final) |
failed |
names no work |
overflowed (final) |
overflowed |
names no work |
An internal decision is resolved by the agent itself inside handle, as you saw on
Actors and events; a request goes to the outside world.
The core loop is admitting, thinking, interpreting, then vetting, awaiting_approval
and acting for tool calls. After every batch of tool calls, checking_sensors decides
whether a sensor is due, and sensing asks for its readings; an agent without sensors
passes straight through checking_sensors to admitting
(below). measuring, remembering, summarising, diagnosing and
overflowed keep the conversation within the model's context window, and recalling lets an
agent built with recall=True read a memory before its model is first called; they are
explained after the walk-through. With no
context_budget, measuring always lets the agent through to thinking unless the vendor
refuses the conversation as too large.
Step 3: walk one run with a tool¶
Follow the happy path through the diagram: the model asks for a search, the policy clears it,
the tool runs, the model answers. Two message types carry the tool traffic: a ToolCall is
the model's request to run one tool (an id the model gave it, the tool's short name and
its arguments), and a ToolResult is what running it produced, matched to the call by the same
id. Start the agent and play the model, replying with a tool call:
from gvn.harness.events import Event
from gvn.harness.messages import Message, ToolCall, ToolResult
research_agent.handle(Event(name="started", payload={"prompt": "Who wrote Moore's paper?"}))
search_call = ToolCall(call_id="call-1", name="search", arguments={"query": "Moore machine 1956"})
asks_for_search = Message.assistant(text="Let me look.", calls=[search_call])
research_agent.handle(
Event(name="model_replied", payload={"message": asks_for_search.to_dto().to_plain()})
)
print(research_agent.state(), research_agent.pending()[0].kind())
The agent did not run the tool. It moved to vetting and asks the outside world to consult
the tool policy: a Decision that answers cleared, needs_approval or forbidden for
each call of the reply. With one call, its verdict is the answer. Play the policy and clear
it:
research_agent.handle(Event(name="cleared"))
print(research_agent.state(), research_agent.pending()[0].kind())
Now play the tool, and then the model's final answer:
found = ToolResult(call_id="call-1", content="Edward F. Moore, 1956.")
research_agent.handle(
Event(name="tools_returned", payload={"results": [found.to_dto().to_plain()]})
)
print(research_agent.state(), research_agent.turns_remaining())
answer = Message.assistant(text="Edward F. Moore wrote it in 1956.")
research_agent.handle(
Event(name="model_replied", payload={"message": answer.to_dto().to_plain()})
)
print(research_agent.outcome())
State('thinking') 8
Outcome('completed', {'text': 'Edward F. Moore wrote it in 1956.', 'tools': [{'name': 'search', 'identity': 'gvn.testing.fakes.search', 'arguments': {'query': 'Moore machine 1956'}, 'content': 'Edward F. Moore, 1956.'}], 'attempts': [{'name': 'search', 'identity': 'gvn.testing.fakes.search', 'arguments': {'query': 'Moore machine 1956'}, 'status': 'ok', 'detail': 'Edward F. Moore, 1956.'}], 'reductions': {'trimmed': 0, 'summarised': 0, 'fell_back': 0, 'remembered': 0, 'unremembered': 0}, 'recalls': {'asked': 0, 'found': 0, 'failed': 0}, 'readings': {'taken': 0, 'failed': 0, 'blocked': 0, 'latest': {}}})
Notice that after the tool returned, the agent went through checking_sensors (it has no
sensors, so nothing was due), then back through admitting (and measuring), and spent a
second turn (10 became 8) before thinking again. The outcome lists what the model actually
did, in tools and attempts, each call with its tool's short name and its identity;
reductions says how often the conversation was made smaller (never, here), recalls how
often the agent read a memory by itself (never: it was not built with recall=True), and
readings what its sensors read (nothing: it has none).
What to notice in the machine¶
- Every loop goes through
admitting, thenmeasuring. Whether the model answered, a tool returned, a call was forbidden, approval was denied, or the run was resumed, the agent checks its turn budget, then its context budget, before it thinks again. A looping agent cannot escape its budget. - The five internal decisions are
branched.check_budgetanswerswithin_budgetorbudget_exhausted;check_contextanswersrecall_due,context_fits,remember_due,trim_due,summary_dueorcontext_exhausted;classify_failureanswersfailure_finalorcontext_exceeded;classify_replyanswersanswered(no tool calls),answered_while_blocked(no tool calls, but a blocking sensor still reads not clean),requested_unoffered(a call names a tool the agent was not offered) orrequested_tools;check_sensorsanswerssensors_dueornothing_due. The verifier holds the machine to every outcome. - An agent only runs the tools it was offered. The shared toolbox may hold more tools than one agent is given. A reply that calls any tool the agent was not offered is refused before the policy is consulted: the whole batch is abandoned and the model is asked again, so no policy, approval or tool request is ever issued for it.
- The policy verdict is a branch too.
vettingmust route all three ofcleared,needs_approvalandforbidden. When a reply holds several calls, each call has its own verdict, but the machine still routes on one of these three symbols (see one verdict per call). - Waiting for approval is a state. The agent parks at
awaiting_approvalwhen its Governor expects a person to answer the request. interruptedis declared in every state with a request outstanding (recalling,remembering,summarising,thinking,vetting,awaiting_approval,acting,sensing) and leads tosuspended.resumedgoes throughchecking_sensors, so readings an interruption cut short are asked for again.
Step 4: a refused call keeps the transcript well formed¶
What happens to a tool call that never runs? Some model vendors require every tool call in a transcript to be answered by a tool result. So whenever pending calls are abandoned, the agent writes a failed result for each one, saying why. Here the policy forbids a delete, and then the model tries a tool it was never offered:
delete_file = StubTool("delete_file", Record({"path": Text()}))
cleanup_agent = Agent(name="helper", instructions="Be brief.", tools=[delete_file])
cleanup_agent.handle(Event(name="started", payload={"prompt": "Clean up."}))
delete_call = ToolCall(call_id="call-1", name="delete_file", arguments={"path": "notes.txt"})
cleanup_agent.handle(
Event(
name="model_replied",
payload={"message": Message.assistant(text="", calls=[delete_call]).to_dto().to_plain()},
)
)
cleanup_agent.handle(Event(name="forbidden"))
answered = cleanup_agent.transcript()[-1]
print(answered.role(), answered.results()[0].failed(), answered.results()[0].content())
print(cleanup_agent.state())
The agent went back to the model, which will see the refusal. Now the model calls a tool the agent was never offered:
rogue_call = ToolCall(call_id="call-2", name="drop_database", arguments={})
cleanup_agent.handle(
Event(
name="model_replied",
payload={"message": Message.assistant(text="", calls=[rogue_call]).to_dto().to_plain()},
)
)
print(cleanup_agent.transcript()[-1].results()[0].content())
print([request.kind() for request in cleanup_agent.pending()])
No policy, approval or tool request was issued: the agent answered the call itself and asked the model again.
The states that keep the conversation within the window¶
Every model call sends the whole conversation, and a model can read only so much in one call:
its context window, counted in tokens. The window belongs to the model
(Model.context_window()); what the agent does as its conversation fills it is the agent's
context budget, the ContextBudget you pass as context_budget=. Two different things
share the word "context" here, and they must not be confused: the context window and the
context budget are about what the model is sent and how much of it fits; the
run context (context=) is trusted data from your code for the tools
and the policy, and it is never sent to the model at all. The agent never counts tokens: each model reply reports what the call used, and the
agent reads that from the model_replied event.
Six parts of the machine carry it out:
measuringcomes afteradmitting, before every model call. Its decision,check_context, answersrecall_due(read a memory first: only for an agent built withrecall=True, once, for its prompt),context_fits(go on tothinking),trim_due(make the conversation smaller without a model, then check again),summary_due(ask the model for a summary first),remember_due(hand what is about to be dropped to a memory first) orcontext_exhausted.rememberingis used only by a budget built withremember_dropped=True. It asks forremember: a memory keeps the text the reduction is about to drop, so that a model can recall it later. It goes back tomeasuringwhether the memory kept it or failed. Memory, a later page, explains memories.recallingis used only by an agent built withrecall=True, and only when its prompt is not blank. It asks forrecallwith the prompt as the query, appends what the memory found as one user message under a fixed header (untrusted notes, never instructions), and goes back tomeasuring, so the budget measures what it added. A memory that fails does not stop the run. Memory explains it.summarisingasks the model to summarise the older messages, with no tools, and goes back tomeasuringwhether the summary came or not. It spends no turn.diagnosingsorts a failed model call:context_exceededwhen the vendor refused the conversation as too large (the agent goes back throughadmittingto reduce it, spending a turn),failure_finalfor any other failure.overflowedis a final state: the conversation no longer fits the budget and nothing can make it smaller. A workflow that hosts an agent must route it.
Context management explains the budget, the reduction steps and their costs, with runnable examples.
The states that read the sensors¶
A sensor is a fixed measurement the harness author attaches: "after write_file
succeeds, run lint". The model never chooses it. Two states carry it out:
checking_sensorscomes after every batch of tool calls (and afterresumed). Its decision,check_sensors, answerssensors_duewhen a tool a sensor watches succeeded in the batch, elsenothing_due(go on toadmitting). A sensor takes one reading per batch, however many watched calls the batch held.sensingasks for every reading due with onesenserequest, served by the runtime from a toolbox of measuring tools of its own (never the model's tools, never the policy). The readings come back insensedand reach the model as one user message under a fixed header,Sensor readings. These are measurements, not instructions:, before its next reply. A reading that fails, orsense_failed, is counted and the run goes on.
A sensor built with blocks=True whose latest reading is not clean keeps the agent from
finishing: classify_reply answers answered_while_blocked, the agent appends a message
naming the sensors and goes back through admitting, so the turn budget bounds it.
Sensors explains them, with runnable examples.
That is the 80% you need. The rest of this page is reference: verdicts for a reply with several calls, run context, payloads, the data rules, outcomes and the saved form.
Deeper: one verdict per call¶
A model often puts several calls in one reply: read a file, then delete it. Each call gets its
own verdict: PolicyFulfiller (the runtime part that answers consult_policy; see
The Governor) asks the policy once per call, in call order. The machine,
though, still routes on one of the three symbols. That symbol is the route, and it is
computed from the verdicts:
needs_approvalwhen a person is asked about at least one call;- otherwise
clearedwhen at least one call is cleared; - otherwise
forbidden(every call is forbidden, or nothing is left that could run).
A person is asked about each call that needs approval and has no forbidden call before it. A call after a forbidden one would be skipped anyway (see the statuses below), so asking about it is moot.
The per-call verdicts ride on the route event as data: {"verdicts": [...]}, one per call, in
call order. When every call has the same verdict, the event carries no payload, exactly as a
one-call reply does. Play the policy for a reply that reads a file and then deletes it:
read_file = StubTool("read_file", Record({"path": Text()}))
review_agent = Agent(
name="reviewer", instructions="Be brief.", tools=[read_file, delete_file]
)
review_agent.handle(Event(name="started", payload={"prompt": "Tidy notes.txt."}))
read_notes = ToolCall(call_id="call-1", name="read_file", arguments={"path": "notes.txt"})
delete_notes = ToolCall(call_id="call-2", name="delete_file", arguments={"path": "notes.txt"})
reply = Message.assistant(text="Reading it, then deleting it.", calls=[read_notes, delete_notes])
review_agent.handle(Event(name="model_replied", payload={"message": reply.to_dto().to_plain()}))
judged = {"verdicts": ["cleared", "needs_approval"]}
try:
review_agent.handle(Event(name="cleared", payload=judged))
except ValueError as error:
print(error)
review_agent.handle(Event(name="needs_approval", payload=judged))
print(review_agent.pending()[0].payload())
invalid payload for 'cleared': the verdicts ['cleared', 'needs_approval'] route to 'needs_approval', not 'cleared'
{'calls': [{'call_id': 'call-2', 'name': 'delete_file', 'arguments': {'path': 'notes.txt'}}], 'identities': ['gvn.testing.fakes.delete_file'], 'positions': [1], 'beside': [{'position': 0, 'verdict': 'cleared', 'call': {'call_id': 'call-1', 'name': 'read_file', 'arguments': {'path': 'notes.txt'}}, 'identity': 'gvn.testing.fakes.read_file'}], 'text': 'Reading it, then deleting it.', 'context': {}}
The agent refused a symbol that does not match the verdicts, and changed nothing. With the
right route it asks for approval of the delete only; identities names the tool of each
asked call, and positions and beside show where that call sits and what else the reply
holds. Now the person approves the reply but denies the
delete:
review_agent.handle(
Event(name="approved", payload={"denied": [{"call_id": "call-2", "reason": "keep it"}]})
)
running = review_agent.pending()[0]
print(running.kind(), running.payload()["refused"])
invoke_tools carries every call of the reply; refused says, per call, whether it runs
(None) or why not. ToolFulfiller (the runtime part that answers invoke_tools) runs none of the refused calls and still answers each one
with a failed result, so the transcript stays well formed.
A policy that reads the whole reply¶
The Consultation a policy receives holds the one call being judged in calls(), with
its tool's identity in identities(), and the whole reply too: reply() is every call in
the model's order, reply_identities() their tools' identities, and position() the judged
call's index there. A policy picks the calls it cares about by tool, never by the short
name: consultation.calls_to(delete_file) is the judged calls to that tool, matched by
identity. A policy that judges a call in the light of the others reads the reply. This one
allows one delete per reply and forbids a second:
from gvn.harness.agent import VERDICTS
from gvn.harness.tools import Consultation
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol
class OneDeletePerReply(Decision):
"""A delete needs a person; a second delete in the same reply is forbidden."""
def outcomes(self) -> Alphabet:
return VERDICTS
def judge(self, consultation: object) -> Symbol:
if not consultation.calls_to(delete_file):
return VERDICTS.named("cleared")
earlier = consultation.reply_identities()[: consultation.position() or 0]
if delete_file.identity() in earlier:
return VERDICTS.named("forbidden")
return VERDICTS.named("needs_approval")
first_delete = ToolCall(call_id="call-1", name="delete_file", arguments={"path": "a.log"})
second_delete = ToolCall(call_id="call-2", name="delete_file", arguments={"path": "b.log"})
whole_reply = [first_delete, second_delete]
reply_identities = [delete_file.identity(), delete_file.identity()]
for position, call in enumerate(whole_reply):
asked = Consultation(
calls=[call],
identities=[delete_file.identity()],
origin="janitor",
reply=whole_reply,
reply_identities=reply_identities,
position=position,
)
print(call.call_id(), OneDeletePerReply().decide(subject=asked))
This is how PolicyFulfiller builds each consultation. position() is None only for a
consultation built without reply, whose calls() is then the whole reply. A policy that
looks only at the call in front of it, like every other policy on this site, needs none of
this. Rules, a ready-made policy from the gvn-tools package, judges one call at a time; a rule that reads the rest of the
reply is written as a Decision.
Deeper: run context¶
A tool or a policy often has to stay within the data of one run: only this alert's hosts,
only this customer's records, only this release's service. The code that builds the agent
knows those facts (in a workflow, a later page, the function that builds each
agent reads them from the run's input); the model
must not be the one to state them. So the agent takes them as context: trusted plain JSON,
copied when the agent is built, fixed for its life, and stored in its Dto.
Every request the agent issues carries it as "context". ToolFulfiller hands it to each
tool inside the Invocation, the object a tool receives with each call
(invocation.context(), next to invocation.key(), the call's
idempotency key, and invocation.origin(), the
name of the actor that asked), and PolicyFulfiller hands it to the policy inside the Consultation it decides on. The
model fulfiller never sends it to the model. Run context explains where it
comes from and works through a tool and a policy that enforce it.
Here a policy forbids restarting any host outside the alert's own hosts:
from gvn.harness.agent import VERDICTS
from gvn.harness.tools import Consultation
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol
restart = StubTool("restart", Record({"host": Text()}))
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):
if call.arguments()["host"] not in hosts:
return VERDICTS.named("forbidden")
return VERDICTS.named("cleared")
oncall_agent = Agent(
name="oncall",
instructions="Fix the alert.",
tools=[restart],
context={"hosts": ["web-1"]},
)
print(oncall_agent.context())
policy = OnlyThisAlertsHosts()
restart_db = ToolCall(call_id="c1", name="restart", arguments={"host": "db-1"})
consultation = Consultation(
calls=[restart_db],
identities=[restart.identity()],
origin=oncall_agent.name(),
context=oncall_agent.context(),
)
print(policy.decide(subject=consultation))
Deeper: event payloads¶
handle validates every payload and raises ValueError for one that does not fit.
| Event | Payload |
|---|---|
started |
{"prompt": str, "attachments"?: [<plain form of Attachment.Dto>, ...]} |
model_replied |
{"message": <plain form of an assistant Message.Dto>, "usage"?: {"input_tokens": int, "output_tokens": int, "cache_read_tokens"?: int, "cache_write_tokens"?: int}, "context_window"?: int}; usage is the tokens the call reported, kept for cost; in thinking, usage and context_window (the model's window, added by the ModelFulfiller when the model knows it) are also the agent's measurement of its conversation. A summary reply's are ignored |
model_failed |
{"reason": str}, and optionally "retryable", "retry_after", "usage", "retries" (recorded, never used) and "exceeded_context": true (the vendor refused the conversation as too large; in thinking it routes, through classify_failure) |
tools_returned |
{"results": [<plain form of ToolResult.Dto>, ...]}, one per pending call, plus optional "retries" keyed by call id |
cleared, needs_approval, forbidden |
None (that verdict for every call) or {"verdicts": [<"cleared", "needs_approval" or "forbidden" per call, in call order>]}, whose route must be the event's name |
approved |
None (every call asked about is approved) or {"denied": [{"call_id": str, "reason"?: str or None}, ...]}: those calls denied, the rest approved. A call id that was not asked about, or one named twice, is a ValueError |
denied |
{"reason": str} or None: every call asked about is denied and nothing in the reply runs |
remembered |
{"entry": str}: the id the memory gave the text. Only counted |
remember_failed |
{"reason": str}: counted; the reduction runs anyway |
recalled |
{"entries": [{"id": str, "text": str}, ...]}: at most recall_limit entries, best first. Their texts become one note; none appends nothing |
recall_failed |
{"reason": str}: counted; the run goes on |
sensed |
{"readings": [...]}: one entry per sensor asked, in the order asked, {"sensor": str, "clean": bool, "text": str} for a reading taken or {"sensor": str, "failed": str} for one that could not be. Any other sensor or order is a ValueError |
sense_failed |
{"reason": str}: every sensor asked counts as failed; the run goes on |
interrupted, resumed |
None |
Both model events can also include "model" and "provider" when known, and
model_replied can include "retries". A model retry entry records its failure reason
and wait, with model, provider, usage and the vendor's requested delay when available.
Using a vendor model explains those fields.
The assistant message may carry sealed content (a vendor's signed thinking, see thinking between tool rounds). It is kept in the transcript and the journal, but it never routes and never reaches the policy, an approver, a tool, a summariser or the outcome.
The internal outcomes (within_budget, budget_exhausted, recall_due, context_fits, remember_due,
trim_due, summary_due, context_exhausted, failure_final, context_exceeded, answered,
answered_while_blocked, answer_invalid (with answer=), requested_tools,
requested_unoffered, sensors_due, nothing_due) are decided by the agent itself. Sending one from
outside is a ValueError.
Deeper: request payloads¶
| Request | Payload |
|---|---|
invoke_model |
In thinking: {"instructions": str, "messages": [<Message.Dto plain>, ...], "tools": [identity, ...], "context": {...}}, "tools" the sorted identities of the offered tools (the model fulfiller sends the model their short names), plus "model_role": str and "answer": <JSON Schema> when configured. In summarising: the summary step's brief as instructions, the older messages followed by a request to summarise them as messages, "tools": [] and "context". "model_role" is the step's role, else the agent's, and absent when neither has one |
remember |
{"text": str, "context": {...}}: the transcript of what the reduction now due would drop, as text (ContextBudget.dropping) |
recall |
{"query": str, "limit": int, "context": {...}}: the prompt's text and the agent's recall_limit. No scope: the fulfiller resolves it from trusted wiring |
sense |
{"readings": [{"sensor": str, "tool": identity, "arguments": {...}}, ...], "context": {...}}: one entry per sensor due, in the order the sensors were given; tool is the identity of its measuring tool |
consult_policy |
{"calls": [<ToolCall.Dto plain>, ...], "identities": [identity, ...], "context": {...}}, every call of the reply, and its tool's identity, one per call |
request_approval |
{"calls": [...], "identities": [...], "text": str, "context": {...}}, only the calls a person is asked about. When the reply has other calls too, also "positions" (the index in the reply of each asked call) and "beside" (the other calls, {"position", "verdict", "call", "identity"} each) |
invoke_tools |
{"calls": [...], "identities": [...], "context": {...}}, every call of the reply; the tool fulfiller runs each call with the toolbox's tool of that identity. When some are refused, also "refused": one entry per call, None (it runs) or {"status": "forbidden" \| "denied" \| "skipped", "reason": str or None} |
context is the run context ({} when the agent has none). text in request_approval is
the text of the assistant message that asked for the calls, so the person approving sees
the agent's explanation as well as the calls. In beside, a needs_approval verdict means
the call came after a forbidden one: nobody is asked about it, and it will not run.
consult_policy and request_approval include "exposure", the sorted source identities,
once the agent has recorded exposure to untrusted content.
When every call is asked about, request_approval omits positions and beside. When
every call is eligible to run, invoke_tools omits refused.
The agent wants at most one thing at a time: pending() is () or a one-element tuple.
Deeper: what happens to the data¶
These rules apply only when the event's step was declared:
startedappends the user message (and, withrecall=Trueand a prompt that is not blank, makes the agent owe a recall for it);model_repliedinthinkingappends the assistant message and measures the conversation from itsusageandcontext_window;tools_returnedappends one tool message with the results.- Entering
thinkingspends one turn of the budget. A summary call spends none. trim_duereplaces the transcript with the reduced one; a summary that comes back with text replaces the older messages with it, and a blank or failed summary falls back to keeping the recent messages (after the note of the drop, when they do not start with a user message). After any reduction the measurement is unknown until the next reply. Reductions happen only inmeasuring, where every tool call is answered.remember_due(only withremember_dropped=True) leads toremembering.rememberedandremember_failedboth mark this loss as handed over and count one"remembered"or"unremembered"; the check then answerstrim_dueorsummary_due, and the step runs. Applying a reduction clears the mark, so the next step's loss is handed over in its turn; a summary round is one loss. An interruption while remembering leaves the mark unset, so after resuming the same loss is asked to be remembered again, under a new request id.recall_dueleads torecallingand counts one"asked".recalledwith entries appends one user message,recalled_note(<their texts>)(the headerRECALLED, then one block per entry), and adds their number to"found";recall_failedappends nothing and counts one"failed". Either settles the recall. An interruption leaves it owed, so it is asked again after resuming. A recall spends no turn.context_exceededrecords the vendor's refusal and stores no failure reason; the next check asks for a reduction or ends the run inoverflowed.tools_returnedmakes every sensor due whose watched tool succeeded in the batch owe a reading.sensedrecords each sensor's latest reading (a taken one counts in"taken", a failed one in"failed") and appends one user message with them;sense_failedappends nothing and counts every sensor asked as failed. An interruption while sensing leaves the readings owed, so they are asked for again after resuming. Sensing spends no turn.answered_while_blockedappends one user message naming the blocking sensors and their latest readings, and counts one"blocked". A run whose turns run out while a blocking sensor reads not clean fails with a reason that names it.- When the reply has tool calls, they become the agent's pending calls until they are answered.
- The transcript stays well formed for any vendor. Whenever pending calls do not run
(forbidden, denied, skipped, or interrupted while vetting, awaiting approval or acting), the
agent or the tool fulfiller answers each one with a failed
ToolResult, saying why. Vendors that require every tool call to be answered never see a dangling one. - When the route is
forbidden, or the answer isdenied, nothing in the reply runs: the agent answers every call itself and goes back toadmitting. Otherwise it goes toacting, andinvoke_toolsruns the calls that are cleared or approved and carries the rest as refused. If nothing is left to run,actingstill asksinvoke_tools, which runs nothing. - A reply calling an unoffered tool is answered the same way, at once: each call to an
unoffered tool says
tool '<name>' was not offered to this agent, and every other call in the batch says the batch was abandoned because of it.
Deeper: outcomes¶
completedcarries{"text": <the final assistant text>, "tools": [...], "attempts": [...], "reductions": {...}}, plus"answer"with the validated data whenanswer=was set, and"citations"when the final reply included citations.failedcarries{"reason": <the model failure, exhausted turn budget, or invalid structured answer>, "attempts": [...], "reductions": {...}}.overflowedcarries{"reason": <that the context budget was exhausted, and whether the vendor refused the conversation or its measured size reached the limit>, "attempts": [...], "reductions": {...}}.
"attempts" lists every tool call the model made in the run, once each, in the order it made
them, as {"name": str, "identity": str or None, "arguments": {...}, "status": str,
"detail": ...}: name is the short name the model wrote and identity the identity of
the offered tool it called (None for an unoffered call, which names no offered tool).
A reduction of the transcript does not change it. "reductions" is {"trimmed": int, "summarised": int,
"fell_back": int, "remembered": int, "unremembered": int}: reductions made without a model,
summaries kept, summaries that failed or came back blank, losses a memory took, and losses
whose remember failed. Every outcome also carries "recalls": {"asked": int, "found": int,
"failed": int}: recall requests the agent issued by itself, entries it appended, and requests
answered recall_failed (all 0 for an agent built without recall=True), and
"readings": {"taken": int, "failed": int, "blocked": int, "latest": {...}}: readings taken,
readings that failed, replies refused because a blocking sensor read not clean, and each
sensor's latest reading, {"clean", "text"} or {"failed"} (zeros and {} for an agent
without sensors). A gate between stages can route on it.
Every outcome includes "exposure" when the agent's exposure is non-empty.
What became of each call¶
The status says what became of the call. Every call gets exactly one:
| Status | Meaning | detail |
|---|---|---|
ok |
the tool ran and succeeded | the tool's result content |
failed |
the call failed, including a failure before invocation such as invalid arguments | the failed result's content |
forbidden |
the policy forbade this call | not run: the policy forbade this call |
denied |
a person denied this call (approved naming it, or denied for the whole reply) |
not run: approval was denied, plus : <reason> when the person gave one |
skipped |
not run because an earlier call of the same reply was refused and this one may depend on it; or it needed approval but came after a forbidden call, so nobody was asked | not run: an earlier call in this reply was refused |
unoffered |
the call named a tool the agent was not offered | the reason text |
abandoned |
interrupted before it ran; in a reply with a call to an unoffered tool; or cleared in a reply a person answered denied |
the reason text |
blocked |
a conversation's close refused because a blocking sensor still read not clean (an agent never has it) |
the refusal, naming the sensors |
Why skipped. The model's call order can express a dependency, such as an edit followed
by a test of that edit. The tool fulfiller uses that order and can run adjacent
independent() reads concurrently. After a refusal, it skips later dependent calls and can
still run independent calls that were cleared or approved.
"tools" is the ok attempts, in the same order, as {"name", "identity", "arguments",
"content"}. A parent workflow can route on what the agent actually did, and on what it was
stopped from doing; it picks a tool's entries with calls_to(entries, tool) or
is_call_to(entry, tool) from gvn.harness.tools, which compare identities, never the
short name.
Deeper: durable form¶
Agent.Dto holds the name, instructions, the sorted identities of the offered tools, the machine's
position (not the whole definition), the transcript, the budget,
the pending tool calls, the failure reason, the run context, the context budget, the gauge
(what the agent last measured of its conversation), the reduction counts, whether the loss
of the reduction now due was handed to a memory (loss_handed_over), the model role, the
recall settings (recall, recall_limit), the text whose recall is still owed
(recall_query, set only while recalling or suspended from it), the recall counts
(recalls), its sensors with the readings still owed, the counts and each sensor's latest
reading (sensors), and the attempts:
one entry per settled tool call, as the outcome lists them. The attempts are recorded when each
call is answered and kept beside the transcript, because a failed ToolResult alone cannot
tell a tool's failure from a refusal, and a reduced transcript no longer holds every call. When a reply's calls had different
verdicts, or a person denied some of them, it also holds those verdicts and denials. It
also stores the structured answer schema, the identities of tools marked untrusted, and
recorded exposure when present. Reviving checks that the position was
recorded on the same definition, by fingerprint, and that the data is consistent with the
state (for example, pending calls exist exactly in vetting, awaiting_approval and
acting).
Recap¶
- The agent is an eighteen-state Moore machine: check the turn budget and the context budget, think, interpret the reply, vet tool calls, maybe wait for approval, act, read its sensors, and loop back.
- It never does I/O; it asks for model calls, policy checks, approvals and tool runs as requests.
- It only runs tools it was offered, every loop spends budget, and every abandoned call gets a failed result so the transcript stays valid for any vendor.
- It keeps its conversation within its context budget, reducing it when due, and ends
overflowedwhen it cannot. - Its outcome reports every tool attempt and what became of it, and how often the conversation was reduced.
Next: The Governor, the runtime that answers every request you played by hand on this page.