File size: 6,422 Bytes
6111b2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | /**
* Plugin/Middleware Architecture β L-8
*
* Pre/post hooks on the request pipeline. Plugins are registered
* with a priority (lower = runs first) and can intercept requests
* before they reach the chat handler or modify responses after.
*
* Lifecycle:
* onRequest β runs BEFORE chat handler (can block/modify request)
* onResponse β runs AFTER chat handler (can modify/log response)
* onError β runs on handler errors (can recover or re-throw)
*
* @module lib/plugins
*/
// ββ Types ββ
import { logger } from "../../../open-sse/utils/logger.ts";
const log = logger("PLUGINS");
export interface PluginContext {
/** Unique request ID */
requestId: string;
/** Request body (parsed JSON) */
body: any;
/** Model string */
model: string;
/** Provider (if resolved) */
provider?: string;
/** API key info */
apiKeyInfo?: any;
/** Arbitrary metadata plugins can share */
metadata: Record<string, any>;
}
export interface PluginResult {
/** If true, stop processing further plugins and return immediately */
blocked?: boolean;
/** Optional response to return if blocked */
response?: any;
/** Modified body (if any) */
body?: any;
/** Modified metadata */
metadata?: Record<string, any>;
}
export interface Plugin {
/** Unique plugin name */
name: string;
/** Priority (lower = runs first, default 100) */
priority?: number;
/** Whether the plugin is enabled */
enabled?: boolean;
/** Called before the chat handler */
onRequest?: (ctx: PluginContext) => Promise<PluginResult | void> | PluginResult | void;
/** Called after the chat handler */
onResponse?: (ctx: PluginContext, response: any) => Promise<any | void> | any | void;
/** Called on handler error */
onError?: (ctx: PluginContext, error: Error) => Promise<any | void> | any | void;
}
// ββ Registry ββ
const _plugins: Plugin[] = [];
/**
* Register a plugin. Plugins are sorted by priority on each registration.
*/
export function registerPlugin(plugin: Plugin): void {
// Set defaults
plugin.priority = plugin.priority ?? 100;
plugin.enabled = plugin.enabled ?? true;
// Remove existing plugin with same name (re-registration)
const idx = _plugins.findIndex((p) => p.name === plugin.name);
if (idx !== -1) _plugins.splice(idx, 1);
_plugins.push(plugin);
_plugins.sort((a, b) => (a.priority || 100) - (b.priority || 100));
log.info("plugin.registered", {
name: plugin.name,
priority: plugin.priority,
enabled: plugin.enabled,
});
}
/**
* Unregister a plugin by name.
*/
export function unregisterPlugin(name: string): boolean {
const idx = _plugins.findIndex((p) => p.name === name);
if (idx === -1) return false;
_plugins.splice(idx, 1);
return true;
}
/**
* Enable/disable a plugin at runtime.
*/
export function setPluginEnabled(name: string, enabled: boolean): boolean {
const plugin = _plugins.find((p) => p.name === name);
if (!plugin) return false;
plugin.enabled = enabled;
return true;
}
/**
* List all registered plugins.
*/
export function listPlugins(): Array<{
name: string;
priority: number;
enabled: boolean;
hooks: string[];
}> {
return _plugins.map((p) => ({
name: p.name,
priority: p.priority || 100,
enabled: p.enabled !== false,
hooks: [
p.onRequest ? "onRequest" : "",
p.onResponse ? "onResponse" : "",
p.onError ? "onError" : "",
].filter(Boolean),
}));
}
// ββ Execution ββ
/**
* Run all onRequest hooks. Returns the (possibly modified) context,
* or a blocked response if any plugin blocked the request.
*/
export async function runOnRequest(
ctx: PluginContext
): Promise<{ blocked: boolean; response?: any; ctx: PluginContext }> {
let currentCtx = { ...ctx };
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onRequest) continue;
try {
const result = await plugin.onRequest(currentCtx);
if (result) {
if (result.blocked) {
log.info("plugin.request_blocked", { name: plugin.name });
return { blocked: true, response: result.response, ctx: currentCtx };
}
if (result.body) currentCtx.body = result.body;
if (result.metadata) {
currentCtx.metadata = { ...currentCtx.metadata, ...result.metadata };
}
}
} catch (err: any) {
log.error("plugin.onRequest_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
// Plugin errors don't block the pipeline by default
}
}
return { blocked: false, ctx: currentCtx };
}
/**
* Run all onResponse hooks. Returns the (possibly modified) response.
*/
export async function runOnResponse(ctx: PluginContext, response: any): Promise<any> {
let currentResponse = response;
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onResponse) continue;
try {
const modified = await plugin.onResponse(ctx, currentResponse);
if (modified !== undefined && modified !== null) {
currentResponse = modified;
}
} catch (err: any) {
log.error("plugin.onResponse_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
}
}
return currentResponse;
}
/**
* Run all onError hooks. Returns a recovery response if any plugin handles it,
* or null to let the error propagate.
*/
export async function runOnError(ctx: PluginContext, error: Error): Promise<any | null> {
for (const plugin of _plugins) {
if (!plugin.enabled || !plugin.onError) continue;
try {
const recovery = await plugin.onError(ctx, error);
if (recovery !== undefined && recovery !== null) {
log.info("plugin.error_recovered", { name: plugin.name });
return recovery;
}
} catch (err: any) {
log.error("plugin.onError_error", {
name: plugin.name,
error: err instanceof Error ? err.message : String(err),
});
}
}
return null; // No recovery β let error propagate
}
/**
* Reset all plugins (for testing).
*/
export function resetPlugins(): void {
_plugins.length = 0;
}
|