Why Uninstalling Plugins Is So Hard—and How Registering Undo Actions at Install Time Fixes It
Plugin lifecycle management is a critical yet often underestimated challenge in agent runtime environments. This article explores why plugin uninstallation tends to fail—from human oversight to shared resource conflicts—and introduces a design pattern where every install action registers its corresponding undo action at install time. By letting the runtime manage rollback order, dependency declarations, and event-driven collaboration, teams can achieve reliable hot reloads and long-term system stability. The discussion includes code examples for undo stacks, topology-based dependency resolution, an event bus implementation, and a practical checklist for designing robust plugin systems.
一、插件安装到底留下了什么
What a Plugin Installation Actually Leaves Behind
In an agent runtime environment, a plugin’s value is largely defined by what it “injects” into the running system. Taking a typical command-line execution tool as an example, installing it into the runtime usually involves three types of actions:
- Registering a tool: A new entry named
shellis added to the tool registry, letting the model know the tool exists and can be invoked during a conversation. - Contributing prompts: A usage guideline is appended to the system prompt, such as “After executing a command, check the exit code; if it is non-zero, explain the reason for the failure.”
- Attaching event listeners: The plugin subscribes to events such as “tool call timeout” and executes handling logic when they occur.
Beyond these three, a plugin may also start scheduled tasks, open file handles, or establish network connections. In other words, installation is not merely copying a file—it is a series of operations the plugin performs within a live system, leaving a series of observable traces behind.
Every request the model receives is typically assembled by the runtime from these traces: the tool registry is built from each plugin’s registration results, and the system prompt is composed from each plugin’s contributed segments. The state of plugins therefore directly determines the world the model sees. If these traces are not properly cleaned up, the model’s view of the world will be inconsistent with the capabilities that are actually available.
二、卸载的难点在哪里
Why Uninstallation Is Difficult
Suppose this command-line execution tool needs to be replaced with another implementation, or a developer has modified one line of code and wants a hot reload. The following must be cleaned up:
- The
shellentry in the tool registry must be removed, otherwise the model will see a tool that has no executor and will only get errors when invoking it. - The usage guideline in the prompt must be withdrawn, otherwise the model will act based on a capability that no longer exists.
- The event listener must be unsubscribed, otherwise the old code may still be triggered after the new implementation is loaded.
- Timers and file handles must be closed, otherwise resources will be continuously occupied.
The most naive approach is to have the plugin author write separate install and uninstall functions and rely on them to keep the two paired:
# Anti-pattern: install and uninstall are maintained separatelydef install(runtime):runtime.tools.register("shell", run_shell)runtime.prompts.add("After executing a command, check the exit code")runtime.events.on("tool_timeout", on_timeout)def uninstall(runtime):runtime.tools.unregister("shell")# The prompt and event listener are omitted, leaving residue behind
This approach has two typical problems. First, humans make mistakes. Three items are installed, but the uninstaller only removes two—the omitted item becomes residue. Second, ownership of shared resources is unclear. When two plugins depend on the same service, the one that is uninstalled first may mistakenly tear down a resource that the other plugin still needs.
As the number of plugins grows, these problems are amplified. Imagine a system that manages dozens of dynamically assembled plugins simultaneously and supports hot reload. If cleanup relies entirely on the plugin author’s discipline, residue will accumulate and eventually undermine the system’s stability and predictability.
三、核心思路:安装时同步登记撤销动作
The Core Idea: Register Undo Actions at Install Time
The solution can be summarized in one sentence: do not make authors maintain the “install” and “uninstall” logic in two separate places. Instead, whenever an installation action occurs, the corresponding undo action is registered at the same time. The runtime stores these undo actions and executes them in order during uninstallation.
The following code is a schematic implementation meant to illustrate the mechanism, not a real interface from a specific framework:
class PluginScope:"""Records all undo actions registered during plugin installation."""def __init__(self):self._undo_stack = []def defer(self, undo_fn):self._undo_stack.append(undo_fn)def dispose(self):# Last-in, first-out: the most recently installed items are removed first,# avoiding breaking dependency relationshipswhile self._undo_stack:self._undo_stack.pop()()def install(ctx):ctx.tools.register("shell", run_shell)ctx.defer(lambda: ctx.tools.unregister("shell"))ctx.prompts.add("After executing a command, check the exit code")ctx.defer(lambda: ctx.prompts.remove("After executing a command, check the exit code"))handle = ctx.events.subscribe("tool_timeout", on_timeout)ctx.defer(handle.cancel)
This design brings three changes:
- The pairing is guaranteed by the runtime. Every registration is accompanied by a deferred undo action. The author no longer needs to remember what to do during uninstallation.
- The undo order is predictable. The last-in-first-out order is the reverse of the installation order, ensuring that the most recently installed items are removed first, reducing anomalies caused by dependency ordering.
- Partial rollback is possible on failure. If installation fails midway, the runtime only needs to execute the already-registered undo actions to restore the system to its pre-installation state.
For services shared by multiple plugins, reference counting can be introduced. Each time a plugin acquires the service, the counter is incremented; on uninstallation, the counter is decremented, and resources are only truly released when the count reaches zero. This way, the plugin that is uninstalled first will not mistakenly tear down a service still used by others.
四、声明依赖:先就绪,再启动
Declaring Dependencies: Ready First, Then Start
The undo mechanism solves the problem of “clean removal,” while dependency declaration solves the problem of “correct installation.” A plugin should declare in its manifest what it requires and what it provides, and the runtime should check whether the dependencies are ready before allowing the plugin to start.
manifest = {"name": "shell-tool","version": "1.0.0","requires": ["logging", "sandbox"], # Capabilities that must be ready before startup"provides": ["tool:shell"], # Capabilities this plugin offers externally}
The runtime can build a directed graph based on these dependency relationships and use topological sorting to determine the startup order. Python’s standard library graphlib.TopologicalSorter can handle this, as shown below:
from graphlib import TopologicalSorterdeps = {"shell-tool": {"logging", "sandbox"},"sandbox": {"logging"},"logging": set(),}order = list(TopologicalSorter(deps).static_order())# logging comes first in the result, shell-tool comes last
Dependency declarations bring two additional benefits. First, when a dependency is missing, the runtime can explicitly refuse to start the plugin with a specific list of missing items, rather than encountering untraceable null-pointer errors or undefined behavior at runtime. Second, when uninstalling a low-level dependency, the runtime can identify all upper-level plugins that depend on it and decide whether to stop them first or reject the uninstallation.
五、通过事件实现插件间协作
Plugin Collaboration Through Events
If plugins call each other directly, coupling quickly grows. A more robust approach is to communicate through an event bus: publishers only declare “what happened,” and subscribers decide how to respond—neither side needs to know the other exists.
Common collaboration patterns include:
- Publish-subscribe: One party sends a notification, multiple parties receive it; suitable for state change notifications.
- Request-response: One party sends a request and waits for a result; suitable for scenarios that require a return value.
- Broadcast: Events are distributed to all listeners; suitable for global state synchronization.
- Filter chain: Events pass through multiple handlers in sequence, each of which can modify or intercept the event; suitable for auditing, data masking, and similar scenarios.
- Sequential pipeline: Multiple processing stages execute in a fixed order; suitable for workflows with dependencies between stages.
The event mechanism and the undo mechanism need to be used together. Subscribing is itself a registration action that needs to be undone—a plugin must cancel its subscriptions on uninstallation, otherwise old handlers will keep receiving events. The following schematic code shows a minimal event bus:
class EventBus:def __init__(self):self._handlers = {}def subscribe(self, topic, handler):self._handlers.setdefault(topic, []).append(handler)class Handle:def cancel(inner_self):self._handlers[topic].remove(handler)return Handle()def publish(self, topic, payload):for handler in list(self._handlers.get(topic, [])):handler(payload)
Here publish copies the handler list before iterating, so that a handler canceling its own subscription during a callback does not modify the list currently being traversed. Such details are easy to overlook in real implementations, yet they directly affect system stability.
六、热重载的实施步骤
Implementing Hot Reload
Hot reload is one of the scenarios where a plugin mechanism demonstrates its greatest value. A reliable hot-reload process typically includes the following steps:
- Mark: Identify the plugin to be replaced and all of its dependents.
- Reverse uninstall: Execute undo actions in reverse dependency order until all traces of the target plugin are cleared.
- Replace: Load the new version of the plugin code.
- Reassemble by dependency: Reinstall the affected plugins in topological order.
- Verify: Check that the tool registry, prompts, and event subscriptions match expectations.
- Rollback: If any step fails, execute the registered undo actions and restore the previous version.
def hot_reload(runtime, plugin_name, new_module):affected = runtime.dependents_of(plugin_name) + [plugin_name]for name in reversed(runtime.topo_order(affected)):runtime.dispose(name)runtime.load(plugin_name, new_module)for name in runtime.topo_order(affected):try:runtime.install(name)except Exception:runtime.rollback_all()raise
The key to this code lies in step 5, verification. Completing the installation alone does not prove the system is in a correct state; only after confirming that the tool registry, prompts, and subscription relationships all meet expectations can the hot reload be considered successful.
七、设计检查清单
Design Checklist
When designing or reviewing a plugin system, the following items can be checked one by one:
- Does every registration, subscription, and resource acquisition action have a corresponding undo action registered?
- Is the undo order the reverse of the installation order?
- Are shared resources managed with reference counting or an equivalent mechanism?
- Does the plugin declare its dependencies and provided capabilities? Does it explicitly refuse to start when dependencies are missing?
- When uninstalling a plugin, can the system list the affected upper-level plugins?
- How are failures of undo actions themselves handled—log and continue, or abort the process?
- Can a hot reload be rolled back to the pre-installation state on failure?
- Do plugins communicate through events rather than direct calls?
The failure of an undo action is a frequently underestimated issue. The undo logic itself can fail, for example, when a file has already been deleted or a network connection has been closed. A sensible practice is to make undo actions as idempotent as possible—executing them repeatedly should produce no additional side effects—and to isolate individual undo failures so that one plugin’s cleanup failure does not block the cleanup of other plugins.
八、对插件生态发展的思考
Reflections on the Plugin Ecosystem
The scale of a plugin ecosystem depends on two factors: whether developers are willing to write plugins, and whether the runtime can reliably host a large number of them. The former relies on interface simplicity; the latter relies on dependable lifecycle management.
“Register undo actions at install time” embeds the lifecycle contract into the runtime itself, allowing plugin authors to focus solely on their own functionality. As the number of plugins grows, the value of this contract becomes more evident: the system can replace components without restarts, and when a plugin misbehaves, the source of residue can be quickly traced.
At the same time, ecosystem expansion brings new challenges. The dependency graph among plugins becomes increasingly complex, version compatibility needs dedicated management, and permission boundaries must be well defined. Which tools a plugin can access, which context it can read, and which events it can subscribe to should all be explicitly authorized by the runtime rather than open by default.
For teams designing or selecting such systems, three things are recommended as top priorities: whether the lifecycle is managed uniformly by the runtime, whether dependencies can be machine-checked, and whether inter-plugin communication goes through an auditable event channel. These three items are the foundation for the long-term, stable evolution of any plugin system.
