Skip to content

Add plugin system #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,34 @@ const results = await runner.runAgentFlows(
);
```

### Creating and Loading Plugins

Extend `Runner` by providing plugin objects or paths when it is constructed. A plugin is a module exporting `{ name, setup(runner) }`.

```javascript
// logger-plugin.js
module.exports = {
default: {
name: 'logger',
setup(runner) {
runner.onUpdate((u) => console.log(u));
},
},
};
```

Load plugins using a file path or directory:

```typescript
import path from 'node:path';
import { Runner } from 'ai-agent-flow';

const runner = new Runner(3, 1000, undefined, [
path.join(__dirname, 'logger-plugin.js'),
path.join(__dirname, 'plugins'), // directory of plugins
]);
```

---

## 🧩 Core Components
Expand Down Expand Up @@ -286,6 +314,7 @@ npm run coverage # Generate coverage report
- [Flow API](./docs/api/flow.md) - Understand Flow creation and management
- [Runner API](./docs/api/runner.md) - Explore Flow execution and monitoring
- [Complete API Reference](./docs/api/index.md) - Full API documentation
- [Plugin Guide](./docs/plugins.md) - Write and load plugins

### Examples

Expand Down
31 changes: 31 additions & 0 deletions docs/plugins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# 🔌 Plugin System

ai-agent-flow supports lightweight plugins that can augment the `Runner` at start up.
A plugin is any module that exports an object with a `name` and `setup` function.

```javascript
// my-plugin.js
module.exports = {
default: {
name: 'my-plugin',
setup(runner) {
// interact with the runner instance
runner.onUpdate((u) => console.log(u));
},
},
};
```

Load plugins by passing them to the `Runner` constructor either directly, via a file path or a directory of plugin files.

```typescript
import path from 'node:path';
import { Runner } from 'ai-agent-flow';

const runner = new Runner(3, 1000, undefined, [
path.join(__dirname, 'my-plugin.js'), // single plugin
path.join(__dirname, 'plugins'), // load all plugins in directory
]);
```

Each plugin's `setup` method is invoked immediately with the runner instance, allowing it to register hooks or modify behavior.
39 changes: 38 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ export * from './nodes/batch';
export * from './types';
export * from './utils/message-bus';
export * from './store';
export * from './plugins';

import type { Context, NodeResult, Transition } from './types';
import { Node } from './nodes/base';
import { ActionNode } from './nodes/action';
import type { Plugin } from './plugins';
import { loadPluginSync, loadPluginsFromDirSync } from './plugins';
import fs from 'fs';

export type { Context, NodeResult, Transition };
export { Node, ActionNode };
Expand Down Expand Up @@ -69,6 +73,7 @@ export class Flow {

export class Runner {
private updateHandler?: (update: { type: string; content: string }) => void;
private plugins: Plugin[] = [];

onUpdate(handler: (update: { type: string; content: string }) => void): void {
this.updateHandler = handler;
Expand All @@ -78,7 +83,39 @@ export class Runner {
private maxRetries = 3,
private retryDelay = 1000,
private store?: import('./store').ContextStore,
) {}
plugins: (Plugin | string)[] = [],
) {
this.registerPlugins(plugins);
}

getPlugins(): Plugin[] {
return this.plugins;
}

registerPlugin(plugin: Plugin): void {
this.plugins.push(plugin);
try {
plugin.setup(this);
} catch {
// ignore plugin errors during setup
}
}

registerPlugins(plugins: (Plugin | string)[]): void {
for (const p of plugins) {
if (typeof p === 'string') {
if (fs.existsSync(p) && fs.statSync(p).isDirectory()) {
const loaded = loadPluginsFromDirSync(p);
loaded.forEach((pl) => this.registerPlugin(pl));
} else {
const plugin = loadPluginSync(p);
if (plugin) this.registerPlugin(plugin);
}
} else {
this.registerPlugin(p);
}
}
}

async runFlow(flow: Flow, context: Context, contextId?: string): Promise<NodeResult> {
if (this.store && contextId) {
Expand Down
35 changes: 35 additions & 0 deletions src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export interface Plugin {
name: string;
setup(runner: import('../index').Runner): void;
}

import fs from 'fs';
import path from 'path';

export function loadPluginSync(modPath: string): Plugin | undefined {
const resolved = path.isAbsolute(modPath) ? modPath : path.resolve(process.cwd(), modPath);
try {

const mod = require(resolved);
const plugin: Plugin | undefined = mod.default ?? mod.plugin;
return plugin;
} catch {
return undefined;
}
}

export function loadPluginsFromDirSync(dir: string): Plugin[] {
const resolvedDir = path.isAbsolute(dir) ? dir : path.resolve(process.cwd(), dir);
if (!fs.existsSync(resolvedDir)) return [];
const files = fs.readdirSync(resolvedDir);
const plugins: Plugin[] = [];
for (const file of files) {
const full = path.join(resolvedDir, file);
const stat = fs.statSync(full);
if (stat.isFile()) {
const plugin = loadPluginSync(full);
if (plugin) plugins.push(plugin);
}
}
return plugins;
}
8 changes: 8 additions & 0 deletions tests/fixtures/example-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
default: {
name: 'example-plugin',
setup(runner) {
runner.exampleInitialized = true;
},
},
};
8 changes: 8 additions & 0 deletions tests/fixtures/plugins/dir-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
default: {
name: 'dir-plugin',
setup(runner) {
runner.dirPluginLoaded = true;
},
},
};
33 changes: 33 additions & 0 deletions tests/plugins.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import path from 'node:path';
import { Runner } from '../src/index';
import { Plugin } from '../src/plugins';

describe('Plugin system', () => {
it('registers plugin objects', () => {
const plugin: Plugin = {
name: 'obj',
setup(r) {
(r as any).objLoaded = true;

Check warning on line 10 in tests/plugins.test.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Unexpected any. Specify a different type
},
};

const runner = new Runner(1, 10, undefined, [plugin]);
expect(runner.getPlugins().some((p) => p.name === 'obj')).toBe(true);
// setup should have run
expect((runner as any).objLoaded).toBe(true);

Check warning on line 17 in tests/plugins.test.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Unexpected any. Specify a different type
});

it('loads plugins from file paths', () => {
const file = path.join(__dirname, 'fixtures', 'example-plugin.js');
const runner = new Runner(1, 10, undefined, [file]);
expect(runner.getPlugins().some((p) => p.name === 'example-plugin')).toBe(true);
expect((runner as any).exampleInitialized).toBe(true);

Check warning on line 24 in tests/plugins.test.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Unexpected any. Specify a different type
});

it('loads plugins from directories', () => {
const dir = path.join(__dirname, 'fixtures', 'plugins');
const runner = new Runner(1, 10, undefined, [dir]);
expect(runner.getPlugins().some((p) => p.name === 'dir-plugin')).toBe(true);
expect((runner as any).dirPluginLoaded).toBe(true);

Check warning on line 31 in tests/plugins.test.ts

View workflow job for this annotation

GitHub Actions / build-and-test

Unexpected any. Specify a different type
});
});
Loading