English
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.
| State | Meaning | Obtained by |
|---|---|---|
Agent.T.Uninit | constructed, not initialized | Agent(...) |
Agent.T.Init | initialized, can run | initialize(), with entry, setup_agent() |
Agent.T.Final | finalized, no longer usable | finalize(), with exit, garbage collection |
Agent.T.Alive | Uninit | Init — still usable | builder return type |
Agent.T.Any | any state | annotation 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.
| Method | Requires | Returns |
|---|---|---|
initialize() | Uninit | Init |
finalize() | any state (no-op unless initialized) | Final |
system() / instruct() | Alive | same state, unchanged |
execute() / execute_command() | Init | Result |
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 anErrcarrying 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)areTypeGuardhelpers for code that receivesAgent[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 exceptionEntering 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.