Hugging Face Papers ↗ · 2026-11-22
Wactorz: Self-Writing LLM Agents That Discover, Repair, and Migrate at the Edge
Media reports Hugging Face Papers Source language: Chinese
Researchers present Wactorz 0.8, an open-source MQTT runtime where LLM-generated agents self-repair code and live-migrate across edge nodes, taking under four minutes…
Full text
Wactorz: Self-Writing LLM Agents That Discover, Repair, and Migrate at the Edge
(Extended Version)
Panagiotis Kasnesis Lazaros Toumanidis Amalia Contiero Christos Chatzigeorgiou
Abstract
Most LLM agent frameworks build a crew that runs a task and exits. Physical environments (e.g., homes, labs, factory floors) need agents that stay up for months, survive their own bugs, and run on whatever hardware is already next to the sensors. We present Wactorz, an open-source runtime in which LLM-generated agents are long-lived, supervised actors: a planner turns a chat request into Python, compiles it into a new actor at runtime, and a supervisor restarts that actor alone, with its state intact, when it crashes. All coordination rides on MQTT, so agents can be spawned on, and live-migrated between, edge nodes such as a Raspberry Pi, and every internal event is a topic external systems can subscribe to. The recorded demo builds a camera-to-lamp automation from one chat request, adds a second agent that is auto-wired to the first by topic and carries a deliberate division-by-zero, watches that agent repair its own code without losing its count, then deploys a fresh Raspberry Pi node and live-migrates the agent onto it, in under four minutes of wall-clock time and $0.13 of model usage. This extended version adds what the two-page demonstration paper could not: the Wiring view of the topic graph, Wactorz as a library for hand-written agents, how trained models are stored, sent to nodes and replaced, the security model, and the system’s limitations.
1Waldiez PC, Maroussi, Greece
2ThinGenious PC, Maroussi, Greece
{pkasnesis, laztoum, chrichatz}@waldiez.io, amaliacontiero@gmail.com
Code — https://github.com/waldiez/wactorz
Introduction
LLM orchestration libraries such as AutoGen (Wu et al. 2023), CrewAI and LangGraph (Chase 2022) model a multi-agent system as a conversation or graph that is executed inside one script and terminates when the task does. That is the wrong lifecycle for physical AI: an agent that watches a camera feed, a power meter, or a door sensor must run continuously, tolerate faults in code it did not write, and often has to sit on a low-power device with intermittent cloud access. Existing edge automation tools (Home Assistant rules, Node-RED flows) are long-lived but static: a human writes every rule.
Wactorz closes that gap by combining three ideas from different communities: the actor model with supervision trees from the Erlang/OTP tradition (Hewitt et al. 1973; Armstrong 2003); code-generating LLM agents that write their own behaviour at runtime (Wang et al. 2023); and a pub/sub IoT bus (MQTT) as the sole coordination substrate (Banks et al. 2019), on which agents discover one another by observed topic rather than by the ontology-driven matching of needs and services we proposed for the social IoT (Kasnesis et al. 2017). The result is a system in which the LLM is the programmer, the supervisor is the safety net, and the broker is the network. To our knowledge it is the first agent framework in which LLM-written agents are first-class, supervised, migratable actors.
The same runtime serves agents nobody generated. A developer can hand Wactorz a Python function and get the same supervision, persistence, wiring and migration, and a trained model can be stored once on the main machine and served, by version, to whichever node runs the agent that needs it. This version describes Wactorz 0.8.
System Description
Figure 1: Wactorz architecture. Blue nodes are created at runtime: †a PlannerAgent per request, which self-terminates, and ∗the DynamicAgents it writes, re-spawned from the persisted registry on restart.
Wactorz is a single-process Python asyncio actor system (Figure 1); a separate Mosquitto broker is the only other component. Every agent is an Actor with an inbox, a message loop, a heartbeat every 10 s, and a key-value persist()/recall() API that routes structured keys to SQLite, trained models, numpy arrays and tensors to blob files of their own, and other Python objects to pickle. Each agent has an identity that survives restarts and moves, and is addressed as name@node, so two machines may each run an agent of the same name.
Agents that write agents
A user types a request in natural language, e.g. “when a person is detected on my PC camera, turn on the office light”. MainActor classifies the intent (direct actuation, Home Assistant query, pipeline, or chat). Pipelines go to an ephemeral per-request PlannerAgent, which emits a JSON plan and, for each step, Python source defining setup(), process() and handle_task(). Each block becomes a DynamicAgent, spawned into the running system with no restart. An InstallerAgent pip-installs declared dependencies before a spawn; a package that is not on an allow-list waits until the operator approves it on the dashboard. A catalogue of trusted recipes (time-series collection, anomaly detection, weather, energy) covers common needs without generated code.
Discovery by topic, not by name
Agents never address each other by name. Each publishes and subscribes through MQTT topics, and a TopicBus registers a contract per topic, including its producer, consumers and a captured sample of the real payload. When a later request needs data that already flows (“count the people the camera sees”), the planner is handed the matching contracts and samples before it writes code, so the consumer reads payload["person"] because that is what the producer actually sends, not what a second LLM call guessed. This removes the classic failure of multi-LLM pipelines, two agents disagreeing on field names, and makes agents replaceable: rename or regenerate a producer and its consumers keep working as long as the topic and shape hold. Our earlier social-IoT work matched objects’ needs to services through ontologies and semantic rules (Kasnesis et al. 2017); contracts learned from live payloads need no shared vocabulary in advance, which is what agents whose schemas do not exist until an LLM writes them require.

