opc-agent 0.9.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,148 @@
1
+ /**
2
+ * OPC Agent Error Hierarchy - v1.0.0
3
+ * Custom error classes with user-friendly messages and recovery hints.
4
+ */
5
+
6
+ export class OPCError extends Error {
7
+ public readonly code: string;
8
+ public readonly hint?: string;
9
+ public readonly context?: Record<string, unknown>;
10
+ public readonly timestamp = Date.now();
11
+
12
+ constructor(message: string, opts?: { code?: string; hint?: string; context?: Record<string, unknown>; cause?: Error }) {
13
+ super(message);
14
+ this.name = 'OPCError';
15
+ this.code = opts?.code ?? 'OPC_UNKNOWN';
16
+ this.hint = opts?.hint;
17
+ this.context = opts?.context;
18
+ if (opts?.cause) this.cause = opts.cause;
19
+ }
20
+
21
+ toJSON(): Record<string, unknown> {
22
+ return { name: this.name, code: this.code, message: this.message, hint: this.hint, context: this.context, timestamp: this.timestamp };
23
+ }
24
+
25
+ toUserMessage(): string {
26
+ return this.hint ? `${this.message}\nšŸ’” ${this.hint}` : this.message;
27
+ }
28
+ }
29
+
30
+ export class ProviderError extends OPCError {
31
+ public readonly provider: string;
32
+ public readonly statusCode?: number;
33
+
34
+ constructor(provider: string, message: string, opts?: { statusCode?: number; hint?: string; cause?: Error }) {
35
+ super(message, {
36
+ code: 'OPC_PROVIDER_ERROR',
37
+ hint: opts?.hint ?? `Check your API key and network connection for ${provider}.`,
38
+ context: { provider, statusCode: opts?.statusCode },
39
+ cause: opts?.cause,
40
+ });
41
+ this.name = 'ProviderError';
42
+ this.provider = provider;
43
+ this.statusCode = opts?.statusCode;
44
+ }
45
+ }
46
+
47
+ export class ValidationError extends OPCError {
48
+ public readonly field?: string;
49
+ public readonly errors: string[];
50
+
51
+ constructor(message: string, errors: string[] = [], field?: string) {
52
+ super(message, {
53
+ code: 'OPC_VALIDATION_ERROR',
54
+ hint: 'Check your OAD configuration file for missing or invalid fields.',
55
+ context: { field, errors },
56
+ });
57
+ this.name = 'ValidationError';
58
+ this.field = field;
59
+ this.errors = errors;
60
+ }
61
+ }
62
+
63
+ export class ConfigError extends OPCError {
64
+ constructor(message: string, hint?: string) {
65
+ super(message, { code: 'OPC_CONFIG_ERROR', hint: hint ?? 'Check your oad.yaml and .env files.' });
66
+ this.name = 'ConfigError';
67
+ }
68
+ }
69
+
70
+ export class ChannelError extends OPCError {
71
+ public readonly channelType: string;
72
+
73
+ constructor(channelType: string, message: string, opts?: { hint?: string; cause?: Error }) {
74
+ super(message, {
75
+ code: 'OPC_CHANNEL_ERROR',
76
+ hint: opts?.hint ?? `Check configuration for the ${channelType} channel.`,
77
+ context: { channelType },
78
+ cause: opts?.cause,
79
+ });
80
+ this.name = 'ChannelError';
81
+ this.channelType = channelType;
82
+ }
83
+ }
84
+
85
+ export class PluginError extends OPCError {
86
+ public readonly pluginName: string;
87
+
88
+ constructor(pluginName: string, message: string, opts?: { hint?: string; cause?: Error }) {
89
+ super(message, {
90
+ code: 'OPC_PLUGIN_ERROR',
91
+ hint: opts?.hint ?? `Check plugin "${pluginName}" configuration.`,
92
+ context: { pluginName },
93
+ cause: opts?.cause,
94
+ });
95
+ this.name = 'PluginError';
96
+ this.pluginName = pluginName;
97
+ }
98
+ }
99
+
100
+ export class RateLimitError extends OPCError {
101
+ public readonly retryAfterMs?: number;
102
+
103
+ constructor(message?: string, retryAfterMs?: number) {
104
+ super(message ?? 'Rate limit exceeded. Please slow down.', {
105
+ code: 'OPC_RATE_LIMIT',
106
+ hint: retryAfterMs ? `Try again in ${Math.ceil(retryAfterMs / 1000)} seconds.` : 'Please wait before sending more messages.',
107
+ context: { retryAfterMs },
108
+ });
109
+ this.name = 'RateLimitError';
110
+ this.retryAfterMs = retryAfterMs;
111
+ }
112
+ }
113
+
114
+ export class SecurityError extends OPCError {
115
+ constructor(message: string, hint?: string) {
116
+ super(message, { code: 'OPC_SECURITY_ERROR', hint: hint ?? 'This request was blocked for security reasons.' });
117
+ this.name = 'SecurityError';
118
+ }
119
+ }
120
+
121
+ export class TimeoutError extends OPCError {
122
+ constructor(operation: string, timeoutMs: number) {
123
+ super(`Operation "${operation}" timed out after ${timeoutMs}ms`, {
124
+ code: 'OPC_TIMEOUT',
125
+ hint: 'The operation took too long. Try again or increase the timeout.',
126
+ context: { operation, timeoutMs },
127
+ });
128
+ this.name = 'TimeoutError';
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Wrap an unknown thrown value into an OPCError.
134
+ */
135
+ export function wrapError(err: unknown, fallbackMessage = 'An unexpected error occurred'): OPCError {
136
+ if (err instanceof OPCError) return err;
137
+ if (err instanceof Error) return new OPCError(err.message, { cause: err });
138
+ return new OPCError(typeof err === 'string' ? err : fallbackMessage);
139
+ }
140
+
141
+ /**
142
+ * Format error for user display (no stack traces).
143
+ */
144
+ export function formatErrorForUser(err: unknown): string {
145
+ if (err instanceof OPCError) return err.toUserMessage();
146
+ if (err instanceof Error) return err.message;
147
+ return String(err);
148
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Security Hardening Module - v1.0.0
3
+ * Input sanitization, CORS, security headers, API key rotation.
4
+ */
5
+
6
+ import type { Request, Response, NextFunction } from 'express';
7
+
8
+ // ── Input Sanitization ──────────────────────────────────────
9
+
10
+ const XSS_PATTERNS = [
11
+ /<script\b[^>]*>[\s\S]*?<\/script>/gi,
12
+ /javascript:/gi,
13
+ /on\w+\s*=/gi,
14
+ /<iframe\b/gi,
15
+ /<object\b/gi,
16
+ /<embed\b/gi,
17
+ /<form\b/gi,
18
+ ];
19
+
20
+ const SQL_PATTERNS = [
21
+ /(\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER|CREATE|EXEC)\b.*\b(FROM|INTO|TABLE|SET|WHERE|ALL)\b)/gi,
22
+ /(--|;)\s*(DROP|ALTER|DELETE)/gi,
23
+ ];
24
+
25
+ export function sanitizeInput(input: string): string {
26
+ let clean = input;
27
+ for (const pattern of XSS_PATTERNS) {
28
+ clean = clean.replace(pattern, '');
29
+ }
30
+ // Encode dangerous HTML entities
31
+ clean = clean.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
32
+ return clean;
33
+ }
34
+
35
+ export function detectInjection(input: string): { safe: boolean; threats: string[] } {
36
+ const threats: string[] = [];
37
+ for (const pattern of XSS_PATTERNS) {
38
+ if (pattern.test(input)) threats.push('xss');
39
+ pattern.lastIndex = 0;
40
+ }
41
+ for (const pattern of SQL_PATTERNS) {
42
+ if (pattern.test(input)) threats.push('sql_injection');
43
+ pattern.lastIndex = 0;
44
+ }
45
+ return { safe: threats.length === 0, threats: [...new Set(threats)] };
46
+ }
47
+
48
+ // ── Security Headers (Helmet-style) ────────────────────────
49
+
50
+ export interface SecurityHeadersConfig {
51
+ contentSecurityPolicy?: string;
52
+ enableHSTS?: boolean;
53
+ frameDeny?: boolean;
54
+ xssProtection?: boolean;
55
+ noSniff?: boolean;
56
+ referrerPolicy?: string;
57
+ }
58
+
59
+ export function securityHeaders(config?: SecurityHeadersConfig) {
60
+ const csp = config?.contentSecurityPolicy ?? "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'";
61
+ return (_req: Request, res: Response, next: NextFunction): void => {
62
+ res.setHeader('Content-Security-Policy', csp);
63
+ res.setHeader('X-Content-Type-Options', 'nosniff');
64
+ res.setHeader('X-Frame-Options', config?.frameDeny !== false ? 'DENY' : 'SAMEORIGIN');
65
+ res.setHeader('X-XSS-Protection', '1; mode=block');
66
+ res.setHeader('Referrer-Policy', config?.referrerPolicy ?? 'strict-origin-when-cross-origin');
67
+ if (config?.enableHSTS !== false) {
68
+ res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
69
+ }
70
+ res.removeHeader('X-Powered-By');
71
+ next();
72
+ };
73
+ }
74
+
75
+ // ── CORS Configuration ──────────────────────────────────────
76
+
77
+ export interface CORSConfig {
78
+ origins?: string[];
79
+ methods?: string[];
80
+ allowHeaders?: string[];
81
+ credentials?: boolean;
82
+ maxAge?: number;
83
+ }
84
+
85
+ export function corsMiddleware(config?: CORSConfig) {
86
+ const origins = config?.origins ?? ['*'];
87
+ const methods = config?.methods ?? ['GET', 'POST', 'OPTIONS'];
88
+ const headers = config?.allowHeaders ?? ['Content-Type', 'Authorization'];
89
+
90
+ return (req: Request, res: Response, next: NextFunction): void => {
91
+ const origin = req.headers.origin ?? '';
92
+ if (origins.includes('*') || origins.includes(origin)) {
93
+ res.setHeader('Access-Control-Allow-Origin', origins.includes('*') ? '*' : origin);
94
+ }
95
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
96
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
97
+ if (config?.credentials) res.setHeader('Access-Control-Allow-Credentials', 'true');
98
+ if (config?.maxAge) res.setHeader('Access-Control-Max-Age', String(config.maxAge));
99
+ if (req.method === 'OPTIONS') { res.status(204).end(); return; }
100
+ next();
101
+ };
102
+ }
103
+
104
+ // ── API Key Rotation ────────────────────────────────────────
105
+
106
+ export interface APIKeyEntry {
107
+ key: string;
108
+ label?: string;
109
+ createdAt: number;
110
+ expiresAt?: number;
111
+ active: boolean;
112
+ }
113
+
114
+ export class APIKeyManager {
115
+ private keys: APIKeyEntry[] = [];
116
+
117
+ addKey(key: string, opts?: { label?: string; expiresAt?: number }): void {
118
+ this.keys.push({ key, label: opts?.label, createdAt: Date.now(), expiresAt: opts?.expiresAt, active: true });
119
+ }
120
+
121
+ revokeKey(key: string): boolean {
122
+ const entry = this.keys.find(k => k.key === key);
123
+ if (entry) { entry.active = false; return true; }
124
+ return false;
125
+ }
126
+
127
+ isValid(key: string): boolean {
128
+ const entry = this.keys.find(k => k.key === key);
129
+ if (!entry || !entry.active) return false;
130
+ if (entry.expiresAt && Date.now() > entry.expiresAt) { entry.active = false; return false; }
131
+ return true;
132
+ }
133
+
134
+ rotateKey(oldKey: string, newKey: string): boolean {
135
+ const entry = this.keys.find(k => k.key === oldKey && k.active);
136
+ if (!entry) return false;
137
+ entry.active = false;
138
+ this.addKey(newKey, { label: entry.label });
139
+ return true;
140
+ }
141
+
142
+ listActive(): APIKeyEntry[] {
143
+ return this.keys.filter(k => k.active && (!k.expiresAt || Date.now() <= k.expiresAt));
144
+ }
145
+
146
+ cleanup(): number {
147
+ const before = this.keys.length;
148
+ this.keys = this.keys.filter(k => k.active && (!k.expiresAt || Date.now() <= k.expiresAt));
149
+ return before - this.keys.length;
150
+ }
151
+ }
152
+
153
+ // ── Input Validation Middleware ──────────────────────────────
154
+
155
+ export function inputValidation() {
156
+ return (req: Request, res: Response, next: NextFunction): void => {
157
+ if (req.body?.message && typeof req.body.message === 'string') {
158
+ const check = detectInjection(req.body.message);
159
+ if (!check.safe) {
160
+ res.status(400).json({ error: 'Input contains potentially unsafe content', threats: check.threats });
161
+ return;
162
+ }
163
+ // Limit message size
164
+ if (req.body.message.length > 100_000) {
165
+ res.status(413).json({ error: 'Message too large (max 100KB)' });
166
+ return;
167
+ }
168
+ }
169
+ next();
170
+ };
171
+ }
@@ -0,0 +1,178 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ /**
4
+ * ProcessWatcher — Background process output monitoring with pattern matching.
5
+ *
6
+ * Inspired by Hermes Agent's watch_patterns feature.
7
+ * Set patterns to watch for in background process output and get callbacks
8
+ * when they match — no polling needed.
9
+ *
10
+ * Usage:
11
+ * const watcher = new ProcessWatcher();
12
+ * watcher.watch(childProcess.stdout, {
13
+ * patterns: [
14
+ * { regex: /listening on port (\d+)/, label: 'server-ready' },
15
+ * { regex: /error|Error|ERROR/, label: 'error-detected' },
16
+ * { regex: /build completed/, label: 'build-done', once: true },
17
+ * ],
18
+ * onMatch: (match) => console.log(`[${match.label}] ${match.line}`),
19
+ * });
20
+ */
21
+
22
+ export interface WatchPattern {
23
+ /** Regex to match against each line of output */
24
+ regex: RegExp;
25
+ /** Human-readable label for this pattern */
26
+ label: string;
27
+ /** If true, auto-remove after first match */
28
+ once?: boolean;
29
+ }
30
+
31
+ export interface WatchMatch {
32
+ /** Pattern label */
33
+ label: string;
34
+ /** The full line that matched */
35
+ line: string;
36
+ /** Regex match groups */
37
+ groups: string[];
38
+ /** Timestamp of match */
39
+ timestamp: number;
40
+ /** Stream source */
41
+ stream: 'stdout' | 'stderr';
42
+ }
43
+
44
+ export interface WatchOptions {
45
+ /** Patterns to match */
46
+ patterns: WatchPattern[];
47
+ /** Callback on match */
48
+ onMatch: (match: WatchMatch) => void;
49
+ /** Optional: max matches to keep in history (default: 100) */
50
+ maxHistory?: number;
51
+ }
52
+
53
+ export class ProcessWatcher extends EventEmitter {
54
+ private watchers = new Map<string, {
55
+ patterns: WatchPattern[];
56
+ onMatch: (match: WatchMatch) => void;
57
+ history: WatchMatch[];
58
+ maxHistory: number;
59
+ }>();
60
+
61
+ private watcherIdCounter = 0;
62
+
63
+ /**
64
+ * Start watching a readable stream for patterns.
65
+ * Returns a watcher ID that can be used to stop watching.
66
+ */
67
+ watch(
68
+ stream: NodeJS.ReadableStream,
69
+ options: WatchOptions,
70
+ streamName: 'stdout' | 'stderr' = 'stdout',
71
+ ): string {
72
+ const id = `watcher_${++this.watcherIdCounter}`;
73
+ const state = {
74
+ patterns: [...options.patterns],
75
+ onMatch: options.onMatch,
76
+ history: [] as WatchMatch[],
77
+ maxHistory: options.maxHistory ?? 100,
78
+ };
79
+ this.watchers.set(id, state);
80
+
81
+ let buffer = '';
82
+
83
+ const onData = (chunk: Buffer | string) => {
84
+ buffer += chunk.toString();
85
+ const lines = buffer.split('\n');
86
+ buffer = lines.pop() ?? ''; // Keep incomplete line in buffer
87
+
88
+ for (const line of lines) {
89
+ this.matchLine(id, line, streamName);
90
+ }
91
+ };
92
+
93
+ stream.on('data', onData);
94
+ stream.on('end', () => {
95
+ // Process remaining buffer
96
+ if (buffer) this.matchLine(id, buffer, streamName);
97
+ this.watchers.delete(id);
98
+ this.emit('watcher:end', id);
99
+ });
100
+
101
+ return id;
102
+ }
103
+
104
+ /**
105
+ * Watch both stdout and stderr of a ChildProcess.
106
+ */
107
+ watchProcess(
108
+ proc: { stdout?: NodeJS.ReadableStream | null; stderr?: NodeJS.ReadableStream | null },
109
+ options: WatchOptions,
110
+ ): string[] {
111
+ const ids: string[] = [];
112
+ if (proc.stdout) ids.push(this.watch(proc.stdout, options, 'stdout'));
113
+ if (proc.stderr) ids.push(this.watch(proc.stderr, options, 'stderr'));
114
+ return ids;
115
+ }
116
+
117
+ /** Stop a specific watcher */
118
+ unwatch(id: string): void {
119
+ this.watchers.delete(id);
120
+ }
121
+
122
+ /** Get match history for a watcher */
123
+ getHistory(id: string): WatchMatch[] {
124
+ return this.watchers.get(id)?.history ?? [];
125
+ }
126
+
127
+ /** Add a pattern to an existing watcher */
128
+ addPattern(id: string, pattern: WatchPattern): void {
129
+ const state = this.watchers.get(id);
130
+ if (state) state.patterns.push(pattern);
131
+ }
132
+
133
+ /** Remove a pattern by label from a watcher */
134
+ removePattern(id: string, label: string): void {
135
+ const state = this.watchers.get(id);
136
+ if (state) {
137
+ state.patterns = state.patterns.filter(p => p.label !== label);
138
+ }
139
+ }
140
+
141
+ private matchLine(watcherId: string, line: string, stream: 'stdout' | 'stderr'): void {
142
+ const state = this.watchers.get(watcherId);
143
+ if (!state) return;
144
+
145
+ const toRemove: number[] = [];
146
+
147
+ for (let i = 0; i < state.patterns.length; i++) {
148
+ const pattern = state.patterns[i];
149
+ const m = line.match(pattern.regex);
150
+ if (m) {
151
+ const match: WatchMatch = {
152
+ label: pattern.label,
153
+ line,
154
+ groups: m.slice(1),
155
+ timestamp: Date.now(),
156
+ stream,
157
+ };
158
+
159
+ state.history.push(match);
160
+ if (state.history.length > state.maxHistory) {
161
+ state.history.shift();
162
+ }
163
+
164
+ state.onMatch(match);
165
+ this.emit('match', match);
166
+
167
+ if (pattern.once) {
168
+ toRemove.push(i);
169
+ }
170
+ }
171
+ }
172
+
173
+ // Remove once-patterns in reverse order
174
+ for (let i = toRemove.length - 1; i >= 0; i--) {
175
+ state.patterns.splice(toRemove[i], 1);
176
+ }
177
+ }
178
+ }
package/src/index.ts CHANGED
@@ -93,3 +93,18 @@ export type { CacheConfig, CacheEntry } from './core/cache';
93
93
  export { getSupportedLocales } from './i18n';
94
94
  export { createDataAnalystConfig } from './templates/data-analyst';
95
95
  export { createTeacherConfig } from './templates/teacher';
96
+
97
+ // v1.0.0 modules
98
+ export { OPCError, ProviderError, ValidationError, ConfigError, ChannelError, PluginError, RateLimitError, SecurityError, TimeoutError, wrapError, formatErrorForUser } from './core/errors';
99
+ export { sanitizeInput, detectInjection, securityHeaders, corsMiddleware, APIKeyManager, inputValidation } from './core/security';
100
+ export type { SecurityHeadersConfig, CORSConfig, APIKeyEntry } from './core/security';
101
+ export { createLoggingPlugin, createAnalyticsPlugin, createRateLimitPlugin } from './plugins';
102
+ export type { PluginManifest } from './plugins';
103
+
104
+ // v1.1.0 modules
105
+ export { FeishuChannel } from './channels/feishu';
106
+ export type { FeishuChannelConfig } from './channels/feishu';
107
+ export { DiscordChannel } from './channels/discord';
108
+ export type { DiscordChannelConfig } from './channels/discord';
109
+ export { ProcessWatcher } from './core/watch';
110
+ export type { WatchPattern, WatchMatch, WatchOptions } from './core/watch';
@@ -1,10 +1,17 @@
1
- import type { ISkill, IChannel } from '../core/types';
1
+ import type { ISkill, IChannel, Message } from '../core/types';
2
2
  import type { MCPTool } from '../tools/mcp';
3
+ import { Logger } from '../core/logger';
3
4
 
4
5
  /**
5
- * Plugin lifecycle hooks.
6
+ * Plugin lifecycle hooks - v1.0.0
6
7
  */
7
8
  export interface PluginHooks {
9
+ onInit?: () => Promise<void>;
10
+ onMessage?: (message: Message) => Promise<Message | void>;
11
+ onResponse?: (message: Message, response: Message) => Promise<Message | void>;
12
+ onError?: (error: Error, context?: Record<string, unknown>) => Promise<void>;
13
+ onShutdown?: () => Promise<void>;
14
+ // Legacy aliases
8
15
  beforeInit?: () => Promise<void>;
9
16
  afterInit?: () => Promise<void>;
10
17
  beforeMessage?: (message: { content: string }) => Promise<void>;
@@ -13,7 +20,15 @@ export interface PluginHooks {
13
20
  }
14
21
 
15
22
  /**
16
- * Plugin interface — extend agent with skills, tools, channels, and lifecycle hooks.
23
+ * Plugin manifest in OAD: plugins: [{ name, config }]
24
+ */
25
+ export interface PluginManifest {
26
+ name: string;
27
+ config?: Record<string, unknown>;
28
+ }
29
+
30
+ /**
31
+ * Plugin interface - extend agent with skills, tools, channels, and lifecycle hooks.
17
32
  */
18
33
  export interface IPlugin {
19
34
  name: string;
@@ -27,9 +42,14 @@ export interface IPlugin {
27
42
 
28
43
  export class PluginManager {
29
44
  private plugins: Map<string, IPlugin> = new Map();
45
+ private logger = new Logger('plugins');
30
46
 
31
47
  register(plugin: IPlugin): void {
48
+ if (this.plugins.has(plugin.name)) {
49
+ this.logger.warn(`Plugin "${plugin.name}" already registered, replacing`);
50
+ }
32
51
  this.plugins.set(plugin.name, plugin);
52
+ this.logger.info(`Plugin registered: ${plugin.name}@${plugin.version}`);
33
53
  }
34
54
 
35
55
  unregister(name: string): void {
@@ -42,9 +62,7 @@ export class PluginManager {
42
62
 
43
63
  list(): { name: string; version: string; description?: string }[] {
44
64
  return Array.from(this.plugins.values()).map(({ name, version, description }) => ({
45
- name,
46
- version,
47
- description,
65
+ name, version, description,
48
66
  }));
49
67
  }
50
68
 
@@ -56,9 +74,59 @@ export class PluginManager {
56
74
  for (const plugin of this.plugins.values()) {
57
75
  const hook = plugin.hooks?.[hookName];
58
76
  if (hook) {
59
- await (hook as (...a: unknown[]) => Promise<void>)(...args);
77
+ try {
78
+ await (hook as (...a: unknown[]) => Promise<void>)(...args);
79
+ } catch (err) {
80
+ this.logger.error(`Plugin "${plugin.name}" hook "${hookName}" failed`, {
81
+ error: err instanceof Error ? err.message : String(err),
82
+ });
83
+ // Don't let one plugin break others
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ async runOnInit(): Promise<void> {
90
+ await this.runHook('onInit');
91
+ await this.runHook('beforeInit');
92
+ await this.runHook('afterInit');
93
+ }
94
+
95
+ async runOnMessage(message: Message): Promise<Message> {
96
+ let msg = message;
97
+ for (const plugin of this.plugins.values()) {
98
+ if (plugin.hooks?.onMessage) {
99
+ const result = await plugin.hooks.onMessage(msg);
100
+ if (result) msg = result;
101
+ }
102
+ if (plugin.hooks?.beforeMessage) {
103
+ await plugin.hooks.beforeMessage({ content: msg.content });
60
104
  }
61
105
  }
106
+ return msg;
107
+ }
108
+
109
+ async runOnResponse(message: Message, response: Message): Promise<Message> {
110
+ let resp = response;
111
+ for (const plugin of this.plugins.values()) {
112
+ if (plugin.hooks?.onResponse) {
113
+ const result = await plugin.hooks.onResponse(message, resp);
114
+ if (result) resp = result;
115
+ }
116
+ if (plugin.hooks?.afterMessage) {
117
+ await plugin.hooks.afterMessage({ content: message.content }, { content: resp.content });
118
+ }
119
+ }
120
+ return resp;
121
+ }
122
+
123
+ async runOnError(error: Error, context?: Record<string, unknown>): Promise<void> {
124
+ await this.runHook('onError', error, context);
125
+ }
126
+
127
+ async runOnShutdown(): Promise<void> {
128
+ await this.runHook('onShutdown');
129
+ await this.runHook('beforeShutdown');
62
130
  }
63
131
 
64
132
  getAllSkills(): ISkill[] {
@@ -85,3 +153,56 @@ export class PluginManager {
85
153
  return channels;
86
154
  }
87
155
  }
156
+
157
+ // ── Built-in Plugins ────────────────────────────────────────
158
+
159
+ export function createLoggingPlugin(): IPlugin {
160
+ const logger = new Logger('agent:messages');
161
+ return {
162
+ name: 'logging',
163
+ version: '1.0.0',
164
+ description: 'Logs all messages and responses',
165
+ hooks: {
166
+ onInit: async () => { logger.info('Agent initialized'); },
167
+ onMessage: async (msg: Message) => { logger.info(`← ${msg.role}: ${msg.content.slice(0, 100)}`); return undefined as any; },
168
+ onResponse: async (_msg: Message, resp: Message) => { logger.info(`→ ${resp.role}: ${resp.content.slice(0, 100)}`); return undefined as any; },
169
+ onError: async (err: Error) => { logger.error(`Error: ${err.message}`); },
170
+ onShutdown: async () => { logger.info('Agent shutting down'); },
171
+ },
172
+ };
173
+ }
174
+
175
+ export function createAnalyticsPlugin(): IPlugin {
176
+ const stats = { messages: 0, errors: 0, startedAt: 0 };
177
+ return {
178
+ name: 'analytics',
179
+ version: '1.0.0',
180
+ description: 'Tracks message counts and error rates',
181
+ hooks: {
182
+ onInit: async () => { stats.startedAt = Date.now(); },
183
+ onMessage: async () => { stats.messages++; return undefined as any; },
184
+ onError: async () => { stats.errors++; },
185
+ },
186
+ };
187
+ }
188
+
189
+ export function createRateLimitPlugin(maxPerMinute = 60): IPlugin {
190
+ const timestamps: number[] = [];
191
+ return {
192
+ name: 'rate-limit',
193
+ version: '1.0.0',
194
+ description: `Rate limits to ${maxPerMinute} messages/minute`,
195
+ hooks: {
196
+ onMessage: async () => {
197
+ const now = Date.now();
198
+ const windowStart = now - 60_000;
199
+ while (timestamps.length > 0 && timestamps[0] < windowStart) timestamps.shift();
200
+ if (timestamps.length >= maxPerMinute) {
201
+ throw new Error('Rate limit exceeded. Please slow down.');
202
+ }
203
+ timestamps.push(now);
204
+ return undefined as any;
205
+ },
206
+ },
207
+ };
208
+ }