Skip to content

Lifecycle & Type State ​

Agent is generic over its lifecycle state. The state is a type parameter, so calling a method the agent is not ready for is a lint-time error rather than a runtime surprise.

StateMeaningObtained by
Agent.T.Uninitconstructed, not initializedAgent(...)
Agent.T.Initinitialized, can runinitialize(), with entry, setup_agent()
Agent.T.Finalfinalized, no longer usablefinalize(), with exit, garbage collection
Agent.T.AliveUninit | Init — still usablebuilder return type
Agent.T.Anyany stateannotation shorthand

T is a namespace on the class, so annotations read naturally:

python
from xun import Agent

def configure(agent: Agent[Agent.T.Uninit]) -> Agent[Agent.T.Init]:
    return agent.initialize()

Rebind on transition ​

Transitions return the agent with the next state. Rebinding is what makes the type system useful:

python
agent = Agent()
agent = agent.initialize()          # Agent[T.Init]
agent.instruct("Hi").execute()
agent = agent.finalize()            # Agent[T.Final]

agent.instruct("again")             # error: not available on Agent[T.Final]

A bare Agent annotation means Agent[T.Uninit] (the type parameter's default). The parameter is covariant: Agent[T.Init] is accepted wherever Agent[T.Any] is expected.

MethodRequiresReturns
initialize()UninitInit
finalize()any state (no-op unless initialized)Final
system() / instruct()Alivesame state, unchanged
execute() / execute_command()InitResult
display_info() / display_warning() / display_error() / get_choice()Init—
cancel() / check_cancel()any—

Runtime behaviour ​

The type state is not only cosmetic — the runtime keeps the same flag:

  • execute() on an uninitialized agent fails the run with an Err carrying that message.
  • initialize() on a finalized agent raises; on an initialized agent it is a no-op.
  • finalize() on an agent that was never initialized just marks it final.
  • Agent.is_initialized(agent) / Agent.is_finalized(agent) are TypeGuard helpers for code that receives Agent[T.Any] (e.g. a display or an extension).

Finalization is guaranteed: an Agent registers a weakref.finalize hook, so even an agent that simply goes out of scope unbinds its display and fires before_finalize.

The with block ​

python
with Agent(display=display) as agent:     # __enter__ → initialize()
    ...                                   # Agent[T.Init] inside the block
# __exit__ → finalize(), also on exception

Entering an already-initialized agent is fine (initialize() is idempotent), which lets a sub-agent getter hand back a configured agent and the runner with-wrap it.

Xun 1.4.2dev (unreleased; source 51d23f3, 2026-10-16) documentation, generated from the source tree.