English
Agent Initialization
Prefer the Agent class: every capability is a constructor argument, and the result is an ordinary dataclass you can inspect. setup_agent() is the shortcut for the common case — a CLI-style agent with built-in tools and commands.
With Agent
python
from xun import Agent, ToolBox
def weather(city: str) -> str:
"""Query the weather for a given city."""
return f"Sunny in {city}"
agent = Agent(toolbox=ToolBox().register(weather)) # Agent[T.Uninit]
agent = agent.initialize() # Agent[T.Init]
answer = agent.instruct("What is the weather in Paris?").execute()
print(answer.unwrap())initialize() must be called before execute(); rebinding the variable keeps the static type precise. See Lifecycle & Type State.
Constructor arguments (all optional):
| Argument | Default | Notes |
|---|---|---|
name | agent-<uuid> | Displayed label; sub-agents are expected to set it. |
identifier | uuid | Stable id used by displays; unique per agent. |
toolbox | empty ToolBox | See Tools. |
display | NullDisplay | Programmatic agents are silent unless you attach a display. |
workspace | Workspace(workdir=Path.cwd()) | workdir plus a lazily created, GC-cleaned tempdir. |
conversation | empty | Message history; system() / instruct() write to it. |
command | empty CommandRegistry | Slash commands. |
config | load_config().clone() | This agent's own copy — mutate freely. |
hooks | fresh Hooks | Not shared with sub-agents. |
compactor | AutoCompactor | Token-budget policy, installed on before_execution_step. |
state | fresh AgentState | Not inherited; see below. |
cancel_event | new root event | Usually only set by Agent.inherit. |
api_call_semaphore | SlotSemaphore(8) | Shared with sub-agents to cap concurrent model calls; the default comes from _XUN_MAX_API_CALL_CONCURRENCY. A slot stays reserved to the agent that last held it, so a conversation keeps landing on the same slot and server-side KV prefixes stay cached (xun.SlotSemaphore). |
extension_loader | default_loader | Scanner for $XUN_HOME/extensions/. |
The first group (config, workspace, toolbox, command, display, extension_loader) is what Agent.inherit() copies or shares; state and hooks deliberately are not, so a sub-agent starts with a clean slate.
What initialize() does
- Applies every extension's
setup_extension(ctx)— the last moment to change tools or config programmatically. - Auto-detects the model name if the config left it empty.
- Binds the display and emits
AgentBindEvent, then prepares the workspace directory. - Installs the compactor on the agent's hooks.
- Fires
after_initialize, then loadsAGENTS.mdinto the system prompt.
initialize() is idempotent, and calling it on a finalized agent raises.
With setup_agent
python
from xun import setup_agent, interactive_session
agent = setup_agent(tools=[weather], default_tools=False, workdir=".")
interactive_session(agent, task="What is the weather in Paris?")| Parameter | Default | Meaning |
|---|---|---|
name | "agent" | Agent name. |
tools | [] | Your own tool functions. |
default_tools | False | Register all 8 built-in tool sets plus the sub-agent tools. Kept off so tools stays explicit. |
default_system_prompt | True | Install the built-in system prompt. |
default_commands | True | Register the built-in slash commands. |
display | Display() | Console display; pass NullDisplay() to silence, or a WebDisplay to serve. |
workdir | Path.cwd() | Workspace root. |
It returns an already initialized Agent[T.Init], and registers ToolBox().with_defaults().with_subagent_provider() when default_tools=True.
Running
python
agent.system("You are a terse assistant.") # replace the system prompt
agent.instruct("hello", images=["cat.png"]) # add a user message (agent stays Init)
result = agent.execute(max_iterations=512, context=my_ctx) # run until the model answerssystem()andinstruct()return the agent, so they chain.execute()returnsResult[str, ErrorInfo], orResult[T, ErrorInfo]with a schema — see Structured Output.contextis the value injected into tools that declare aToolCallContextparameter — see Tools.max_iterationsbounds the loop; on exhaustion the run ends with an error result.execute_command(name, "args")runs a slash command instead of the model loop.
Finalizing
finalize() fires before_finalize, unbinds the display, emits AgentUnbindEvent and makes the agent unusable. A with block does both ends for you. Do not rely on garbage collection: the agent's weakref.finalize hook cannot observe a dying agent, so cleanup happens only when you call finalize().
python
with Agent(display=my_display) as agent: # initialize()
agent.toolbox.register(weather)
agent.instruct("…").execute()
# finalize() here, also on exceptionsInheriting
Agent.inherit(parent, …) builds a child the way sub-agents normally look:
| Flag | Default | Effect |
|---|---|---|
share_workspace | True | Same workdir and the same lazy temp dir. |
share_display | True | Child events go to the parent's display. |
copy_toolbox | True | Shallow copy of the registered tools. |
copy_command | True | Shallow copy of slash commands. |
copy_conversation | False | Sub-agents start with a blank context. |
inherit_cancel_event | True | Cancelling the parent cancels the child. |
Config is deep-cloned, the API-call semaphore is shared, and the child's name becomes <parent>-child-<id>.