GeminiRevolver/test-filters.ts
tyuXX 26341533ed feat: add input & output text processing filters, triggers, and /admin/filters page
- Implement FilterEngine supporting literal word replacement, interactive regex matching, instruction injection, and sandboxed JS scripts (vm)
- Add conditional triggers (AND/OR, text contains, regex match, length threshold, conversation state)
- Support arbitrary per-model execution ordering and global filter pipelines
- Add smart SSE streaming mode with keep-alive buffering and chunk-by-chunk processing
- Integrate filter execution step traces into liveWatcher and Admin Playground
- Add dedicated /admin/filters page with visual regex assistant, live regex match preview, model pipeline orchestrator, and dry-run sandbox
- Add automated end-to-end filter test suite in test-filters.ts
2026-11-06 21:04:01 +00:00

510 lines
20 KiB
TypeScript

process.env.API_PASSWORD = process.env.API_PASSWORD || 'test-password';
import fs from 'fs';
import path from 'path';
import http from 'http';
import express from 'express';
import assert from 'assert';
import { ConfigStore } from './src/configStore';
import { FilterEngine } from './src/filterEngine';
import { RevolverEngine } from './src/revolverEngine';
import { renderFiltersPage } from './src/adminView';
import adminRoutes from './src/adminRoutes';
async function runFilterTests() {
console.log('🧪 Starting Text Post-Processing Filters & Pipeline Test Suite...\n');
const testConfigPath = path.join(__dirname, 'data', 'test-filters-config.json');
if (fs.existsSync(testConfigPath)) {
fs.unlinkSync(testConfigPath);
}
try {
const store = new ConfigStore(testConfigPath);
const filterEngine = new FilterEngine(store);
// 1. Test Filter CRUD & Model Assignment in ConfigStore
console.log('1. Testing Filter CRUD, Global flags, and Model Pipeline Ordering...');
const mockProvider = store.saveProvider({
name: 'Mock OpenAI Upstream',
type: 'openai',
baseUrl: 'http://127.0.0.1:19876/v1',
keys: ['sk-test-key-1234567890']
});
const modelA = store.saveCustomModel({
name: 'agent-alpha',
description: 'Alpha model with custom filter pipeline',
isDefault: true,
tiers: [{ tierIndex: 0, name: 'Main Tier', targets: [{ providerId: mockProvider.id, model: 'gpt-4o-mini' }] }]
});
const modelB = store.saveCustomModel({
name: 'agent-beta',
description: 'Beta model without model-specific filters',
isDefault: false,
tiers: [{ tierIndex: 0, name: 'Main Tier', targets: [{ providerId: mockProvider.id, model: 'gpt-4o-mini' }] }]
});
// Filter 1: Literal Word/Text Replacement (Input & Output)
const fLiteral = store.saveFilter({
name: 'Brand & Terminology Replacer',
direction: 'both',
inputTarget: 'last_user',
type: 'literal_replace',
literalConfig: {
caseSensitive: false,
wholeWord: true,
rules: [
{ find: 'badword', replace: '[censored]' },
{ find: ' AcmeCorp ', replace: ' ZenithAI ' },
{ find: 'secretcode', replace: 'REDACTED_CODE' }
]
},
triggers: { matchMode: 'all', rules: [{ type: 'always' }] },
assignedModelIds: [modelA.id]
});
// Filter 2: Regex Filter (Strip <think>...</think> blocks on Output)
const fRegexThink = store.saveFilter({
name: 'Strip Think Reasoning Tags',
direction: 'output',
streamMode: 'buffer_full',
type: 'regex_replace',
regexConfig: {
pattern: '<think(?:ing)?>[\\s\\S]*?<\\/think(?:ing)?>\\s*',
flags: 'gi',
replacement: ''
},
triggers: {
matchMode: 'all',
rules: [{ type: 'regex_match', value: '<think', flags: 'i' }]
},
assignedModelIds: [modelA.id]
});
// Filter 3: Instruction Injection (Prepend System Prompt when no system prompt is present)
const fSysInject = store.saveFilter({
name: 'Auto System Prompt Injector',
direction: 'input',
inputTarget: 'system',
type: 'instruction_inject',
instructionConfig: {
position: 'prepend_system',
content: 'You are {{model}}, a helpful assistant.',
separator: '\n\n'
},
triggers: {
matchMode: 'all',
rules: [{ type: 'no_system_prompt' }]
},
assignedModelIds: [modelA.id]
});
// Filter 4: Dynamic JS Script (Sandboxed vm)
const fScript = store.saveFilter({
name: 'Custom JS Tag Formatter',
direction: 'output',
type: 'custom_script',
scriptConfig: {
code: `
if (text.includes('HIGH_PRIORITY')) {
return '[ALERT] ' + replaceAll(text, 'HIGH_PRIORITY', 'URGENT') + ' [/ALERT]';
}
return text + ' (verified by ' + context.model + ')';
`,
timeoutMs: 500
},
triggers: {
matchMode: 'any',
rules: [
{ type: 'contains', value: 'HIGH_PRIORITY' },
{ type: 'length_gt', value: '5' }
]
},
assignedModelIds: [modelA.id]
});
// Filter 5: Global Output Filter
const fGlobal = store.saveFilter({
name: 'Global Boilerplate Remover',
isGlobal: true,
direction: 'output',
type: 'regex_replace',
regexConfig: {
pattern: '^As an AI assistant,\\s*',
flags: 'i',
replacement: ''
},
triggers: { matchMode: 'all', rules: [{ type: 'always' }] }
});
assert.strictEqual(store.getFilters().length, 5, 'Should have 5 saved filters');
const updatedModelA = store.getCustomModelById(modelA.id)!;
assert.deepStrictEqual(updatedModelA.filterIds, [
fLiteral.id,
fRegexThink.id,
fSysInject.id,
fScript.id
]);
console.log(' ✓ Filter creation, model binding, and global filter config verified.');
// 2. Test Input Filter Pipeline & Conditional Triggers
console.log('\n2. Testing Input Filter Pipeline & Trigger Evaluation...');
const inputRun1 = filterEngine.applyInputFilters({
messages: [{ role: 'user', content: 'Hello, can you check secretcode and badword for me?' }],
customModel: updatedModelA
});
assert.strictEqual(inputRun1.modified, true, 'Input should be modified');
assert.strictEqual(inputRun1.messages.length, 2, 'System message should have been injected by fSysInject');
assert.strictEqual(inputRun1.messages[0].role, 'system');
assert.strictEqual(inputRun1.messages[0].content, 'You are agent-alpha, a helpful assistant.');
assert.strictEqual(
inputRun1.messages[1].content,
'Hello, can you check REDACTED_CODE and [censored] for me?',
'Whole-word literal replacements should have been applied to user message'
);
// Verify whole-word boundary: "badword_extra" should NOT be replaced when wholeWord=true
const inputRunWholeWord = filterEngine.applyInputFilters({
messages: [
{ role: 'system', content: 'Existing system prompt' },
{ role: 'user', content: 'Testing badword_extra vs badword!' }
],
customModel: updatedModelA
});
assert.strictEqual(inputRunWholeWord.messages.length, 2, 'Should not add duplicate system message');
assert.strictEqual(inputRunWholeWord.messages[0].content, 'Existing system prompt', 'fSysInject trigger (no_system_prompt) should skip when system prompt exists');
assert.strictEqual(inputRunWholeWord.messages[1].content, 'Testing badword_extra vs [censored]!');
// Verify multimodal array content handling (preserves image_url while transforming text)
const multimodalRun = filterEngine.applyInputFilters({
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Please analyze secretcode' },
{ type: 'image_url', image_url: { url: 'https://example.com/chart.png' } }
] as any
}
],
customModel: updatedModelA
});
assert.strictEqual(multimodalRun.messages.length, 2);
const userContent = (multimodalRun.messages[1].content as unknown) as any[];
assert.ok(Array.isArray(userContent), 'Multimodal content array must be preserved');
assert.strictEqual(userContent[0].text, 'Please analyze REDACTED_CODE', 'Text part should be transformed');
assert.strictEqual(userContent[1].type, 'image_url', 'Non-text part should be untouched');
// Verify multiple user messages with system prepending (checks array shifting logic)
const multiUserRun = filterEngine.applyInputFilters({
messages: [
{ role: 'user', content: 'First message badword' },
{ role: 'assistant', content: 'Acknowledge' },
{ role: 'user', content: 'Second message secretcode' }
],
customModel: updatedModelA,
filtersOverride: [
store.saveFilter({
name: 'All User Replacer',
direction: 'input',
inputTarget: 'all_user',
type: 'literal_replace',
literalConfig: {
rules: [
{ find: 'badword', replace: '[clean1]' },
{ find: 'secretcode', replace: '[clean2]' }
]
},
triggers: { matchMode: 'all', rules: [{ type: 'always' }] }
}),
fSysInject
]
});
assert.strictEqual(multiUserRun.messages.length, 4, 'System prompt + 3 conversation messages');
assert.strictEqual(multiUserRun.messages[0].role, 'system');
assert.strictEqual(multiUserRun.messages[1].content, 'First message [clean1]');
assert.strictEqual(multiUserRun.messages[2].content, 'Acknowledge');
assert.strictEqual(multiUserRun.messages[3].content, 'Second message [clean2]');
console.log(' ✓ Input filters, whole-word boundaries, multimodal preservation, and array offsets verified.');
// 3. Test Output Filter Pipeline & Custom Execution Order
console.log('\n3. Testing Output Filter Pipeline & Custom Reordering...');
const rawOutput = '<think>\nThinking about secretcode...\n</think>\nAs an AI assistant, here is your secretcode result.';
// Notice: if fGlobal runs BEFORE fRegexThink, '^As an AI assistant,' wouldn't match at start of string because '<think>...' is at the start!
// But in modelA's resolved pipeline: [fLiteral, fRegexThink, fScript, fGlobal] -> fRegexThink strips <think> first, then fScript appends '(verified by agent-alpha)', then fGlobal strips '^As an AI assistant, '!
const outputRun1 = filterEngine.applyOutputFilters({
text: rawOutput,
customModel: updatedModelA
});
assert.strictEqual(
outputRun1.text,
'here is your REDACTED_CODE result. (verified by agent-alpha)',
'Output pipeline should strip <think>, replace secretcode, run script, and strip leading AI disclaimer'
);
// Now test reversing the order on modelA: put fScript BEFORE fLiteral
store.updateModelFilterPipeline(modelA.id, [fRegexThink.id, fGlobal.id, fScript.id, fLiteral.id], false);
const reorderedModelA = store.getCustomModelById(modelA.id)!;
const outputRunReordered = filterEngine.applyOutputFilters({
text: '<think>reasoning</think>\nAs an AI assistant, HIGH_PRIORITY notice for badword',
customModel: reorderedModelA
});
assert.strictEqual(
outputRunReordered.text,
'[ALERT] URGENT notice for [censored] [/ALERT]',
'Reordered pipeline should execute in exact new sequence'
);
console.log(' ✓ Output filter pipeline and dynamic per-model reordering verified.');
// 4. Test Sandboxed JS Script Timeout Protection
console.log('\n4. Testing Sandboxed JS Script Timeout Protection...');
const fInfiniteLoop = store.saveFilter({
name: 'Infinite Loop Script',
direction: 'output',
type: 'custom_script',
scriptConfig: {
code: 'while (true) {} return text;',
timeoutMs: 80
}
});
const loopRes = filterEngine.applyOutputFilters({
text: 'Safe fallback text',
customModel: reorderedModelA,
filtersOverride: [fInfiniteLoop]
});
assert.strictEqual(loopRes.text, 'Safe fallback text', 'Original text should be preserved when script times out');
assert.ok(loopRes.traces[0].error, 'Error trace should record script timeout');
store.deleteFilter(fInfiniteLoop.id);
console.log(' ✓ VM sandbox timeout protection verified (' + loopRes.traces[0].error + ').');
// 5. Test End-to-End RevolverEngine Non-Streaming & SSE Streaming with Mock Upstream Server
console.log('\n5. Testing End-to-End RevolverEngine (Non-Streaming & SSE Streaming with Output Filters)...');
let lastReceivedUpstreamBody: any = null;
const upstreamApp = express();
upstreamApp.use(express.json());
upstreamApp.post('/v1/chat/completions', (req, res) => {
lastReceivedUpstreamBody = req.body;
if (req.body.stream) {
res.setHeader('Content-Type', 'text/event-stream');
res.flushHeaders();
// Deliberately split <think>...</think> across multiple SSE chunks!
const chunks = [
'<thi',
'nk>\nMulti-chunk internal reasoning...\n</th',
'ink>\nAs an AI assistant, ',
'hello from badword stream!'
];
let i = 0;
const timer = setInterval(() => {
if (i < chunks.length) {
res.write(`data: ${JSON.stringify({
id: 'chatcmpl-stream-1',
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [{ index: 0, delta: { content: chunks[i] }, finish_reason: null }]
})}\n\n`);
i++;
} else {
clearInterval(timer);
res.write(`data: ${JSON.stringify({
id: 'chatcmpl-stream-1',
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }]
})}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
}, 15);
} else {
res.json({
id: 'chatcmpl-nonstream-1',
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [
{
index: 0,
message: {
role: 'assistant',
content: '<think>Hidden thought</think>\nAs an AI assistant, response for secretcode.'
},
finish_reason: 'stop'
}
],
usage: { prompt_tokens: 12, completion_tokens: 10, total_tokens: 22 }
});
}
});
const upstreamServer = await new Promise<http.Server>((resolve) => {
const srv = upstreamApp.listen(19876, '127.0.0.1', () => resolve(srv));
});
try {
// Configure modelA with [fSysInject, fLiteral, fRegexThink, fGlobal, fScript]
store.updateModelFilterPipeline(
modelA.id,
[fSysInject.id, fLiteral.id, fRegexThink.id, fGlobal.id, fScript.id],
false
);
const engine = new RevolverEngine(store);
// 5a: Test executeTestPrompt (Admin Playground runner)
const playgroundRes = await engine.executeTestPrompt({
customModelId: modelA.id,
prompt: 'Check secretcode please'
});
assert.strictEqual(lastReceivedUpstreamBody.messages.length, 2, 'Upstream should receive injected system message');
assert.strictEqual(lastReceivedUpstreamBody.messages[1].content, 'Check REDACTED_CODE please', 'Upstream should receive filtered user prompt');
assert.strictEqual(playgroundRes.content, 'response for REDACTED_CODE. (verified by agent-alpha)');
assert.ok(Array.isArray(playgroundRes.trace.appliedFilters) && playgroundRes.trace.appliedFilters.length > 0, 'Diagnostic trace should include appliedFilters');
console.log(' ✓ Non-streaming & Playground diagnostic trace verified.');
// 5b: Test SSE Streaming (Smart Buffer Mode across split <think> chunks)
const clientApp = express();
clientApp.use(express.json());
clientApp.post('/v1/chat/completions', async (req, res) => {
await engine.executeChatCompletion({
requestBody: req.body,
requestId: 'req-stream-test',
res,
isStreaming: !!req.body.stream
});
});
const clientServer = await new Promise<http.Server>((resolve) => {
const srv = clientApp.listen(19877, '127.0.0.1', () => resolve(srv));
});
try {
const streamResp = await fetch('http://127.0.0.1:19877/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'agent-alpha',
stream: true,
messages: [{ role: 'user', content: 'Stream test with badword' }]
})
});
assert.strictEqual(streamResp.status, 200);
const rawSse = await streamResp.text();
const dataLines = rawSse
.split('\n')
.map(l => l.trim())
.filter(l => l.startsWith('data: ') && l !== 'data: [DONE]');
let reconstructedStreamText = '';
for (const line of dataLines) {
const parsed = JSON.parse(line.slice(6));
if (parsed.choices?.[0]?.delta?.content) {
reconstructedStreamText += parsed.choices[0].delta.content;
}
}
assert.strictEqual(
reconstructedStreamText,
'hello from [censored] stream! (verified by agent-alpha)',
'Multi-chunk <think> tags and output filters should be cleanly applied on SSE stream'
);
console.log(' ✓ Smart SSE Stream buffering & multi-chunk regex/script filtering verified.');
} finally {
clientServer.close();
}
} finally {
upstreamServer.close();
}
// 6. Verify Admin Filters Page HTML Rendering
console.log('\n6. Testing Admin Filters Page HTML Rendering...');
const html = renderFiltersPage();
assert.ok(html.includes('Text Processing Filters &amp; Triggers'), 'Should render Filters page header');
assert.ok(html.includes('href="/admin/filters"'), 'Should include /admin/filters tab in navigation');
assert.ok(html.includes('Interactive Regex Assistant &amp; Presets'), 'Should include interactive regex builder');
assert.ok(html.includes('Model Filter Pipeline Orchestrator'), 'Should include per-model pipeline orchestrator');
console.log(' ✓ Admin UI HTML rendering verified.');
// 7. Verify Admin API Route Syntax Validation
console.log('\n7. Testing Admin API Route Validation (Regex & Script Syntax Check)...');
const adminApp = express();
adminApp.use(express.json());
adminApp.use('/api/admin', adminRoutes);
const adminServer = await new Promise<http.Server>((resolve) => {
const srv = adminApp.listen(19878, '127.0.0.1', () => resolve(srv));
});
try {
// Test invalid regex
const badRegexResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Bad Regex Filter',
type: 'regex_replace',
regexConfig: { pattern: '[invalid(regex', flags: 'g', replacement: '' }
})
});
assert.strictEqual(badRegexResp.status, 400);
const badRegexJson = (await badRegexResp.json()) as any;
assert.ok(badRegexJson.error?.includes('Invalid regular expression'), 'Should catch invalid regex pattern');
// Test invalid JavaScript script syntax
const badScriptResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Bad Script Filter',
type: 'custom_script',
scriptConfig: { code: 'function broken( { return text;' }
})
});
assert.strictEqual(badScriptResp.status, 400);
const badScriptJson = (await badScriptResp.json()) as any;
assert.ok(badScriptJson.error?.includes('JavaScript syntax error in filter code'), 'Should catch invalid JS code');
// Test valid script save
const goodScriptResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Good Script Filter',
type: 'custom_script',
scriptConfig: { code: 'return text.toLowerCase();' }
})
});
assert.strictEqual(goodScriptResp.status, 200);
console.log(' ✓ Admin API regex and JavaScript syntax validations verified.');
} finally {
adminServer.close();
}
console.log('\n✅ ALL TEXT FILTER TESTS PASSED SUCCESSFULLY!');
} finally {
if (fs.existsSync(testConfigPath)) {
fs.unlinkSync(testConfigPath);
}
}
}
runFilterTests().catch(err => {
console.error('❌ Test failed:', err);
process.exit(1);
});