Harness
Define the task environment and run the agent through it. Context managers decide what the policy sees, branch points decide where search may continue, and workspaces hold durable task data.
Run a policy in a task. Each decision prepares the context, generates an action, applies it to the environment, and records the turn with its exact prompt tokens and behavior log probabilities.
This agent keeps the transcript with AppendOnly and makes every decision boundary available to search. After 32 steps, including compaction steps, it makes one final-answer attempt; set finish_prompt=None to stop without that attempt. Use context=Segments(256) for exact token continuation or context=Summarize(...) for summaries. branch_points selects candidate checkpoints, and execution configures shared capacity and persistence. The agent chooses an action parser from the policy format and the action kind declared by the context manager or environment. Pass parser= to override that choice. Derived agents share the same policy and execution services.
async with agent starts its execution services and closes them on exit, cancelling and awaiting outstanding requests. The caller closes policy clients and checkpoint storage separately. If several agents share services, use one outer lifecycle scope for all their work. Run derived agents inside that scope; use Collector(..., own=False) when a collector borrows it.
Definition
Agent.init
Section titled “Agent.init”Agent.aenter
Section titled “Agent.aenter”Agent.aexit
Section titled “Agent.aexit”Agent.aclose
Section titled “Agent.aclose”Close this agent’s execution services, cancelling and awaiting outstanding requests. This also affects every agent sharing those services. Policy clients and checkpoint storage remain open. The async context manager calls this on exit.
Agent.services
Section titled “Agent.services”The execution services that run this agent’s model requests. Agents built with the same Execution share capacity.
Agent.checkpointer
Section titled “Agent.checkpointer”The checkpointer from Execution, or None when states are kept only in memory.
Agent.generate_timeout
Section titled “Agent.generate_timeout”Seconds to wait for one generation, from Execution.
Agent.save_checkpoint
Section titled “Agent.save_checkpoint”Save a complete rollout state when a checkpointer is configured, whether or not search can branch there. Call this after editing a saved state by hand. If the state cannot be snapshotted, the previous recoverable checkpoint remains available.
Agent.restore
Section titled “Agent.restore”Restore a saved state on the same branch, using compatible agent components. Stop the previous execution first. The saved resource allowance is restored with the state; service usage still counts failed attempts. Call fork() to start an independent branch.
Agent.restore_latest
Section titled “Agent.restore_latest”Restore the latest intact snapshot for a branch and invocation.
Agent.env
Section titled “Agent.env”The task environment.
Agent.policy
Section titled “Agent.policy”The policy used for task generation, also used by derived agents.
Agent.parser
Section titled “Agent.parser”The parser that turns this agent’s replies into actions: parser= if given, otherwise the policy format’s own, adapted to the declared action kind.
Agent.tools
Section titled “Agent.tools”A copy of the tool schemas shown in the agent’s prompts, including any the context manager adds.
Agent.derive
Section titled “Agent.derive”Create an agent for another environment and prompt that shares this agent’s policy and execution services. Summarize uses it to run the compaction task with the same model. The derived agent keeps the transcript, offers the new environment’s tools, and uses this agent’s sampling parameters unless overridden.
Agent.root
Section titled “Agent.root”Create a root checkpoint from a seed conversation. The environment validates the workspace and resets task state, and the context manager initializes before any generation.
Agent.start
Section titled “Agent.start”Create a root checkpoint from a task prompt and optional workspace. Adds the system prompt and the workspace’s usage guidance. Continue with advance(), run(), or iter_run().
Agent.advance
Section titled “Agent.advance”Take one decision: honor an environment finish request, compact if the context manager requests it, then check whether a non-compacting context is near its limit. Otherwise generate and apply an action. The returned state records the generation; the input stays unchanged. finish_prompt=None ends a limited rollout without an extra generation.
Agent.finish
Section titled “Agent.finish”End the rollout with one final-answer turn. No tool runs; the environment’s finish() reads and scores the answer. With finish_prompt=None, mark the rollout truncated without generating.
Agent.compact
Section titled “Agent.compact”Fold the live context now, even if the context manager’s trigger has not fired, and record the fold turns and the new context version.
Agent.max_steps
Section titled “Agent.max_steps”Decisions per continuation before the final-answer turn; -1 is unlimited.
Agent.iter_run
Section titled “Agent.iter_run”Run to completion, exposing selected continuations and the endpoint.
A new local decision consumes one step, including a fold-only advance. Finalization is outside that budget and happens once. Every yielded checkpoint has an independent snapshot.
Agent.run
Section titled “Agent.run”Consume the shared loop and return its terminal or truncated endpoint.
Agent.run_from
Section titled “Agent.run_from”Fresh episode: start then run. To branch, run(rs).
Define the task’s rules. reset creates an initial state; step applies one parsed action and returns the next state, observations, rewards, and completion status. Return a new state so forked branches remain independent.
Definition
Fields
Env.reset
Section titled “Env.reset”Required implementation.
Return the initial state for a fresh episode.
Env.step
Section titled “Env.step”Required implementation.
Apply the parsed action and return a StepResult with the next state, observations, and rewards. Return a new state to keep forks independent. Tools receive the current branch’s workspace through this call.
Env.validate_workspace
Section titled “Env.validate_workspace”Check task-specific workspace requirements before an episode starts. Raise an error for an incompatible workspace; the default accepts any workspace. The agent calls this before resetting the environment or generating tokens.
Env.finish
Section titled “Env.finish”Read or score a final action after the agent’s step budget is exhausted. This ends the episode without executing tools or other task operations. The default keeps the task state unchanged; override it to extract and score the final answer.
Env.should_finish
Section titled “Env.should_finish”Whether to stop working and take the final-answer turn now. Called before each decision; the default never stops early. Override it for task limits such as a repeated identical request.
Env.finish_tools
Section titled “Env.finish_tools”The tool schemas offered on the final-answer turn. The default offers all of them; return only the submission tool to require an answer.
Env.on_compaction_failure
Section titled “Env.on_compaction_failure”The terminal task state when a rejected compaction ends the episode, which happens when the agent is built with on_compaction_failure="end". The episode ends with zero outcome reward; override this to clear a partial answer or record the reasons.
Execution
Section titled “Execution”How an agent’s model calls run, persist, and recover: the shared execution services, an optional checkpointer, retry rules, a resource budget, and a generation timeout.
This agent retries a failed generation up to three times and abandons a generation after two minutes. Pass the same Execution to several agents, or to agents built for different policy snapshots, so their requests share one capacity limit. Add a checkpointer to persist rollout states for recovery.
Definition
Fields
StepResult
Section titled “StepResult”Describe the result of one environment action: the next task state, reply messages, reward components, and whether the episode ended.
This result ends the episode with outcome reward 1.0 and the supplied final state. Add messages when an action produces observations for the agent.
Definition
Fields
StepResult.reward
Section titled “StepResult.reward”The raw sum of reward_outcome and reward_step. Training applies the weights in RewardConfig to the separate components.
ToolEnv
Section titled “ToolEnv”Build an environment that dispatches tool calls. Implement initial_state and the task’s reward or submission rules. Each tool defines its arguments, behavior, and workspace requirements.
Definition
ToolEnv.init
Section titled “ToolEnv.init”ToolEnv.validate_workspace
Section titled “ToolEnv.validate_workspace”Run each tool’s workspace validation hook when present. Structural third-party tools without this hook remain supported. Override this method and call super() to add environment-wide checks.
ToolEnv.reset
Section titled “ToolEnv.reset”Create the initial state and validate the fields that tool dispatch updates.
ToolEnv.initial_state
Section titled “ToolEnv.initial_state”Required implementation.
Build fresh task state.
ToolEnv.tools
Section titled “ToolEnv.tools”The available tools, including the submission tool when configured.
ToolEnv.schemas
Section titled “ToolEnv.schemas”The tool schemas supplied to the policy’s chat template or native API.
ToolEnv.step
Section titled “ToolEnv.step”ToolEnv.finish
Section titled “ToolEnv.finish”Read the final submission without executing tools or retrying errors.
ToolEnv.reward
Section titled “ToolEnv.reward”Score a valid submission (or a text ending when submit is disabled).
ToolEnv.answer_field
Section titled “ToolEnv.answer_field”The argument name used for the final answer in the submission schema.
ToolEnv.on_submit
Section titled “ToolEnv.on_submit”Record a valid answer. Text is used only with submit disabled.
ToolEnv.on_tool_calls
Section titled “ToolEnv.on_tool_calls”Decrease the optional round allowance by the number of dispatched tool calls.
ToolError
Section titled “ToolError”Signal an expected tool failure that can be reported to the agent as an observation, such as invalid arguments or an unavailable resource.
Definition
Turn a function into a tool. The tool’s name, description, and argument schema come from the function’s signature and docstring.
The model sees a lookup tool with a required string term and an optional integer limit. Arguments are validated before the call; a wrong type or unknown argument becomes a ToolError the model can read. Annotate a parameter workspace to receive the branch’s workspace; it is hidden from the model. Return a string or any JSON-serializable value.
Definition
BaseTool
Section titled “BaseTool”Define a tool the agent can call. Subclass it with a name, description, parameter schema, and call implementation; ToolEnv handles dispatch.
Definition
Fields
BaseTool.function
Section titled “BaseTool.function”BaseTool.validate_workspace
Section titled “BaseTool.validate_workspace”Check the workspace capabilities this tool needs. ToolEnv calls this hook before generation; the default accepts any workspace. Keep branch-specific data in the supplied workspace.
BaseTool.verify_args
Section titled “BaseTool.verify_args”Parse JSON arguments, check required fields, and convert values to their declared types. Validate value ranges and task-specific constraints in your tool.
BaseTool.call
Section titled “BaseTool.call”Required implementation.
Checkpointer
Section titled “Checkpointer”Define persistence for complete rollout states. Saving records a snapshot; loading returns an isolated state suitable for recovery or branching.
Use the in-memory implementation to save and recover isolated states within a process. A custom store implements _put(), _get(), info(), and list(); the base class handles serialization and validation. Pass it through Execution(checkpointer=...). BranchPoints separately selects where search may continue.
Definition
Checkpointer._put
Section titled “Checkpointer._put”Required implementation.
Atomically store this snapshot and its metadata. The base class serializes the rollout and computes the digest before calling this backend hook.
Checkpointer._get
Section titled “Checkpointer._get”Required implementation.
Retrieve the stored snapshot by checkpoint ID. The base class verifies its digest and deserializes an isolated rollout after this hook returns.
Checkpointer.info
Section titled “Checkpointer.info”Required implementation.
Read checkpoint metadata without decoding the rollout payload.
Checkpointer.list
Section titled “Checkpointer.list”Required implementation.
Return checkpoint metadata in reverse commit order for the requested episode, branch, and invocation.
Checkpointer.put
Section titled “Checkpointer.put”Atomically save a new snapshot; the input’s checkpoint ID is its parent.
Checkpointer.get
Section titled “Checkpointer.get”Load an independent snapshot. Explicit IDs never silently fall back.
Checkpointer.latest
Section titled “Checkpointer.latest”Load the last intact snapshot, skipping corrupt records in this scope.
DEFAULT_FINISH_PROMPT
Section titled “DEFAULT_FINISH_PROMPT”The agent’s default instruction for the final-answer turn when a rollout runs out of steps.
Definition
FunctionTool
Section titled “FunctionTool”The tool @tool creates: a function with a JSON schema derived from its signature and docstring, whose arguments are validated before each call.
Definition
FunctionTool.init
Section titled “FunctionTool.init”FunctionTool.call
Section titled “FunctionTool.call”Validate the arguments, pass the branch’s workspace if the function asks for it, and return the result as text.
InMemoryWorkspace
Section titled “InMemoryWorkspace”Store named text entries for each branch. The entries survive context compaction, and forks receive independent copies. The agent reads and writes them through the storage tool.
This example saves a note for later use. Pass workspace to Collector.collect() or Agent.start(). To recover after a restart, use a checkpointer to save the complete rollout.
Definition
InMemoryWorkspace.init
Section titled “InMemoryWorkspace.init”InMemoryWorkspace.tools
Section titled “InMemoryWorkspace.tools”InMemoryWorkspace.guidance
Section titled “InMemoryWorkspace.guidance”InMemoryWorkspace.compaction_guidance
Section titled “InMemoryWorkspace.compaction_guidance”InMemoryWorkspace.fork
Section titled “InMemoryWorkspace.fork”InMemoryWorkspace.read
Section titled “InMemoryWorkspace.read”InMemoryWorkspace.write
Section titled “InMemoryWorkspace.write”InMemoryWorkspace.delete
Section titled “InMemoryWorkspace.delete”InMemoryWorkspace.paths
Section titled “InMemoryWorkspace.paths”InMemoryWorkspace.exists
Section titled “InMemoryWorkspace.exists”InMemoryWorkspace.clear
Section titled “InMemoryWorkspace.clear”InMemoryWorkspace.update
Section titled “InMemoryWorkspace.update”InMemoryWorkspace.init
Section titled “InMemoryWorkspace.init”InMemoryWorkspace.snapshot
Section titled “InMemoryWorkspace.snapshot”InMemoryWorkspace.serialize
Section titled “InMemoryWorkspace.serialize”InMemoryWorkspace.deserialize
Section titled “InMemoryWorkspace.deserialize”InMemoryWorkspace.contains
Section titled “InMemoryWorkspace.contains”InMemoryWorkspace.len
Section titled “InMemoryWorkspace.len”MemoryCheckpointer
Section titled “MemoryCheckpointer”Store serialized rollout snapshots in memory and load isolated copies within the process.
Definition
MemoryCheckpointer.init
Section titled “MemoryCheckpointer.init”MemoryCheckpointer.info
Section titled “MemoryCheckpointer.info”MemoryCheckpointer.list
Section titled “MemoryCheckpointer.list”NullWorkspace
Section titled “NullWorkspace”Run without a scratch store or storage tools. Information carried through compaction lives in the retained context.
Use for tasks that need only the conversation and environment state.
Definition
NullWorkspace.fork
Section titled “NullWorkspace.fork”NullWorkspace.folded_guidance
Section titled “NullWorkspace.folded_guidance”NullWorkspace.compaction_guidance
Section titled “NullWorkspace.compaction_guidance”PackedSequence
Section titled “PackedSequence”Hold a prefix-stable token sequence, its training mask, and the behavior log probability of each generated token.
Definition
Fields
RolloutState
Section titled “RolloutState”Hold a resumable agent state: live conversation, task state, workspace, generation history, and remaining resources. Agent creates and advances it; fork creates an independent continuation.
Definition
Fields
RolloutState.forkable
Section titled “RolloutState.forkable”Whether this state is live, restorable, and eligible for branching.
RolloutState.tagged
Section titled “RolloutState.tagged”The turns carrying any of tags (None means every turn).
RolloutState.transitions
Section titled “RolloutState.transitions”The environment transitions recorded so far, in order. Compaction turns have no environment transition.
RolloutState.folds
Section titled “RolloutState.folds”The number of consecutive groups of compaction turns in the history. Two compactions with no task turn between them count as one group. A compaction that generates no tokens still records a marker.
RolloutState.boundaries
Section titled “RolloutState.boundaries”Indices of the first turns after each consecutive group of compaction turns. These mark where generation resumes from a rewritten context.
RolloutState.reward
Section titled “RolloutState.reward”The sum of outcome and step rewards across environment transitions. This raw total is used for ranking; RewardConfig.configured_return() applies the training weights and discount.
RolloutState.reward_outcome
Section titled “RolloutState.reward_outcome”The sum of task-outcome rewards recorded at episode endings.
RolloutState.reward_step
Section titled “RolloutState.reward_step”The sum of step rewards across environment transitions.
RolloutState.done
Section titled “RolloutState.done”Whether the latest environment transition ended the episode. A subsequent compaction turn leaves this status unchanged.
RolloutState.turns_taken
Section titled “RolloutState.turns_taken”The number of environment transitions so far. Search uses changes in this count to charge task-transition budgets. Compaction consumes an agent step but does not increase this count.
RolloutState.edge
Section titled “RolloutState.edge”Return the turns added after parent. For example, after resuming a checkpoint and generating two segments, state.edge(checkpoint) returns those two turns with their token records and environment transitions. Raises ValueError if the parent’s turns are not a prefix of this state’s history.
RolloutState.generated_since
Section titled “RolloutState.generated_since”Return the behavior log probabilities of tokens generated after parent, in order, filtered by turn tags. Use task tags to inspect task-generation uncertainty; turns without recorded probabilities contribute no values.
RolloutState.owner
Section titled “RolloutState.owner”The episode, branch, and invocation scope used to account for this rollout’s requests and resource budget.
RolloutState.check_continuation
Section titled “RolloutState.check_continuation”Validate the checkpoint format required to resume generation. Raises ValueError if the checkpoint does not satisfy that format.
RolloutState.snapshot
Section titled “RolloutState.snapshot”Copy the branch’s mutable state and workspace while sharing immutable generation records. Use a snapshot to preserve the current checkpoint before advancing it. This method can copy states that are not eligible for branching.
RolloutState.fork
Section titled “RolloutState.fork”Create an independent branch with a new identity and a copy of the remaining resource allowance. Raises ValueError when the state is not forkable.
RoundBudget
Section titled “RoundBudget”Add per-round tool-call counters to a task state. ToolEnv spends calls_remaining as tools run; StateCounter refills it after compaction.
This example starts a round with five tool calls. Include these fields in the state returned by Env.reset() when compaction is triggered by the tool-call allowance.
Definition
Fields
SQLiteCheckpointer
Section titled “SQLiteCheckpointer”Store complete rollout snapshots in a local SQLite database for recovery across processes.
Definition
SQLiteCheckpointer.init
Section titled “SQLiteCheckpointer.init”SQLiteCheckpointer.info
Section titled “SQLiteCheckpointer.info”SQLiteCheckpointer.list
Section titled “SQLiteCheckpointer.list”SUBMIT
Section titled “SUBMIT”The built-in submit tool instance used by ToolEnv to accept a final answer and end the task. Customize the environment’s submission handling to score that answer.
Definition
StorageTool
Section titled “StorageTool”Expose workspace file operations to the agent. Its workspace must support reading, writing, deleting, and listing paths.
Definition
StorageTool.init
Section titled “StorageTool.init”StorageTool.validate_workspace
Section titled “StorageTool.validate_workspace”Require the key-value operations used by the storage tool.
StorageTool.call
Section titled “StorageTool.call”SubmitFields
Section titled “SubmitFields”Add an optional answer field to a task state dataclass. Tool environments can store the agent’s submitted answer here for final scoring.
Definition
Fields
SubmitTool
Section titled “SubmitTool”Describe the terminal submission action and its argument schema; the environment intercepts it to finish the task.
Definition
SubmitTool.init
Section titled “SubmitTool.init”SubmitTool.verify_args
Section titled “SubmitTool.verify_args”Validate declared string fields as well as required keys.
SubmitTool.call
Section titled “SubmitTool.call”Specify the name, schema, and callable behavior required of an agent tool. Structural implementations can satisfy this protocol without subclassing BaseTool.
Definition
Fields
Tool.call
Section titled “Tool.call”Record one generation and its associated task transition or context-management operation. Rollout histories use these records to recover token spans and rewards.
Definition
Fields
Workspace
Section titled “Workspace”Define the agent’s branch-local scratch storage, its tools, and how it is copied or restored. Implement this interface to add a storage backend.
Definition
Workspace.tools
Section titled “Workspace.tools”Return the tools the agent can use to access this workspace. The default returns none.
Workspace.compaction_tools
Section titled “Workspace.compaction_tools”Return the workspace tools available during compaction. Defaults to the same tools used by the agent.
Workspace.guidance
Section titled “Workspace.guidance”Explain how the agent should use the workspace. The agent adds this text to the system prompt; an empty string adds no guidance.
Workspace.folded_guidance
Section titled “Workspace.folded_guidance”Explain how to use memory after compaction. Defaults to guidance(); override it when the available memory changes after a summary.
Workspace.compaction_guidance
Section titled “Workspace.compaction_guidance”Provide instructions for using the workspace during compaction. An empty string adds no instructions.
Workspace.snapshot
Section titled “Workspace.snapshot”Return inspectable workspace contents for metrics and debugging. The default is empty. The model accesses stored data through the workspace tools.
Workspace.fork
Section titled “Workspace.fork”Required implementation.
Create an independent copy of the workspace with the same initial contents.
AnyRollout
Section titled “AnyRollout”Refer to a RolloutState without fixing its environment-state and action type parameters.
Definition
CheckpointInfo
Section titled “CheckpointInfo”Describe a stored checkpoint’s identity, ordering, and snapshot metadata.
Definition
Fields
CorruptCheckpoint
Section titled “CorruptCheckpoint”Report a saved snapshot that failed integrity verification or decoding.
Definition
Identify ordinary task-generation turns in a rollout.
Definition
TurnTag
Section titled “TurnTag”Classify a generation turn by its role in the task or context-management process.
Definition
WorkspaceError
Section titled “WorkspaceError”Report a failed operation on a branch’s workspace.
Definition
dispatch
Section titled “dispatch”Execute one parsed tool call and return the text observation supplied to the model.
Definition
flatten_tool_calls
Section titled “flatten_tool_calls”Render tool-call blocks as inert text for transcript inspection and summarization.
Definition
format_transcript
Section titled “format_transcript”Render messages as a role-labeled transcript with tool calls flattened to text.
Definition
logprob
Section titled “logprob”Sum the behavior log probabilities of the generated tokens in a sequence of turns. Raises an error if a turn has no recorded probabilities.
Definition
_Stored
Section titled “_Stored”Carry the serialized checkpoint bytes, integrity digest, and CheckpointInfo passed between Checkpointer and its storage backend. This record is the input to _put() and the result of _get().
Definition
Fields
regions
Section titled “regions”Pack a sequence of turns into training token regions. Context rewrites create new regions because the next prompt starts from a different token prefix.
Definition
tool_schema
Section titled “tool_schema”Build the function schema that a chat template exposes to the model for a tool.
Definition
DEFAULT_DESCRIPTION
Section titled “DEFAULT_DESCRIPTION”Provide the default model-facing description of the final submission tool.
Definition
trainable_logprobs
Section titled “trainable_logprobs”Read every generated token’s behavior log probability, in generation order.
Definition
Effect
Section titled “Effect”Record a committed task or context operation and the generation that requested it. Checkpoint policies inspect these effects to choose resumable boundaries.
Definition
Fields