Plugin Architecture in Practice: A Guide to Five Plugin Patterns

    This article breaks down five common plugin patterns used in plugin-based architectures: minimal plugins for validating the loading pipeline, tool plugins that expose custom capabilities to a model, event plugins that hook into framework lifecycle moments, configuration plugins that accept user settings, and service plugins that provide reusable functionality to other plugins. You will learn a shared three-step setup, key interfaces such as apply, inject, defineTool, effect, and provide, and practical guidance on lifecycle cleanup, configuration defaults, and how to combine patterns in real projects.

    1. Why Start With Examples: The Learning Path for Plugin Development

    Specification documents for plugin systems usually describe constraints, while example code shows workable solutions. For developers approaching the plugin mechanism for the first time, reading the specification directly can lead into the weeds of abstract definitions. Starting from a minimal plugin that prints a log line quickly builds a closed-loop understanding of writing, loading, and verification.

    This article uses the plugin framework adopted by an AI coding tool as its background, abstracts five common plugin patterns, and explains the design intent, key interfaces, and implementation details of each one. Note that whether a plugin is called a host plugin or a model-side plugin, the runtime and loading flow are identical; the only difference is what capability the plugin registers internally.

    The five patterns cover the main plugin development scenarios: validating the loading pipeline, exposing tools to the model, listening to framework events, accepting external configuration, and providing services to other plugins. They are not mutually exclusive. In real projects, a mature plugin is often a combination of several patterns.

    2. The Common Skeleton: Get the Loading Pipeline Working in Three Steps

    All five examples share the same directory structure and startup approach. Understanding this skeleton is a prerequisite for everything that follows.

    Step 1: Create an Isolated Working Directory

    Under the source checkout root, create an isolated plugin workspace containing a source directory and an overlay configuration file:

    1. project-root/ # checkout root
    2. └── scratch-plugin/
    3. ├── src/
    4. │ └── my-plugin.ts # all examples go in this file
    5. └── overlay.yml # overlay configuration

    Keeping the plugin in a separate directory instead of modifying the main project source has obvious benefits: plugin code is physically isolated from framework code, which makes version management and rollback easier and keeps the main build output clean.

    Step 2: Write the Overlay Configuration

    The core purpose of an overlay is to contribute configuration incrementally, not to replace the main configuration. In the configuration, the plugin id identifies the instance, and the name field points to the absolute path of the plugin source:

    1. - id: demo
    2. name: '/absolute/path/to/project-root/scratch-plugin/src/my-plugin.ts'

    There is a common pitfall here: the path must be absolute. The reason is that the overlay only contributes configuration entries and does not change the profile directory baseline used by the loader when resolving module paths. If a relative path is used, the loader resolves it against the profile directory, ends up pointing to the wrong location, and the plugin fails silently.

    Step 3: Start and Verify

    Launch the host environment with the startup command that includes the overlay parameter. The expected result is that the UI works normally and the plugin is mounted into the plugin tree. If you do not see the expected logs, check in this order: whether the path is absolute, whether the source has compilation errors, and whether the overlay indentation follows the required format.

    3. Pattern 1: The Minimal Plugin — Validate the Environment and Loading Pipeline

    The minimal plugin exports only a name constant and an apply function, and the function body prints a single log line:

    1. import type { Context } from '@framework/cordis'
    2. export const name = 'hello-plugin'
    3. export function apply(ctx: Context) {
    4. console.log('[hello-plugin] plugin loaded!')
    5. }

    The value of this pattern is that it acts as a pipeline probe. Failures in plugin systems are often silent: a misconfigured entry does not raise an error, it simply does not load. So in engineering practice, follow one rule: before developing any complex plugin, get the minimal plugin running and printing logs first. If you do not see that output, do not stack on more functionality, or the cost of fault localization will multiply.

    4. Pattern 2: The Tool Plugin — Let the Model Call Your Capability

    The goal of a tool plugin is to wrap a custom capability as a tool the model can call. There are two implementation points: declare a dependency on the tool registry via inject, and call defineTool in apply to define and register the tool.

    1. import type { Context } from '@framework/cordis'
    2. export const name = 'tool-plugin'
    3. export const inject = ['tools']
    4. export function apply(ctx: Context) {
    5. ctx.tools.defineTool({
    6. name: 'query_status',
    7. description: 'Query the current status of a specified resource',
    8. parameters: {
    9. type: 'object',
    10. properties: { id: { type: 'string' } },
    11. required: ['id'],
    12. },
    13. async execute(args) {
    14. return { id: args.id, status: 'running' }
    15. },
    16. })
    17. }

    Three design points are worth noting. First, inject is a declarative dependency; the framework uses it to guarantee the tool registry is ready before the plugin’s apply runs, avoiding manual null checks. Second, the tool description and parameter schema are the only basis for the model to select the tool correctly. The description should state what it does, when to use it, and what the parameters mean, rather than simply restating the function name. Third, execute should be idempotent and return quickly; long-running tasks should be split into asynchronous jobs that return a job identifier, to avoid blocking the main interaction loop.

    5. Pattern 3: The Event Plugin — Insert Logic at Framework Moments and Clean Up Automatically

    Event plugins insert logic at specific framework moments, such as session start, before a message is sent, or after a configuration change. The key interface is ctx.effect, which binds a callback to the lifecycle and unbinds it automatically when the plugin is unloaded, so there is no need to remove listeners manually.

    1. export function apply(ctx: Context) {
    2. ctx.effect(() => {
    3. const off = ctx.events.on('session/start', (s) => {
    4. console.log('[event-plugin] session started:', s.id)
    5. })
    6. return () => off()
    7. })
    8. }

    Automatic cleanup is the core value that distinguishes plugin systems from ordinary callback registration. In development mode with hot reload, plugins are repeatedly unloaded and reloaded. If listeners, timers, and file handles are not released when the plugin is destroyed, they quickly accumulate into memory leaks and duplicate triggers. So it is recommended to put every resource that needs releasing into the cleanup function returned by effect, including timers, subscriptions, and temporary caches.

    6. Pattern 4: The Configuration Plugin — Let Users Change Plugin Behavior

    A configuration plugin exports a Config type and a corresponding Schema, so the host can validate user configuration at load time and inject it into the second parameter of apply.

    1. export interface Config {
    2. level: 'debug' | 'info' | 'warn'
    3. maxItems: number
    4. }
    5. export const Config = {
    6. type: 'object',
    7. properties: {
    8. level: { type: 'string', enum: ['debug', 'info', 'warn'], default: 'info' },
    9. maxItems: { type: 'number', default: 20 },
    10. },
    11. required: ['level'],
    12. }
    13. export function apply(ctx: Context, config: Config) {
    14. console.log('[config-plugin] level =', config.level, 'max =', config.maxItems)
    15. }

    Configuration design should follow three practices: provide sensible defaults for every field so the plugin works with zero configuration; use enums and numeric bounds to constrain value ranges, catching errors at load time rather than at runtime; and stay reactive to configuration changes, so users do not have to restart the host for changes to take effect.

    7. Pattern 5: The Service Plugin — Let Other Plugins Call You

    A service plugin encapsulates its capability as a class and registers it in the service table. Other plugins declare the service name via inject to obtain the instance.

    1. export class MetricsService {
    2. private counter = 0
    3. hit() { return ++this.counter }
    4. }
    5. export function apply(ctx: Context) {
    6. ctx.provide('metrics', new MetricsService())
    7. }

    The consumer side uses export const inject = ['metrics'] and then uses ctx.metrics directly in apply. The essence of this pattern is dependency inversion: callers do not depend on implementation details, only on the service contract. In engineering, it is recommended to define a clear interface for the service rather than exposing the class directly, and to make the service lifecycle explicit — singleton or per-session — otherwise state crosstalk is likely.

    8. Combining Patterns and Choosing the Right One

    In real development, combine the five patterns as needed: a business plugin is usually both a configuration plugin and a service plugin, using effect internally to manage events and defineTool to expose model tools. When choosing, start from three questions: does it need to be called by the model, does it need to respond to user configuration, and is it reused by other plugins. Only introduce the corresponding pattern for capabilities where the answer is yes, avoiding the maintenance burden of premature abstraction. Once you master this skeleton and the five patterns, plugin development moves from copying examples to designing against contracts, which is the key step in unlocking the real extensibility value of a plugin architecture.