Plugin-Based Agent Frameworks: Writing a Plugin from Scratch
This article uses the full lifecycle of a custom plugin, from creation to installation, as the organizing thread for understanding a plugin-based agent framework. It covers editor resolution, type compilation configuration, build behavior, source versus artifact startup, workspace linking, publishing, user-level profiles, and module resolution, with a focus on why base and core packages are themselves plugins and why common loading errors occur. Readers get a practical five-layer mental model and troubleshooting checklist for diagnosing plugin issues and moving from following tutorials to designing plugin systems independently.
Introduction: Why Writing a Plugin Is the Best Entry Point
The learning curve for a plugin-based agent framework (referred to here as the host framework) is often less about the concepts themselves and more about the coupling between them. An editor error may mean a dependency is not installed, or it may mean the workspace is not linked. A runtime “module not found” error may mean build artifacts are missing, or it may mean user-level configuration in a config directory is overriding project configuration. If you only follow a tutorial once, you have no way to troubleshoot when something goes wrong.
This article takes a different thread: it uses the complete lifecycle of a self-built plugin from zero to installable as the axis, connecting editor resolution, type compilation configuration, builds, startup paths, workspace mechanics, publishing, profiles, and module resolution layer by layer. The prerequisites are modest: basic familiarity with a JavaScript runtime, package managers, and a statically typed language is enough.
1. Foundation: Plugin Containers and Source Code Shipped with Packages
1.1 Everything Is a Plugin, Including Packages That Look Like the Base
The core philosophy of this kind of framework is “everything is a plugin”: there is no privileged kernel that needs patching. Model adapters, tool invocation, session logs, and the agent main loop all exist as plugins and are assembled through configuration. The easiest point for beginners to misunderstand is that packages with names containing base, core, or foundation are themselves plugins, not lower-level libraries that are imported.
Take a “base bundle package” as an example. Its package manifest declares a bundle marker and includes a configuration patch file that inserts about 78 lines of plugin declarations into an empty configuration tree. The content roughly covers:
- Runtime infrastructure: timers and hot reload;
- Model layer: model capability abstraction + concrete model adapters;
- Session layer: session event log and in-memory storage;
- Agent layer: agent interface + default driver (main loop);
- Tool layer: tool registry, prompt assembly, filesystem tools, and retrieval tools;
- Execution layer: subprocess and shell execution;
- Security layer: sandbox and approval policies;
- Support layer: user settings, credential management, subagents and workflows, and web capabilities.
In other words, this package is not “a collection of APIs to be called”; it is an assembly manifest that says “which plugins should be mounted.”
1.2 Why Make the Base Itself a Plugin
- Replaceable: if the default main loop is not suitable, you can replace only the main loop plugin and leave everything else unchanged;
- Trimmable: if web capabilities are not needed, do not mount them, reducing attack surface and startup overhead;
- Observable: every capability boundary is a plugin boundary, so logs, metrics, and approval policies can be attached at the same layer;
- Evolvable: upgrading the base means upgrading the configuration manifest, not resolving merge conflicts in core code.
Once you understand this, later issues such as “module not found” and “configuration does not take effect” become something you can reason about.
2. The First Plugin: Fix Editor Errors First
When creating a plugin according to a tutorial, the most common first obstacle is an editor filled with red squiggles: imports of host framework types fail, and the exported plugin definition has no type hints.
It is better to troubleshoot in a fixed order rather than blindly changing configuration:
- Whether dependencies are actually installed in a resolvable location (inspect the lockfile and directory structure generated by the package manager);
- Whether the target package manifest has a types entry field, and whether the file it points to is published with the package;
- Whether the current package is correctly linked in the workspace (a common local-package issue: source exists but cannot be resolved);
- Whether the include/exclude settings in the type compilation configuration exclude dependency source code;
- Whether editor caches and dependency analysis caches are stale (restart the language service, not the editor window).
A minimal illustrative plugin skeleton:
// src/index.js — plugin export conventionexport const name = 'my-plugin';export const inject = ['tools', 'session']; // declare dependent pluginsexport function apply(ctx) {ctx.tools.register({name: 'echo',description: 'Echo input to verify plugin loading',async execute(input) { return { ok: true, input }; },});}
The key point is that a plugin declares the capabilities it needs through dependency injection rather than directly importing global singletons. This convention determines the later behavior of module resolution and configuration assembly.
3. Clarifying Core Concepts in Type Compilation Configuration
Most editor errors come from confusing four concepts in compilation configuration:
- Compilation target and module output: determines the degree of syntax downleveling and the output module format, and must match how the runtime loads modules; otherwise you get “source runs, artifact does not run”;
- Module resolution strategy: determines “how a package name becomes a file path” and is strongly related to the export fields in the manifest;
- Type roots and path mapping: path mapping only takes effect at compile time and in the editor. It is not automatically followed at runtime. This is a frequent cause of “the editor reports no error, but runtime fails”;
- include/exclude and declaration output: include determines the source range that participates in checking. exclude is often misused to “eliminate errors,” but in practice it only hides the problem until runtime.
One practical rule: any mapping that passes compile time must have an equivalent runtime mechanism as a fallback (workspace links, package export fields, or startup arguments). The two must be designed as a pair.
4. Build System: What a Build Command Actually Does
A standard build command usually performs five things in order:
- Sort packages according to the dependency graph and build dependencies first;
- Run static type checking and stop on failure;
- Generate runtime artifacts (transpile, bundle, or emit per module);
- Generate or validate entry, types, and export fields in the manifest;
- Write incremental cache so the next build can skip unchanged nodes.
Therefore, “build succeeds but runtime fails” usually does not mean the build is broken; it means artifacts and runtime resolution rules do not match. “The build is slow” is often caused by invalid cache or a excessively deep dependency graph.
5. Source Startup and Build Artifacts: Two Runtime Paths
| Dimension | Source startup | Artifact startup |
|---|---|---|
| Loading target | Original source in the workspace | Build output directory |
| Preconditions | Workspace links and source resolution rules | Complete artifacts and correct entry fields |
| Modification feedback | Immediate with hot reload | Requires rebuild |
| Typical problems | Cannot resolve local package | Missing entry, mismatched export conditions |
| Use cases | Local development and debugging | Integration validation, publishing, deployment |
Conclusion: only when both paths work has the plugin truly been “finished.” Verifying only the source path leaves half the risk until after publishing.
6. Workspace Mechanics: Local Links and the Workspace Protocol
A workspace solves the problem of “multiple local packages referencing each other without publishing”:
- The package manager places local packages into the dependency directory as links, so source changes are directly visible;
- Manifests declare versions using the workspace protocol, and the publishing tool replaces them with real semantic versions;
- Dependency hoisting keeps a single copy of same-name dependencies. If resolution finds different copies, the common symptoms are “incompatible types” or “plugin registered twice.”
Troubleshooting mantra: first confirm the link exists, then confirm the real path the link points to, and finally confirm whether multiple copies exist.
7. Publishing: From Local Plugin to Installable Bundle
Before publishing, confirm four things: entry and types fields point to real artifacts; export fields cover the loading conditions used at runtime; the dependency on the host framework is declared as “provided by the host” rather than bundled into the artifact; version numbers follow semantic versioning rules. After publishing, verify once with a “clean environment install + cold start” to avoid local cache masking problems.
8. Profile Mechanism: What the User-Level Configuration Directory Really Is
A profile under the user-level configuration directory (for example, a runtime configuration area in the user home directory) is essentially a “private user configuration overlay”: it applies another configuration patch on top of project configuration for personal preferences, credential references, and local debugging switches.
This leads to three practical rules:
- Priority: user-level overlays usually override project-level configuration. When troubleshooting “configuration changed but does not take effect,” check this layer first;
- Portability: profiles belong to a personal environment and should not be treated as team deliverables;
- Reproducibility: configuration shared by the team should live inside the project, while profiles should contain only differences.
9. The Full Module Resolution Chain
The complete journey of a single import can be broken into seven steps: resolve the package name → read export fields in the manifest → select the corresponding entry by loading conditions → apply compile-time path mapping → enter the dependency directory and resolve symbolic links → obtain the real file path → hit the module cache.
If any step breaks, you get “module not found,” and the error message usually does not tell you which step failed. Memorize this chain together with the two runtime paths from Section 5, and most loading-related issues can be located within ten minutes.
10. Summary and Mental Model
You can compress this into a five-layer model: container layer (plugin assembly and dependency injection) → configuration layer (project configuration + user-level overlay) → resolution layer (manifest exports + workspace links + path mapping) → build layer (dependency ordering + type checking + artifacts) → runtime layer (load either source or artifacts).
A companion troubleshooting checklist: editor errors → check dependencies and type entries; runtime missing module → check links and artifacts; configuration not taking effect → check overlay order; incompatible types → check multiple copies; post-publish anomalies → check export conditions and cold start. With these five layers and this checklist, you are no longer facing a specific error but an entire class of problems—this is the boundary between “following a tutorial” and “being able to design a plugin system independently.”