Figure 2: The Wiring view during a run of the demonstration on Wactorz 0.8, grouped by machine. Agents are on the left of each band and topics are rounded boxes. The detector on the main machine publishes person-detection, which feeds a lamp trigger on main and a counter that has been migrated to the rpi-kitchen node: the edge crosses machines because the counter subscribes to a topic, not to an agent. The trigger’s output topic is outlined in red because no agent reads it; a topic only the dashboard reads is marked as such rather than as a problem.
The registry is also what a person needs to see what the system has become after a few weeks of requests. The dashboard’s Wiring view (Figure 2, also served as GET /api/wiring) draws it as a graph of agents and topics, optionally grouped by machine, and flags three kinds of problem: a topic an agent publishes that no agent reads; a subscriber whose topic has no producer and on which nothing has been seen (outside the roots where sensors, Home Assistant or scripts are expected to publish); and a field mismatch, where an agent declares a field it reads that the topic does not carry. What a topic carries is what was actually observed on it, falling back to what its producer declares. Selecting an agent or a topic shows its last payload. The view keeps no state of its own: it is the topic registry, read at the time of asking.
Supervision and self-healing
Because the code was written by a model, faults are expected rather than exceptional. Generated code passes a pre-execution validator that blocks shell execution, file deletion and eval; a sanitiser fixes the most common LLM mistake (awaiting synchronous methods); repeated runtime errors in setup(), process() or an MQTT subscribe callback hand the code and traceback back to the LLM for an in-place repair, which is persisted to the spawn registry; and process() calls are timeout-guarded. Above that, the Supervisor applies a ONE_FOR_ONE strategy: a crashing agent is restarted alone and reloads its persisted state. Restarts back off rather than stop: after a run of consecutive crashes the delay grows to minutes and then up to an hour, because an outage of something an agent depends on usually ends, and a retired agent would stay down until someone noticed. MonitorActor tracks heartbeats and an error registry, restarting degraded agents but deliberately not restarting agents whose code fails to compile (those are reported to the user instead). The spawn registry itself is persisted, so every dynamic agent comes back after a reboot.
The operator in the loop
Long-lived agents occasionally need a person. An agent can write to the operator first, with notify_user, on the dashboard, Telegram, Discord or WhatsApp, optionally with options to pick; with ask_operator it waits for the answer, and the wait survives restarts. The dashboard’s Inbox lists every question an agent is currently waiting on, alongside the package approvals mentioned above.
Edge nodes and live migration
Any machine with Python 3.11 becomes a node by running the same package as wactorz --node. /deploy provisions one over SSH from a target configured on the main machine (credentials never pass through chat): it installs Wactorz at main’s own version into a virtual environment, writes the node’s configuration, starts it under a systemd unit with a watchdog, and reports success only after the node has reached the broker and sent a heartbeat. Main publishes spawn commands to nodes/{name}/spawn; the node compiles and supervises the agent locally and heartbeats back, so remote agents appear in the same dashboard.
/migrate moves a running agent between main and a node, or between nodes. Every move goes through main. The agent is stopped first, so that what its shutdown hook writes last goes with it; its state travels as JSON, and its blobs (byte strings, numpy arrays, torch tensors, scikit-learn-family models) travel beside it in chunks on topics of their own, each checked against its SHA-256 on arrival. The source keeps its copy until the destination confirms that the agent started; a destination that never confirms is told to drop it and the agent is restarted where it was. An agent leaving a node is always restarted from main’s own copy of its program, never from code the node hands back.
Security model
Spawned agents execute code, so the defaults are conservative. The server binds to loopback unless given an API key. Commands to a node are signed; the node’s link to the broker uses TLS; each node has its own broker account, limited by an access list; and main accepts a reply, manifest or heartbeat only from the node it belongs to, so one node cannot answer for, or delete, another node’s agents. Model-written agents can be confined to a sandbox node: in the Docker Compose stack, a container holding none of main’s credentials, whose network reaches the broker and nothing else.
Model-agnostic, offline-capable
Providers (Anthropic, OpenAI, Gemini, NVIDIA NIM, Ollama) are configured per call site, so cheap high-frequency calls (intent routing) can run on a local 4B model while code generation uses a hosted one. A built-in evaluation harness scores models per call site against the production system prompts: exact-match for routing and Home Assistant classification, action-set match for actuation (an unrequested actuation counts as failure, and some cases expect a refusal because the device does not exist), a valid plan with allowed agent types for the planner, and compile-and-define checks for generated code. It reports accuracy, latency and cost, so that the split is chosen from measurement rather than guesswork. A deterministic fake provider, and a --minimal profile that runs agents and the dashboard with no model at all, cover offline use.
Wactorz as a Library
Everything above the LLM is also available to code a person writes. The decorator in Listing 1 turns a plain function into a supervised agent: it is called once per message on the subscribed topics, with the decoded payload, and what it returns is published. It remains an ordinary function that a test can call directly. A plain function runs on a worker thread, so a slow model never blocks the event loop the other agents share; a coroutine runs on the loop.
⬇
import wactorz
@wactorz.agent(
name="imu-anomaly",
subscribes="sensors/imu/#",
publishes="anomalies/imu",
requires={"packages": ["numpy"]},
models={"model": "imu-detector:3"})
async def detect(reading, me):
model = await me.load_model("model")
score = model_score(model, reading)
if score < 4.0:
return None # publish nothing
me.persist("anomalies_total",
int(me.recall("anomalies_total", 0)) + 1)
return {"score": score, "reading": reading}
wactorz.run(agents=[detect], minimal=True)
List of listings 1 A hand-written agent: supervised, persistent, wired by topic, and movable to a node with its code, packages and model.
wactorz.run(..., minimal=True) starts the monitor, the dashboard and the given agents with no orchestrator, catalogue or installer, so it needs no model, API key or provider SDK. await wactorz.serve(...) does the same inside a program that already has an event loop: a Jupyter notebook, a FastAPI application or a ROS node. Agents with their own lifecycle subclass Actor, whose class attributes (SUBSCRIBES, PUBLISHES, input and output schemas) become the agent’s catalogue entry and the contracts a pipeline is checked against. Steps can be declared together as a pipeline with a schedule and typed rules, and the planner can wire newly generated agents to what hand-written ones publish.
A registered library agent migrates like a generated one. Main sends the folder its module is in (Python files only) along with the spawn; the node checks it against the hash the signed spawn names, installs the packages the agent declares, fetches the models it names, and builds the agent. Imports from outside that folder, other than the standard library, Wactorz and declared packages, are refused before anything stops, naming the import. A node makes no model calls, so an agent’s me.llm is None there.
Wactorz does not replace LangGraph or AG2; it keeps them running. An async agent that invokes a compiled graph is the whole integration, and the graph’s nodes can call the system’s model through me.llm, so their spend is counted with every other call. The chat itself is answered by an orchestrator, a three-method protocol: main is the LLM-driven default, and a deployment can supply its own, a LangGraph graph or a rule engine, without changing anything else.
Models at the Edge
Physical-AI agents usually serve a trained model, and the model changes more often than the agent’s code. Wactorz keeps models on the main machine, by name and version, with wactorz-artifacts; each version resolves to the SHA-256 of its bytes, and identical bytes are stored once. An agent names the models it needs (models= in Listing 1, or an artifacts entry in a generated agent’s spawn configuration) and opens them with load_model, which reads npz, npy, safetensors, state_dict checkpoints and ONNX in ways that execute no code from the file. Pickles, joblib files and whole torch modules, which do run code when loaded, are refused unless the caller passes allow_code=True; other formats (GGUF, TFLite) are opened by path.
Transfer to nodes.
When an agent that names a model is placed on a node, main pins each reference to the exact version and bytes it means at that moment, so the agent restarted or moved later runs the same model. The node asks main only for what its cache lacks, checks each file against its hash, and starts the agent only once every file is present; a migration whose model does not arrive is put back where it was. Main sends a node only the models of the agents placed on it.
Replacing a model.
Two pointers per model say which version is active (served) and which is shadow: on trial beside it, on the same inputs, acted on by nobody. Every pointer move records who made it and why, and is published on a retained topic so every machine hears it. A version can declare which label values count as what it should flag; a trial then judges both versions against labels that operators supply, reporting precision, recall, F1, false alarms per day and time to detection with confidence intervals and a test of whether the two differ. A promotion policy (metric, margin, minimum days and labelled inputs) decides when the shadow may replace the active version, automatically or after the operator confirms on the dashboard. A trainer agent can produce versions inside the loop, from a user-written recipe run on a window of recorded readings in a child process; and a drift agent compares recent readings with the window the served version was trained on (PSI, a two-sample KS test, and ADWIN on the model’s scores). An alarm is an ordinary topic, so a rule can send the trainer a task, and the policy decides whether the result is promoted: the loop closes without a person, unless the policy asks for one.
Demonstration
The station runs Wactorz on a laptop with its webcam, a Home-Assistant-controlled lamp and a Raspberry Pi; the accompanying video is one unedited run (Claude Sonnet 5 at every call site; total cost $0.13). Visitors type into the chat and watch the Feed:
1.
Create. “Spawn an agent to detect if there is any person; if there is, turn on the living-room light. Publish every detection to camera/livingroom/person …use my laptop’s camera.” The planner proposes a YOLO detector (with ultralytics and OpenCV declared as installs) and a Home Assistant actuator; on yes, both spawn and the lamp lights within seconds.
2.
Extend. “Add an agent that counts when a person is detected. Persist the running total. When the counter is ≥10\geq 10, divide it by zero—my system can handle such errors.” The counter is auto-wired to the detector’s topic and starts incrementing; the Wiring view shows the new edge.
3.
Break and heal. At count 10 the callback raises a ZeroDivisionError three times in four seconds; the Feed shows Runtime error—asking LLM to fix, then has recovered and is running normally again. The repaired code no longer divides; the count continues 10, 11, 12 without a reset, and the lamp keeps actuating throughout.
4.
Deploy. /deploy rpi-kitchen provisions a bare Raspberry Pi over SSH (virtual environment, Wactorz, systemd unit) while the counter keeps ticking; the node appears in the dashboard.
5.
Move. /migrate livingroom-person-counter rpi-kitchen stops the local instance and re-spawns it on the Pi with its state: the count continues from the new node, /nodes reports rpi-kitchen ⋅\cdot 1 agent, and the Wiring view, grouped by machine, shows the counter under rpi-kitchen, still reading the detector’s topic on main (Figure 2).
Without network access, every call site can run on a local model through an Ollama-compatible interface.
Limitations
The validator is not a sandbox.
The pre-execution check is a blocklist over the code’s syntax tree. A name it cannot follow (held in a variable, looked up in sys.modules) passes, and so does anything a permitted module can do, such as deleting a file through pathlib. Inside one process, all agents share one privilege level: there is no isolation between them. Isolation comes from placement instead, by running model-written code on the sandbox node or on a separate machine.
A repair restores liveness, not intent.
In the demonstration the repaired counter no longer divides by zero, which is what keeps it running, but the user had asked for the division. The LLM repair optimises for code that runs; whether it still does what was asked is for the operator to judge, and the repaired source is persisted and visible for that reason.
Migration has limits.
State that can be neither serialised nor rebuilt (an open camera handle, a socket, an object of the agent’s own class) blocks a move unless it is forced, in which case those keys are left behind and named. State and blobs are capped (8 MiB and 64 MiB by default), and values that run code when they load (a pickled model, a whole torch module) are sent from main to a node but never accepted back from one, so an agent that must return keeps a state_dict instead. Main and its nodes must run the same release series; a node is redeployed when main is upgraded.
Evaluation.
The demonstration shows one run of one scenario; we report no systematic measurements of repair success rates across models or fault types. The evaluation harness is the instrument for such a study, which we leave to future work.
Significance
Wactorz bridges the LLM-agent, distributed-systems and IoT communities: it shows that classical supervision makes LLM-written code safe enough to run unattended, that pub/sub is a sufficient substrate for spawning and migrating agents, and the models they serve, across heterogeneous hardware, and that the whole stack can be self-hosted. The same runtime hosts hand-written agents, so a team can mix code it wrote, code a model wrote, and graphs from other frameworks under one supervisor and one dashboard. It ships as a pip package, Docker image and Home Assistant add-on under Apache-2.0, with a 500-file test suite and an extensible evaluation harness.
References
Armstrong (2003) J. Armstrong Making reliable distributed systems in the presence of software errors. Ph.D. Thesis, Royal Institute of Technology (KTH), Stockholm, Sweden. Cited by: Introduction.
Banks et al. (2019) A. Banks, E. Briggs, K. Borgendale, and R. Gupta MQTT version 5.0, OASIS standard. Note: https://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.htmlAccessed: 2026-09-18 Cited by: Introduction.
Chase (2022) H. Chase LangChain. Note: https://github.com/langchain-ai/langchainAccessed: 2026-09-18 Cited by: Introduction.
Hewitt et al. (1973) C. Hewitt, P. Bishop, and R. Steiger A universal modular ACTOR formalism for artificial intelligence. In Proceedings of the 3rd International Joint Conference on Artificial Intelligence (IJCAI-73), Stanford, Calif., pp. 235–245. Cited by: Introduction.
Kasnesis et al. (2017) P. Kasnesis, C. Z. Patrikakis, D. Kogias, L. Toumanidis, and I. S. Venieris Cognitive friendship and goal management for the social IoT. Computers & Electrical Engineering 58, pp. 412–428. Cited by: Introduction, Discovery by topic, not by name.
Wang et al. (2023) G. Wang, Y. Xie, Y. Jiang, A. Mandlekar, C. Xiao, Y. Zhu, L. Fan, and A. Anandkumar Voyager: an open-ended embodied agent with large language models. External Links: 2305.16291 Cited by: Introduction.
Wu et al. (2023) Q. Wu, G. Bansal, J. Zhang, Y. Wu, B. Li, E. Zhu, L. Jiang, X. Zhang, S. Zhang, J. Liu, A. H. Awadallah, R. W. White, D. Burger, and C. Wang AutoGen: enabling next-gen LLM applications via multi-agent conversation. External Links: 2308.08155 Cited by: Introduction.