Building and Debugging Plugins for Agent Frameworks: A Hands-on Guide
This article provides a practical walkthrough for creating, building, and debugging custom plugins in a plugin-based agent framework. It covers reading the configuration manifest, setting up a TypeScript plugin project, resolving common type errors, differentiating between source and built execution, using workspace linking for local integration, packaging plugins as bundles, understanding profile and runtime module resolution, and troubleshooting runtime errors with a reference table. By following the steps, you will be able to create compilable plugins, locate issues from error messages, and package them for release or rollback.
Introduction
This article follows the complete process of writing and running a custom plugin, covering everything from configuration to troubleshooting. The specific package names, directory structures, and field names in the framework may vary between versions; the examples here are meant to illustrate the structure and underlying concepts. For actual implementation, always refer to the official documentation for your specific version and verify field names.
After reading this article, you should be able to accomplish three things: create a plugin that compiles and runs, locate issues based on error messages, and package the plugin for safe publication or rollback.
1. Understanding the Configuration Manifest
Many beginners treat the framework’s base package as a library to import. In reality, such base packages (often named base or core) are more like a composition manifest—they declare dependencies and inject a set of plugins into an empty configuration tree via configuration.
The framework typically provides only a lightweight dependency injection container and a lifecycle manager. Capabilities such as model adaptation, tool registration, session logging, and the Agent main loop all exist as plugins. Therefore, starting the application can be understood as: the framework reads the configuration, loads plugins as declared, and then initializes them in sequence.
A typical plugin mounting configuration looks like this (field names are illustrative):
plugins:- id: timer-hotreloadenabled: true- id: llm-adapter-openaienabled: trueoptions:model: "your-model-name"- id: session-log-memoryenabled: true- id: tool-registryenabled: true
To switch the underlying LLM adapter, simply replace the llm-adapter-openai line with the target adapter’s id and fill in its required options. The framework source code does not need to be modified. This approach works when the adapter interfaces are consistent. If the new adapter requires additional runtime capabilities, you must confirm that those capabilities are already mounted in the manifest.
2. Creating a Custom Plugin
Start by creating an independent plugin project outside your main workspace:
mkdir my-tool-plugin && cd my-tool-pluginnpm init -ynpm install -D typescript @types/nodenpx tsc --init
A recommended directory structure is as follows:
my-tool-plugin/├── package.json├── tsconfig.json├── tsconfig.build.json├── src/│ └── index.ts└── manifest.json
An example plugin entry point (interface names are illustrative; replace them with the real API from the framework documentation):
// src/index.tsexport default {id: "my-tool",register(ctx: any) {ctx.tools.add({name: "echo",description: "Returns the input text unchanged",run: async (input: { text: string }) => input.text,});},};
The manifest.json file declares the plugin id, version, and entry file. The framework reads it during loading:
{"id": "my-tool","version": "1.0.0","entry": "dist/index.js","permissions": []}
The permissions field should list only the permissions the plugin truly requires. This follows the principle of least privilege and makes future auditing easier.
3. Editor Type Errors and tsconfig Troubleshooting
Editor type errors usually occur because TypeScript cannot resolve the framework’s type declarations. If the framework uses a monorepo or custom path aliases, the standard tsconfig may not locate these types.
Below is a reference tsconfig configuration. The paths mapping links the framework’s type package to a local declaration directory:
{"compilerOptions": {"target": "ES2022","module": "NodeNext","moduleResolution": "NodeNext","strict": true,"esModuleInterop": true,"skipLibCheck": true,"baseUrl": ".","paths": {"@framework/types": ["node_modules/@framework/types/dist/index.d.ts"],"@framework/types/*": ["node_modules/@framework/types/dist/*"]},"outDir": "dist","rootDir": "src"},"include": ["src"]}
paths affects only the editor and type checking, not runtime resolution. Runtime rules are defined separately; see Section 7 for details.
To locate the virtual type declaration file, first run npm ls @framework/types to confirm the package is installed, then check the types field in its package.json. If that field is empty, the package does not provide type declarations, and you will need to confirm with the framework maintainer.
A pure type check outside the editor can distinguish between “editor issues” and “code issues”:
npx tsc --noEmit -p tsconfig.json
If this command passes but the editor still shows errors, it usually means the editor is using a different TypeScript version. In VS Code, run “TypeScript: Select TypeScript Version” and choose the project-local version.
Common error scenarios:
| Symptom | Likely Cause | Resolution |
|---|---|---|
| TS2307: Cannot find module ‘@framework/types’ | Package not installed or paths not configured | Run npm install and verify paths |
Type completions missing but tsc passes |
Editor uses a different TypeScript version | Switch to the project-local TypeScript |
| TS2307 only in ESM files | moduleResolution does not match module |
Set both to NodeNext and add .js extensions to relative imports |
| TS2304: Cannot find name ‘Foo’ | Framework types not exported or import missing | Check index.d.ts exports and add the import |
| Old error persists after type changes | Editor cache | Restart the TypeScript service or reopen the window |
4. Build vs Source Launch: Key Differences
During development, source launching is common, but for production you must run the built output. The differences between the two paths are summarized below:
| Aspect | Source Launch | Built Output Launch |
|---|---|---|
| Typical command | npm run dev |
npm run build && npm start |
| Module resolution | Runtime transpilation by dev tool; path aliases need tool support | Directly resolves JS based on package.json exports or entry |
| Hot reload | Usually supported; changes apply automatically | Usually not supported; requires rebuild and restart |
| Environment variables | Often reads .env or dev config |
Often reads production variables; must be set in advance |
| Startup speed | Slower due to transpilation | Faster |
| Error location | Stack points to TS source files, easier debugging | Stack points to dist JS; enable sourcemaps |
These differences hold for most frameworks, but specifics vary by version; always confirm with your framework’s documentation.
A typical build script has four steps: clean old output, compile, copy static assets, and generate manifest. The following commands can be configured as the build script in package.json:
rm -rf dist && npx tsc -p tsconfig.build.json && cp -r assets dist/ && node scripts/gen-manifest.js
tsconfig.build.json should extend the base configuration and exclude test files to prevent them from entering the build output.
When build failures occur, troubleshoot sequentially: first check for compilation errors (type or syntax issues), then check whether output files are missing (copy step), and finally verify whether the manifest was generated (script step). Step-by-step diagnosis is faster than retrying the whole process blindly.
5. Workspace and Local Integration
When multiple plugins depend on each other, publishing test packages each time slows down development. The pnpm workspace protocol allows local packages to reference each other directly.
At the repository root, create pnpm-workspace.yaml:
packages:- "plugins/*"- "apps/*"
Then, in the dependent package’s package.json, use the workspace protocol:
{"dependencies": {"my-tool-plugin": "workspace:*"}}
Common integration commands:
pnpm installpnpm -r buildpnpm --filter my-tool-plugin dev
--filter runs only the specified package, ideal for diagnosing a single plugin. -r builds all packages in dependency order, which can expose cross-package type errors early.
If your framework does not support pnpm workspaces, you can fall back to npm link, but be aware that it modifies global links; run npm unlink afterward to clean up.
6. From Local Plugin to Bundle Release
Once the plugin is developed, you need to package it as an independently distributable Bundle. The Bundle contains the plugin’s build output, dependency declarations, and the manifest. Users can add it to their applications via an installation command.
Before packaging, review the list of files to be published to avoid including .env, test data, or credentials:
npm pack --dry-run
After confirming, generate the tarball:
npm pack
The resulting my-tool-plugin-1.0.0.tgz typically has the following structure when extracted:
package/├── package.json├── manifest.json└── dist/├── index.js└── index.d.ts
Install locally for testing:
npm install ./my-tool-plugin-1.0.0.tgz
After installation, start the application once and confirm the plugin id appears in the framework’s loading log.
Before final publication, perform these security checks:
- Run
npm auditand address high-severity dependency vulnerabilities. - Pin dependency versions and commit lock files to avoid unexpected behavior from minor upstream changes.
- Verify the
permissionsfield inmanifest.jsonto ensure no excessive permissions. - The
npm publish --access publiccommand is difficult to fully retract once executed. Confirm the package name and version before publishing.
Rollback method: if the new version has problems, uninstall it and install the last known good version:
npm uninstall my-tool-pluginnpm install my-tool-plugin@1.0.0
Before rolling back, record the current version number to reproduce the issue.
7. Profile Mechanism and Runtime Module Resolution
7.1 Profile Directory
Frameworks generally use profiles to isolate configuration for different users or environments. Taking ~/.framework/profiles/web as an example, this directory usually stores plugin mounting state, user credentials, and session logs.
Always back up before clearing caches, as sessions and credentials are often unrecoverable once deleted:
cp -r ~/.framework/profiles/web ~/framework-backup-web-$(date +%Y%m%d)rm -rf ~/.framework/profiles/web/cache
If you need to configure a separate toolset for a test environment, copy a profile directory and modify its mounting manifest, leaving the production environment unaffected.
7.2 Loading Order
Runtime loading roughly follows five steps:
- Read the configuration file to obtain the plugin list.
- Parse each plugin’s dependency declarations to construct a dependency graph.
- Apply topological sorting to the dependency graph, placing dependent plugins first.
- Instantiate plugins according to the sorted order via the dependency injection container.
- Call each plugin’s lifecycle hooks, such as
initandstart.
If the framework requires “base plugins” to be loaded first, the usual approach is to place them earlier in the manifest or assign them a higher priority field. Consult your framework’s documentation for specific rules.
7.3 Circular Dependencies
When plugin A depends on B and B depends on A, topological sorting cannot produce a deterministic order. Most frameworks detect the cycle during startup and report an error, often in the form of circular dependency detected: a -> b -> a.
There are two common solutions. The first is to extract the interfaces both plugins need into a third package, so that both A and B depend on that interface package, breaking the cycle. The second is lazy dependency resolution—do not resolve dependencies at construction time, but fetch them from the container at the moment they are actually used:
// Example: resolve dependency at use time to avoid construction-phase cyclesregister(ctx: any) {const getB = () => ctx.container.get("plugin-b");ctx.tools.add({name: "use-b",run: async () => getB().doSomething(),});}
Lazy resolution provides a quick fix but postpones errors to runtime; ensure adequate test coverage. Structurally, extracting shared interfaces is more robust in the long run.
7.4 Node.js Resolution vs. Framework Resolution
Runtime module lookup operates on two levels. The lower level is Node.js’s resolution algorithm, which uses node_modules and the exports field in package.json to locate files. The upper level is the framework’s own resolution, which uses the id from the configuration to locate plugins. Both must succeed for a plugin to load.
If you see “can import but the framework cannot find it,” the problem usually lies in the upper level. If the framework reports a module not found error, the issue is usually in the lower level.
When multiple plugins declare the same id, most frameworks use the later declaration to override the earlier one. However, this rule varies by version; consult the documentation and confirm in the logs which plugin ultimately takes effect.
8. Runtime Error Reference Table
| Startup Error | Likely Cause | Resolution |
|---|---|---|
plugin not found: <id> |
Typo in the configuration id, or the package is not installed | Verify the configuration id, run npm ls to check installation |
circular dependency detected |
Plugins depend on each other | Refer to Section 7.3 |
EADDRINUSE |
Port is occupied by an old process | Use lsof -i :<port> to find and kill the process, or use a different port |
| Hot reload not working | Running from built output | Start with npm run dev |
| Plugin loads but tool is not visible | Tool not registered to the current profile | Check that the profile mounting manifest includes the plugin |
| Credentials invalid | Credentials expired or profile replaced | Restore from backup, or re-authenticate |
9. Checklist
Before finishing development and publication, verify each item:
- The plugin id in the configuration manifest matches the id in
manifest.json. -
npx tsc --noEmitpasses, and the editor uses the project-local TypeScript version. -
npm run buildproduces the correct output and the manifest is generated. - The bundle has been tested via
npm install ./my-tool-plugin-1.0.0.tgzand appears in the loading log. -
npm auditshows no high-severity vulnerabilities, and dependency versions are pinned. -
manifest.jsondoes not contain unnecessary permissions. - A rollback plan is in place, with the last known good version recorded.
