Five Plugin Patterns: From Loading Validation to Service Collaboration
Explore five plugin patterns in a Cordis-style framework: minimal plugins, tool registration, event listeners, configuration injection, and shared services. This guide covers project setup, dependency declarations, lifecycle cleanup, and practical checks for loading, configuration, and plugin collaboration, while identifying APIs that must be adapted to your framework version.
1. Scope and Prerequisites
In a plugin-based framework, each plugin declares what it registers with the framework. This article uses a Cordis-style plugin model, including imports such as import type { Context } from 'cordis'. If you use another framework, replace service names, event names, and APIs with those documented for your framework. The underlying ideas—directory organization, plugin loading, and dependency injection—remain the same.
These examples have not been individually tested against a specific framework version. They contain two kinds of APIs: common patterns in this plugin model and placeholders explicitly marked as requiring replacement. The latter illustrate an approach and are not guaranteed to run as written.
Before starting, check the framework version pinned in your project’s lockfile and consult the documentation for that version.
Requirements:
- Node.js 18 or later and pnpm 8 or later.
- A TypeScript project, with plugin source files in
scratch-plugin/inside the framework checkout.
2. Comparing the Five Plugin Patterns
The following table summarizes what each pattern registers and how to verify it.
| Pattern | Registers | Dependency declaration | Cleanup | Configuration exposure | Relationship to other plugins | Verification |
|---|---|---|---|---|---|---|
| Minimal plugin | Nothing | None | None | None | None | Loading message appears in startup logs |
| Tool plugin | Tool definition | inject = ['tools'] |
ctx.effect returns unregister logic |
None | Higher-level components call it through the tool registry | Tool call returns the expected result |
| Event listener | Listeners and timers | None | ctx.effect returns a cleanup function |
None | None | No more tick output after unloading |
| Configuration injection | Configuration schema | None | None | Schema and the second argument to apply |
None | Changing configuration and restarting changes the output |
| Service plugin | Service instance | Service name declared in inject |
Released with the service lifecycle | Optional | Other plugins call it by service name | Removing the service stops consumer output |
These patterns build on one another. First verify loading, then register a tool, manage listener and timer lifecycles, expose configuration, and finally enable collaboration between plugins.
Work through them in this order and verify each example before moving on.
3. Directory Layout and Startup
All five examples use the same directory structure. Create the plugin project under the framework root:
framework/├── package.json├── overlay.yaml└── scratch-plugin/└── src/├── hello-plugin.ts├── tool-demo.ts├── event-demo.ts├── config-demo.ts├── calc-service.ts└── service-consumer.ts
Keeping plugin source separate from framework source makes it easier to maintain independently.
The overlay.yaml file declares which plugins to load and their configuration. It does not change the framework’s base directory for path resolution.
In the examples below, <FRAMEWORK_ROOT> represents the absolute path to your framework root. Replace it with your actual path, such as /home/dev/framework or D:/dev/framework. Quote Windows paths.
plugins:- id: helloname: "<FRAMEWORK_ROOT>/scratch-plugin/src/hello-plugin.ts"
Each id must be unique, and name must be the absolute path to the plugin source file. Relative paths are resolved against the framework’s configured base directory and can lead to module-not-found errors.
Do not add every plugin at once. Add one entry to overlay.yaml after completing each example, then start the framework and verify it. This limits troubleshooting to the plugin you just added.
Run:
pnpm installpnpm dev
The startup command depends on the dev script in the framework’s package.json. If your framework requires an argument to select the overlay file, such as pnpm dev -- --overlay overlay.yaml, add it according to the documentation.
After startup succeeds, the logs should show the web server’s listening address. The port varies by framework.
4. Example 1: A Minimal Plugin to Verify Loading
A minimal plugin exports only name and apply. It registers no capabilities; its purpose is to confirm that the environment and loading process work.
// scratch-plugin/src/hello-plugin.tsimport type { Context } from 'cordis'export const name = 'hello-plugin'export function apply(ctx: Context) {console.log('[hello-plugin] plugin loaded!')}
Expected output: The terminal prints [hello-plugin] plugin loaded! after startup.
If this message does not appear, check the following in order:
- The
nameinoverlay.yamlis an absolute path, and the file exists. - The
iddoes not duplicate another entry. - YAML indentation is correct. YAML does not allow tabs for indentation.
- The source passes compilation. Run
npx tsc --noEmitto check types.
If loading does not work, none of the later examples can take effect. Resolve this step before continuing.
5. Example 2: A Tool Plugin for Higher-Level Callers
A tool plugin obtains the tool registry through dependency injection. inject is an exported plugin field alongside name, not an argument to apply.
// scratch-plugin/src/tool-demo.tsimport type { Context } from 'cordis'export const name = 'tool-demo'export const inject = ['tools']export function apply(ctx: Context) {ctx.effect(() => {// This example assumes defineTool returns an unregister function.// The effect calls it when the plugin is unloaded.return ctx.tools.defineTool({name: 'calc_add',description: 'Calculate the sum of two numbers. Use this tool when the user needs addition.',parameters: {type: 'object',properties: {a: { type: 'number', description: 'First operand' },b: { type: 'number', description: 'Second operand' },},required: ['a', 'b'],},async execute({ a, b }) {try {if (typeof a !== 'number' || typeof b !== 'number') {return { ok: false, error: 'Arguments must be numbers' }}return { ok: true, data: a + b }} catch (err) {return { ok: false, error: String(err) }}},})})console.log('[tool-demo] Registered tool calc_add')}
If defineTool returns void in your framework, you cannot return its result directly from the effect callback. Instead, provide explicit unregister logic.
The following is pseudocode. Replace the removal method with the actual API documented by your framework:
// Pseudocode: replace removeTool with the framework's actual unregister method.ctx.effect(() => {ctx.tools.defineTool({ /* Same tool definition as above */ })return () => ctx.tools.removeTool('calc_add')})
Expected output:
- Startup logs include
[tool-demo] Registered tool calc_add. - Calling the tool with
{ "a": 1, "b": 2 }returns{ ok: true, data: 3 }. - Passing string arguments returns
{ ok: false, error: 'Arguments must be numbers' }.
Keep three points in mind when writing tools:
- Use an accurate description. Higher-level callers commonly rely on it to decide whether to invoke the tool.
- Define a strict parameter schema. This reduces runtime type errors.
- Catch exceptions and return structured results. This makes responses easier for callers to parse.
6. Example 3: Event Listeners and Lifecycle Cleanup
Event-listener plugins run logic at specific points in the framework lifecycle. Place both listeners and timers inside ctx.effect so the framework can clean them up when the plugin is disabled or reloaded.
// scratch-plugin/src/event-demo.tsimport type { Context } from 'cordis'export const name = 'event-demo'export function apply(ctx: Context) {const onReady = () => console.log('[event-demo] Received ready event')// This example assumes ctx.on returns an unregister function,// which the effect calls when the plugin is unloaded.ctx.effect(() => ctx.on('ready', onReady))ctx.effect(() => {const timer = setInterval(() => console.log('[event-demo] tick'), 10_000)return () => {clearInterval(timer)console.log('[event-demo] Timer cleaned up')}})}
ready is an assumed event name in this article. Replace it with an event documented by your framework.
If ctx.on does not return an unregister function, manually call the framework’s listener-removal API in the effect’s cleanup function. Otherwise, the listener will remain registered after unloading.
Expected output: When the framework emits ready, the terminal prints [event-demo] Received ready event. It then prints [event-demo] tick every 10 seconds.
To test cleanup, remove the event-demo entry from overlay.yaml, then restart or use the framework’s reload feature. The expected cleanup message is [event-demo] Timer cleaned up, followed by no further tick output.
If tick continues after unloading, check that the timer is registered inside an effect and that its cleanup function is being used.
7. Example 4: Configuration Injection Through the Overlay
Configuration injection lets plugin settings come from overlay.yaml instead of being hard-coded. The plugin exports a configuration schema, and the framework passes the validated configuration as the second argument to apply.
First, add a configuration entry to the overlay:
- id: config-demoname: "<FRAMEWORK_ROOT>/scratch-plugin/src/config-demo.ts"config:greeting: HellointervalSec: 10
// scratch-plugin/src/config-demo.tsimport type { Context } from 'cordis'import { Schema } from 'cordis'export const name = 'config-demo'export interface Config {greeting: stringintervalSec: number}// Confirm these schema construction methods in your version's documentation.export const Config: Schema<Config> = Schema.object({greeting: Schema.string().default('Hello').description('Greeting to print'),intervalSec: Schema.number().default(30).min(1).description('Print interval in seconds'),})export function apply(ctx: Context, config: Config) {ctx.effect(() => {const timer = setInterval(() => {console.log(`[config-demo] ${config.greeting}`)}, config.intervalSec * 1000)return () => clearInterval(timer)})}
Schema construction methods vary by version. Methods such as Schema.object, default, and min are common forms in this model, but you should verify them against your version before use.
Expected output: With greeting: Hello and intervalSec: 10, the terminal prints [config-demo] Hello every 10 seconds.
Restart after changing the overlay configuration for the changes to take effect. If you set intervalSec to 0, schema validation should prevent startup and report a validation error. That error confirms that configuration validation is active.
Configuration injection checklist:
- Field names under
configinoverlay.yamlmatch the schema. - Omitting
configcauses the plugin to use the schema defaults. - Invalid values, such as
intervalSec: 0, are rejected at startup. - Changing configuration and restarting changes the output.
8. Example 5: Service Collaboration Between Plugins
A service plugin packages its capabilities as a named service that other plugins can call. This example uses two plugins: calc-service provides the service, while service-consumer declares its dependency and calls it.
// scratch-plugin/src/calc-service.tsimport type { Context } from 'cordis'export const name = 'calc-service'export function apply(ctx: Context) {ctx.effect(() => {// ctx.provide is an assumed service registration API in this example.// Replace it with your framework's actual registration mechanism.ctx.provide('calc', {add: (a: number, b: number) => a + b,})console.log('[calc-service] Service calc is available')})}
// scratch-plugin/src/service-consumer.tsimport type { Context } from 'cordis'export const name = 'service-consumer'export const inject = ['calc']export function apply(ctx: Context) {// ctx.calc requires the framework's service type declarations.// If TypeScript reports an error, add declarations as documented.const sum = ctx.calc.add(1, 2)console.log('[service-consumer] 1 + 2 =', sum)}
If your framework registers services differently, replace the provide call and the relevant type declarations. The dependency declaration and loading-order concepts still apply.
Expected output: The terminal prints these messages in order:
[calc-service] Service calc is available[service-consumer] 1 + 2 = 3
To verify the dependency relationship, remove the calc-service entry from overlay.yaml and restart. Because the service declared in inject is unavailable, service-consumer should not activate, and its message should not appear in the startup logs.
This confirms that the dependency declaration is taking effect.
9. Cleanup and Injection Checklist
After completing all examples, check the following:
- Each example produces its expected startup output.
- Every
nameinoverlay.yamlis an absolute path, and allidvalues are unique. - Tools, listeners, and timers are registered through
ctx.effectand stop producing output after unloading. - Names in
injectmatch the registered service names. - Configuration fields match the schema, and invalid values are rejected at startup.
- Removing
calc-servicestopsservice-consumerfrom producing output.
10. Common Errors and Troubleshooting
- Module not found: Check that the path is absolute, capitalization matches the actual file path, and Windows paths are quoted.
- Compilation error: Run
npx tsc --noEmitand fix the source according to the reported errors. - Undefined service or missing service type: Check the dependency name in
injectand the service type declarations described in the service example.
