Skip to content

Extension Development ​

An extension is a Python file dropped into $XUN_HOME/extensions/ (default ./.xun/extensions/). Every agent — including sub-agents — runs its setup_extension(ctx) at initialization, so tools, hooks, commands and settings appear in sessions you never launched yourself. No registration, no wiring.

API or extension? ​

APIExtension
Entrypointyours — a script, service or notebookxun's (xun, xuns, xunc, xunx)
Purposebuild an agent, tool or pipelinechange what existing sessions do
Accessconstruct an Agentreceives an uninitialized Agent
Reachthe agents you createevery agent that loads it

Extensions are written on top of the API, not beside it: whatever you can do in your own script (toolbox.register, hooks, command.register, editing config) you do through ctx.agent. The difference is who owns the process. Anything the core does not need for every user belongs in an extension — that is how skills, mcp and stat ship even though they are maintained in the same repository.

Extensions are trusted code: they execute at import time with full process privileges, like a shell rc file. Nothing is sandboxed.

Loading mechanism ​

RuleDetail
Two source formsextensions/{name}/setup_extension.py (package: relative imports allowed) or extensions/{name}.py (flat: zero ceremony). A package shadows the same-named file; ./__ entries are ignored; a directory without setup_extension.py is skipped with a warning.
Name and descriptionThe directory/file stem is the extension name; the first line of the module docstring is its description in /extensions.
Imported once, set up manyModules are imported and cached once per process and stay in sys.modules; setup_extension runs again for every Agent.initialize(), with a fresh ExtensionContext.
OrderName-sorted, so a_logging.py runs before z_mcp/. Tool-override conflicts resolve by override, not by luck.
Failure isolationImport errors and setup errors only warn — startup continues and other extensions are unaffected. Inspect with /extensions, which lists uninitialized, loaded, skipped or failed, with reasons.
Opt outenable_extensions: false in the config. Internal helper agents (command risk assessment, compaction) set it automatically.

Quick guide ​

python
"""Log every tool call."""          # extensions/tool_logger.py
from xun import ExtensionContext

def setup_extension(ctx: ExtensionContext) -> None:
    ctx.agent.hooks.before_tool_call.add(
        lambda args: print("tools:", [c.function.name for c in args.tool_calls])
    )

Typical effects, all through the uninitialized agent in ctx:

GoalHow
Add a toolctx.agent.toolbox.register(my_tool) — plain functions; @tool_attr(override=True) to replace a built-in
Add a slash commandctx.agent.command.register(Command(name="hi", handler=…))
React to the lifecyclectx.agent.hooks.<point>.add(handler) — see Hooks
Change defaultsmutate ctx.agent.config (setup runs before model auto-detection)
Read user settingsctx.settings — this extension's bag from config.json: {"extension_settings": {"<name>": { … }}}
Keep filesctx.data_dir() → $XUN_HOME/extension_data/<name>/, created on demand
Add prompt textctx.agent.conversation.set_system_persistent_section("mine", "…")

A second example that registers a tool and a command, with settings:

python
"""Greeting extension."""          # extensions/greeting.py
from xun import Command, ExtensionContext

def setup_extension(ctx: ExtensionContext) -> None:
    name = ctx.settings.get("name", "friend")

    def greet(who: str) -> str:
        """Greet someone by name."""
        return f"Hello, {who}!"

    ctx.agent.toolbox.register(greet)
    ctx.agent.command.register(Command(
        name="hello",
        description=f"Say hello as {name}.",
        handler=lambda agent: agent.display_info(f"Hi, I am {name}."),
    ))

Keep setup_extension cheap and side-effect-light: it runs for every agent, including the short-lived sub-agents used by the compactor and the risk assessor (those run with extensions disabled, but your own sub-agents do not).

Extension attributes ​

@extension_attr on the entry function declares version compatibility, data layout and an optional command line:

python
import argparse
from xun import ExtensionContext, extension_attr

parser = argparse.ArgumentParser()
parser.add_argument("--user", default="me")

def run(args) -> int:
    print(args.user)
    return 0

@extension_attr(
    api_min_version="1.2",
    api_max_version="2.0",
    data_version="1",
    cli=(parser, run),
)
def setup_extension(ctx: ExtensionContext) -> None: ...
AttributeMeaning
api_min_version / api_max_versionInclusive range of xun releases the extension supports. Outside it the extension is skipped (not failed) with the reason in /extensions. Comparison uses the numeric core of the versions; a source checkout (no package metadata) always passes the gate.
data_versionOne safe path segment. data_dir() then resolves to extension_data/<name>/data_v_<version>/, so bumping it starts a fresh layout while the old directory stays untouched. extension_data_dir(name, data_version=None) computes the same path from outside a running extension, which is what a CLI needs.
cli=(parser, handler)Enables xune <name> [args…]: the extension is imported the way an agent imports it, parser parses the arguments, and handler runs — an int return becomes the exit code. Bare xune lists extensions that declare a CLI.

Shipped examples ​

ExtensionDeclaresShows
extensions/mcp/api_min_version="1.3.0"Talking to external processes, exposing their tools through ToolBox.register_raw / pop, configuring via ctx.settings.
extensions/skills/api_min_version="1.4.0", needs pyyamlDiscovering files on disk, progressive disclosure, persistent prompt sections, a /skills command.
extensions/stat/api_min_version="1.4.0", data_version and a CLISQLite under data_dir(), completion_token_update and before_tool_call hooks, refusing a run from before_execution, rendering HTML in chat, and xune stat with budgets.

Each has its own README, and make test-ext runs their tests.

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