diff --git a/package.json b/package.json index f49e4ef..fa19397 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "dev": "ts-node src/index.ts", "watch": "tsc --watch", "logs": "ts-node src/inspectLogs.ts", - "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts && API_PASSWORD=test_password ts-node test-moderation-and-cooldown-recovery.ts && API_PASSWORD=test_password ts-node test-log-compression.ts" + "test": "API_PASSWORD=test_password ts-node test-revolver.ts && API_PASSWORD=test_password ts-node test-filters.ts && API_PASSWORD=test_password ts-node test-integration.ts && API_PASSWORD=test_password ts-node test-timeout-keepalive.ts && API_PASSWORD=test_password ts-node test-live-watcher.ts && API_PASSWORD=test_password ts-node test-telemetry-fallback.ts && API_PASSWORD=test_password ts-node test-content-length-resilience.ts && API_PASSWORD=test_password ts-node test-circuit-breaker-fallback.ts && API_PASSWORD=test_password ts-node test-moderation-and-cooldown-recovery.ts && API_PASSWORD=test_password ts-node test-log-compression.ts" }, "keywords": [ "openai", diff --git a/src/admin/filtersPage.ts b/src/admin/filtersPage.ts new file mode 100644 index 0000000..930838b --- /dev/null +++ b/src/admin/filtersPage.ts @@ -0,0 +1,1732 @@ +import { renderAdminLayout } from './layout'; + +export function renderFiltersPage(): string { + const extraStyles = ` + .filters-top-bar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; + flex-wrap: wrap; + margin-bottom: 1.25rem; + } + + .filter-pills { + display: flex; + gap: 0.4rem; + flex-wrap: wrap; + } + + .filter-pill-btn { + background: rgba(255, 255, 255, 0.05); + border: 1px solid var(--border-dark); + color: var(--muted-dark); + padding: 0.4rem 0.85rem; + border-radius: 20px; + font-size: 0.8rem; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; + } + + .filter-pill-btn.active, + .filter-pill-btn:hover { + background: rgba(187, 134, 252, 0.18); + color: var(--primary-color); + border-color: var(--primary-color); + } + + .filter-card-meta { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + margin-bottom: 0.85rem; + } + + .filter-rule-preview { + background: rgba(0, 0, 0, 0.28); + border: 1px solid var(--border-dark); + border-radius: 8px; + padding: 0.65rem 0.8rem; + font-family: monospace; + font-size: 0.8rem; + color: var(--text-dark); + margin-bottom: 0.85rem; + overflow-x: auto; + white-space: pre-wrap; + word-break: break-word; + } + + body.light-theme .filter-rule-preview { + background: rgba(0, 0, 0, 0.04); + border-color: var(--border-light); + color: var(--text-light); + } + + .filter-trigger-summary { + font-size: 0.78rem; + color: var(--muted-dark); + margin-bottom: 0.75rem; + display: flex; + align-items: center; + gap: 0.4rem; + flex-wrap: wrap; + } + + .pipeline-orchestrator-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1.5rem; + margin-top: 2rem; + } + + @media (max-width: 980px) { + .pipeline-orchestrator-grid { + grid-template-columns: 1fr; + } + } + + .pipeline-chain-list { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin: 0.85rem 0; + min-height: 80px; + } + + .pipeline-chain-item { + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.75rem; + background: rgba(0, 0, 0, 0.24); + border: 1px solid var(--border-dark); + border-radius: 8px; + padding: 0.6rem 0.85rem; + } + + body.light-theme .pipeline-chain-item { + background: rgba(0, 0, 0, 0.03); + border-color: var(--border-light); + } + + .pipeline-chain-index { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(187, 134, 252, 0.2); + color: var(--primary-color); + font-size: 0.75rem; + font-weight: 700; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .builder-box { + background: rgba(187, 134, 252, 0.06); + border: 1px solid rgba(187, 134, 252, 0.22); + border-radius: 10px; + padding: 1rem; + margin-bottom: 1rem; + } + + .rule-row { + display: flex; + gap: 0.5rem; + align-items: center; + margin-bottom: 0.5rem; + flex-wrap: wrap; + } + + .flag-chip { + display: inline-flex; + align-items: center; + gap: 0.3rem; + background: rgba(0, 0, 0, 0.25); + border: 1px solid var(--border-dark); + border-radius: 6px; + padding: 0.35rem 0.6rem; + font-size: 0.8rem; + cursor: pointer; + user-select: none; + } + + .var-chip { + background: rgba(187, 134, 252, 0.14); + border: 1px solid rgba(187, 134, 252, 0.3); + color: var(--primary-color); + border-radius: 6px; + padding: 2px 8px; + font-family: monospace; + font-size: 0.75rem; + cursor: pointer; + transition: all 0.15s ease; + } + + .var-chip:hover { + background: var(--primary-color); + color: #121212; + } + + .regex-highlight-box { + background: rgba(0, 0, 0, 0.35); + border: 1px solid var(--border-dark); + border-radius: 8px; + padding: 0.75rem; + font-family: monospace; + font-size: 0.82rem; + white-space: pre-wrap; + word-break: break-word; + min-height: 54px; + } + + .regex-match-mark { + background: rgba(3, 218, 198, 0.28); + border-bottom: 2px solid var(--accent-success); + color: #fff; + padding: 0 2px; + border-radius: 3px; + } + + .trace-step-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.5rem; + padding: 0.45rem 0.65rem; + border-radius: 6px; + background: rgba(0, 0, 0, 0.2); + border: 1px solid var(--border-dark); + font-size: 0.8rem; + margin-bottom: 0.4rem; + } + `; + + const bodyHtml = ` +
+
+
+

+ + Text Processing Filters & Triggers +

+

+ Create reusable Input & Output filters (Word/Text Replacement, Interactive Regex, Instruction Injection, or Sandboxed JS Scripts) and bind them to any Custom Model in any execution order. +

+
+ +
+ +
+
+ + + + +
+
+ + Use Up/Down controls on cards or in the Model Pipeline Orchestrator below to control execution sequence. +
+
+ +
+ +
+ + +
+ +
+
+
+
+ + Model Filter Pipeline Orchestrator +
+
+ Configure and reorder the exact filter execution sequence for each Custom Model. +
+
+
+ +
+ + +
+ +
+ +
+ +
+ + +
+ +
+ Ordered Execution Chain (Top → Bottom) +
+
+ +
+
+ + +
+
+
+
+ + Interactive Pipeline Dry-Run Sandbox +
+
+ Simulate Input & Output filter execution step-by-step without consuming API tokens. +
+
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ + + + +
+
+
+ `; + + const modalsHtml = ` + + + `; + + const pageScript = ` + let currentState = { + filters: [], + customModels: [], + presets: [] + }; + let activeTab = 'all'; + let modalTriggers = [{ type: 'always', value: '' }]; + let modalLiteralRules = [{ find: '', replace: '' }]; + + const scriptStarterTemplates = { + clean_text: "// Normalize whitespace and strip leading/trailing spaces\\nreturn text.replace(/\\\\r\\\\n/g, '\\n').trim();", + inject_system: "// Dynamically inject a system instruction if the user asks for code\\nif (context.direction === 'input' && /code|function|script/i.test(text)) {\\n prependSystem('Always provide clean, well-commented, production-ready code.');\\n}\\nreturn text;", + extract_json: "// Extract JSON object if wrapped in prose or markdown\\nconst match = text.match(/\\\\{[\\\\s\\\\S]*\\\\}/);\\nreturn match ? match[0] : text;", + append_footer: "// Append a metadata footer to output\\nreturn text + '\\n\\n---\\n*Processed by ' + context.model + '*';" + }; + + async function initPage() { + await loadFiltersData(); + } + + async function loadFiltersData() { + try { + const res = await apiRequest('/api/admin/filters'); + if (!res.ok) throw new Error('Failed to load filters configuration'); + currentState = await res.json(); + populateRegexPresets(); + renderFiltersLibrary(); + populateOrchestratorSelectors(); + populateSandboxSelectors(); + } catch (err) { + showToast(err.message, 'error'); + } + } + + function populateRegexPresets() { + const select = document.getElementById('regex-preset-select'); + select.innerHTML = ''; + (currentState.presets || []).forEach(p => { + const opt = document.createElement('option'); + opt.value = p.id; + opt.textContent = p.name; + select.appendChild(opt); + }); + } + + // Filter pill tabs + document.querySelectorAll('.filter-pill-btn').forEach(btn => { + btn.addEventListener('click', () => { + document.querySelectorAll('.filter-pill-btn').forEach(b => b.classList.remove('active')); + btn.classList.add('active'); + activeTab = btn.getAttribute('data-filter-tab') || 'all'; + renderFiltersLibrary(); + }); + }); + + function getDirectionBadge(dir) { + if (dir === 'input') return ' Input'; + if (dir === 'output') return ' Output'; + return ' Input & Output'; + } + + function getTypeBadge(type) { + switch (type) { + case 'literal_replace': + return ' Word/Text Replace'; + case 'regex_replace': + return ' Regex Filter'; + case 'instruction_inject': + return ' Instruction Inject'; + case 'custom_script': + return ' JS Script'; + default: + return '' + escapeHtml(type) + ''; + } + } + + function summarizeFilterRule(filter) { + if (filter.type === 'literal_replace') { + const rules = filter.literalConfig?.rules || []; + if (rules.length === 0) return 'No replacement pairs defined'; + return rules.slice(0, 3).map(r => '"' + r.find + '" -> "' + r.replace + '"').join('\\n') + + (rules.length > 3 ? '\\n... (+' + (rules.length - 3) + ' more)' : ''); + } + if (filter.type === 'regex_replace') { + const cfg = filter.regexConfig || {}; + return '/' + (cfg.pattern || '') + '/' + (cfg.flags || 'g') + ' ==> ' + (cfg.replacement ? '"' + cfg.replacement + '"' : '[STRIP]'); + } + if (filter.type === 'instruction_inject') { + const cfg = filter.instructionConfig || {}; + return '[' + (cfg.position || 'prepend_system') + ']: ' + (cfg.content || '').slice(0, 120); + } + if (filter.type === 'custom_script') { + return (filter.scriptConfig?.code || '').slice(0, 140); + } + return ''; + } + + function summarizeTriggers(filter) { + const rules = filter.triggers?.rules || []; + if (rules.length === 0 || (rules.length === 1 && rules[0].type === 'always')) { + return 'Trigger: Always (Unconditional)'; + } + const mode = filter.triggers?.matchMode === 'any' ? 'OR' : 'AND'; + const parts = rules.map(r => { + if (r.type === 'always') return 'Always'; + if (r.type === 'no_system_prompt') return 'No System Prompt'; + return r.type + '(' + (r.value || '') + ')'; + }); + return 'Trigger [' + mode + ']: ' + parts.join(', '); + } + + function renderFiltersLibrary() { + const container = document.getElementById('filters-list'); + container.innerHTML = ''; + + const allFilters = currentState.filters || []; + const filtered = allFilters.filter(f => { + if (activeTab === 'input') return f.direction === 'input' || f.direction === 'both'; + if (activeTab === 'output') return f.direction === 'output' || f.direction === 'both'; + if (activeTab === 'global') return !!f.isGlobal; + return true; + }); + + if (filtered.length === 0) { + container.innerHTML = '

No text filters found in this view. Click "New Text Filter" to create one.

'; + return; + } + + filtered.forEach((filter) => { + const globalIdx = allFilters.findIndex(x => x.id === filter.id); + const boundModels = (currentState.customModels || []).filter(m => + Array.isArray(m.filterIds) && m.filterIds.includes(filter.id) + ); + + const modelBadges = filter.isGlobal + ? ' Global (All Models)' + : (boundModels.length > 0 + ? boundModels.map(m => '' + escapeHtml(m.name) + '').join(' ') + : 'Unassigned'); + + const card = document.createElement('div'); + card.className = 'card'; + if (!filter.enabled) { + card.style.opacity = '0.65'; + } + + card.innerHTML = \` +
+
+
+ \${escapeHtml(filter.name)} + \${!filter.enabled ? 'Disabled' : ''} +
+
\${escapeHtml(filter.description || 'Text Processing Filter')}
+
+
+ + + + + +
+
+ +
+ \${getDirectionBadge(filter.direction)} + \${getTypeBadge(filter.type)} + \${(filter.direction === 'input' || filter.direction === 'both') ? 'Target: ' + escapeHtml(filter.inputTarget || 'last_user') + '' : ''} + \${(filter.direction === 'output' || filter.direction === 'both') ? 'SSE: ' + (filter.streamMode === 'chunk_by_chunk' ? 'Chunk' : 'Smart Buffer') + '' : ''} +
+ +
\${escapeHtml(summarizeFilterRule(filter))}
+ +
+ + \${escapeHtml(summarizeTriggers(filter))} +
+ +
+ Models: + \${modelBadges} +
+ \`; + + container.appendChild(card); + }); + + container.querySelectorAll('.toggle-filter-btn').forEach(btn => { + btn.addEventListener('click', () => toggleFilterEnabled(btn.getAttribute('data-id'))); + }); + container.querySelectorAll('.move-filter-up').forEach(btn => { + btn.addEventListener('click', () => moveGlobalFilter(parseInt(btn.getAttribute('data-idx')), -1)); + }); + container.querySelectorAll('.move-filter-down').forEach(btn => { + btn.addEventListener('click', () => moveGlobalFilter(parseInt(btn.getAttribute('data-idx')), 1)); + }); + container.querySelectorAll('.edit-filter-btn').forEach(btn => { + btn.addEventListener('click', () => openEditFilterModal(btn.getAttribute('data-id'))); + }); + container.querySelectorAll('.delete-filter-btn').forEach(btn => { + btn.addEventListener('click', () => deleteFilter(btn.getAttribute('data-id'))); + }); + } + + async function toggleFilterEnabled(id) { + const f = (currentState.filters || []).find(x => x.id === id); + if (!f) return; + try { + const res = await apiRequest('/api/admin/filters', { + method: 'POST', + body: { ...f, enabled: !f.enabled } + }); + if (!res.ok) throw new Error('Failed to update filter'); + await loadFiltersData(); + showToast('Filter ' + (!f.enabled ? 'enabled' : 'disabled') + '.', 'info'); + } catch (err) { + showToast(err.message, 'error'); + } + } + + async function moveGlobalFilter(index, delta) { + const ids = (currentState.filters || []).map(f => f.id); + const targetIdx = index + delta; + if (targetIdx < 0 || targetIdx >= ids.length) return; + const tmp = ids[index]; + ids[index] = ids[targetIdx]; + ids[targetIdx] = tmp; + + try { + const res = await apiRequest('/api/admin/filters/reorder', { + method: 'POST', + body: { orderedIds: ids } + }); + if (!res.ok) throw new Error('Failed to reorder filters'); + await loadFiltersData(); + } catch (err) { + showToast(err.message, 'error'); + } + } + + async function deleteFilter(id) { + if (!confirm('Are you sure you want to delete this text filter?')) return; + try { + const res = await apiRequest('/api/admin/filters/' + id, { method: 'DELETE' }); + if (!res.ok) throw new Error('Failed to delete filter'); + showToast('Filter deleted.', 'info'); + await loadFiltersData(); + } catch (err) { + showToast(err.message, 'error'); + } + } + + // ==================== PER-MODEL PIPELINE ORCHESTRATOR ==================== + function populateOrchestratorSelectors() { + const modelSelect = document.getElementById('orchestrator-model-select'); + const prevModelId = modelSelect.value; + modelSelect.innerHTML = ''; + + (currentState.customModels || []).forEach(m => { + const opt = document.createElement('option'); + opt.value = m.id; + opt.textContent = m.name + (m.isDefault ? ' (Default)' : ''); + modelSelect.appendChild(opt); + }); + + if (prevModelId && (currentState.customModels || []).some(m => m.id === prevModelId)) { + modelSelect.value = prevModelId; + } + + renderOrchestratorChain(); + } + + document.getElementById('orchestrator-model-select').addEventListener('change', () => { + renderOrchestratorChain(); + }); + + function renderOrchestratorChain() { + const modelId = document.getElementById('orchestrator-model-select').value; + const model = (currentState.customModels || []).find(m => m.id === modelId); + const chainContainer = document.getElementById('orchestrator-chain-container'); + const addFilterSelect = document.getElementById('orchestrator-add-filter-select'); + const disableGlobalCheckbox = document.getElementById('orchestrator-disable-global'); + + if (!model) { + chainContainer.innerHTML = '
No custom models available.
'; + addFilterSelect.innerHTML = ''; + return; + } + + disableGlobalCheckbox.checked = !!model.disableGlobalFilters; + + const attachedIds = Array.isArray(model.filterIds) ? [...model.filterIds] : []; + const allFilters = currentState.filters || []; + const filterMap = new Map(allFilters.map(f => [f.id, f])); + + // Populate attach dropdown with filters not yet in attachedIds + addFilterSelect.innerHTML = ''; + allFilters.forEach(f => { + if (!attachedIds.includes(f.id)) { + const opt = document.createElement('option'); + opt.value = f.id; + opt.textContent = f.name + ' [' + f.direction.toUpperCase() + ' - ' + f.type + ']' + (f.isGlobal ? ' (Global)' : ''); + addFilterSelect.appendChild(opt); + } + }); + + // Build effective display list: explicitly attached (reorderable) + any remaining active Global filters + const unattachedGlobalFilters = !model.disableGlobalFilters + ? allFilters.filter(f => f.isGlobal && !attachedIds.includes(f.id)) + : []; + + if (attachedIds.length === 0 && unattachedGlobalFilters.length === 0) { + chainContainer.innerHTML = '
No filters attached to ' + escapeHtml(model.name) + '. Attach a filter above or mark a filter as Global.
'; + return; + } + + chainContainer.innerHTML = ''; + + attachedIds.forEach((fid, idx) => { + const f = filterMap.get(fid); + if (!f) return; + const row = document.createElement('div'); + row.className = 'pipeline-chain-item'; + row.innerHTML = \` +
+ \${idx + 1} +
+
+ \${escapeHtml(f.name)} + \${getDirectionBadge(f.direction)} + \${getTypeBadge(f.type)} + \${!f.enabled ? 'Disabled' : ''} +
+
\${escapeHtml(summarizeTriggers(f))}
+
+
+
+ + + +
+ \`; + chainContainer.appendChild(row); + }); + + unattachedGlobalFilters.forEach((f, gIdx) => { + const row = document.createElement('div'); + row.className = 'pipeline-chain-item'; + row.style.borderStyle = 'dashed'; + row.innerHTML = \` +
+ G +
+
+ \${escapeHtml(f.name)} + Auto-Global + \${getDirectionBadge(f.direction)} +
+
Runs via Global setting (Attach explicitly to pin custom position)
+
+
+
+ +
+ \`; + chainContainer.appendChild(row); + }); + + chainContainer.querySelectorAll('.model-chain-up').forEach(btn => { + btn.addEventListener('click', () => reorderModelFilter(model, parseInt(btn.getAttribute('data-idx')), -1)); + }); + chainContainer.querySelectorAll('.model-chain-down').forEach(btn => { + btn.addEventListener('click', () => reorderModelFilter(model, parseInt(btn.getAttribute('data-idx')), 1)); + }); + chainContainer.querySelectorAll('.model-chain-remove').forEach(btn => { + btn.addEventListener('click', () => detachModelFilter(model, btn.getAttribute('data-id'))); + }); + chainContainer.querySelectorAll('.pin-global-btn').forEach(btn => { + btn.addEventListener('click', () => attachFilterToModel(model, btn.getAttribute('data-id'))); + }); + } + + async function saveModelPipeline(modelId, filterIds, disableGlobalFilters) { + try { + const res = await apiRequest('/api/admin/models/' + modelId + '/filters', { + method: 'POST', + body: { filterIds, disableGlobalFilters } + }); + if (!res.ok) throw new Error('Failed to update model filter pipeline'); + await loadFiltersData(); + showToast('Model filter pipeline updated.', 'success'); + } catch (err) { + showToast(err.message, 'error'); + } + } + + document.getElementById('orchestrator-attach-btn').addEventListener('click', () => { + const modelId = document.getElementById('orchestrator-model-select').value; + const filterId = document.getElementById('orchestrator-add-filter-select').value; + const model = (currentState.customModels || []).find(m => m.id === modelId); + if (!model || !filterId) return; + attachFilterToModel(model, filterId); + }); + + document.getElementById('orchestrator-disable-global').addEventListener('change', (e) => { + const modelId = document.getElementById('orchestrator-model-select').value; + const model = (currentState.customModels || []).find(m => m.id === modelId); + if (!model) return; + saveModelPipeline(model.id, model.filterIds || [], e.target.checked); + }); + + function attachFilterToModel(model, filterId) { + const ids = Array.isArray(model.filterIds) ? [...model.filterIds] : []; + if (!ids.includes(filterId)) ids.push(filterId); + saveModelPipeline(model.id, ids, !!model.disableGlobalFilters); + } + + function detachModelFilter(model, filterId) { + const ids = (model.filterIds || []).filter(id => id !== filterId); + saveModelPipeline(model.id, ids, !!model.disableGlobalFilters); + } + + function reorderModelFilter(model, idx, delta) { + const ids = Array.isArray(model.filterIds) ? [...model.filterIds] : []; + const targetIdx = idx + delta; + if (targetIdx < 0 || targetIdx >= ids.length) return; + const tmp = ids[idx]; + ids[idx] = ids[targetIdx]; + ids[targetIdx] = tmp; + saveModelPipeline(model.id, ids, !!model.disableGlobalFilters); + } + + // ==================== DRY-RUN SANDBOX ==================== + function populateSandboxSelectors() { + const sel = document.getElementById('sandbox-target-select'); + const prev = sel.value; + sel.innerHTML = ''; + + const modelsGroup = document.createElement('optgroup'); + modelsGroup.label = 'Test Full Custom Model Pipeline'; + (currentState.customModels || []).forEach(m => { + const opt = document.createElement('option'); + opt.value = 'model:' + m.id; + opt.textContent = 'Model: ' + m.name; + modelsGroup.appendChild(opt); + }); + sel.appendChild(modelsGroup); + + const filtersGroup = document.createElement('optgroup'); + filtersGroup.label = 'Test Single Filter in Isolation'; + (currentState.filters || []).forEach(f => { + const opt = document.createElement('option'); + opt.value = 'filter:' + f.id; + opt.textContent = 'Filter: ' + f.name + ' (' + f.direction + ')'; + filtersGroup.appendChild(opt); + }); + sel.appendChild(filtersGroup); + + if (prev) sel.value = prev; + } + + document.getElementById('run-sandbox-btn').addEventListener('click', async () => { + const targetVal = document.getElementById('sandbox-target-select').value || ''; + const sampleInputText = document.getElementById('sandbox-input-text').value; + const sampleOutputText = document.getElementById('sandbox-output-text').value; + + const payload = { + sampleInputText, + sampleOutputText + }; + + if (targetVal.startsWith('model:')) { + payload.customModelId = targetVal.slice(6); + } else if (targetVal.startsWith('filter:')) { + const fid = targetVal.slice(7); + const f = (currentState.filters || []).find(x => x.id === fid); + if (f) { + payload.filtersOverride = [{ ...f, enabled: true }]; + } + } + + await executeDryRunAndRender(payload); + }); + + async function executeDryRunAndRender(payload) { + try { + const res = await apiRequest('/api/admin/filters/dry-run', { + method: 'POST', + body: payload + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Dry-run failed'); + + document.getElementById('sandbox-results-container').style.display = 'block'; + + // Input results + const inBadge = document.getElementById('sandbox-input-badge'); + inBadge.className = 'badge ' + (data.inputResult.modified ? 'badge-success' : 'badge-info'); + inBadge.textContent = data.inputResult.modified ? 'Modified' : 'Unchanged'; + + const inTracesEl = document.getElementById('sandbox-input-traces'); + inTracesEl.innerHTML = (data.inputResult.traces || []).map(t => \` +
+ \${escapeHtml(t.filterName)} (\${escapeHtml(t.filterType)}) + + \${t.error ? 'Error: ' + escapeHtml(t.error) + '' : + (!t.triggered ? 'Trigger Skipped' : + (t.modified ? 'Modified (' + t.durationMs + 'ms)' : 'Triggered / No Change'))} + +
+ \`).join(''); + + document.getElementById('sandbox-input-output').textContent = + (data.inputResult.afterMessages || []).map(m => '[' + m.role.toUpperCase() + ']: ' + m.content).join('\\n\\n'); + + // Output results + const outBadge = document.getElementById('sandbox-output-badge'); + outBadge.className = 'badge ' + (data.outputResult.modified ? 'badge-success' : 'badge-info'); + outBadge.textContent = data.outputResult.modified ? 'Modified' : 'Unchanged'; + + const outTracesEl = document.getElementById('sandbox-output-traces'); + outTracesEl.innerHTML = (data.outputResult.traces || []).map(t => \` +
+ \${escapeHtml(t.filterName)} (\${escapeHtml(t.filterType)}) + + \${t.error ? 'Error: ' + escapeHtml(t.error) + '' : + (!t.triggered ? 'Trigger Skipped' : + (t.modified ? 'Modified (' + t.durationMs + 'ms)' : 'Triggered / No Change'))} + +
+ \`).join(''); + + document.getElementById('sandbox-output-result').textContent = data.outputResult.afterText; + } catch (err) { + showToast(err.message, 'error'); + } + } + + // ==================== MODAL BUILDER & INTERACTIVE CONTROLS ==================== + function updateModalVisibilityByType() { + const selectedType = document.getElementById('filter-type-select').value; + document.querySelectorAll('.filter-mode-panel').forEach(p => p.style.display = 'none'); + const activePanel = document.getElementById('panel-' + selectedType); + if (activePanel) activePanel.style.display = 'block'; + if (selectedType === 'regex_replace') { + updateLiveRegexPreview(); + } + } + + document.getElementById('filter-type-select').addEventListener('change', updateModalVisibilityByType); + + document.getElementById('instruction-position').addEventListener('change', (e) => { + document.getElementById('instruction-suffix-group').style.display = + e.target.value === 'wrap_target' ? 'flex' : 'none'; + }); + + document.querySelectorAll('.var-chip').forEach(chip => { + chip.addEventListener('click', () => { + const textarea = document.getElementById('instruction-content'); + const v = chip.getAttribute('data-var') || ''; + const start = textarea.selectionStart || textarea.value.length; + const end = textarea.selectionEnd || textarea.value.length; + textarea.value = textarea.value.slice(0, start) + v + textarea.value.slice(end); + textarea.focus(); + }); + }); + + document.getElementById('script-template-select').addEventListener('change', (e) => { + const tpl = scriptStarterTemplates[e.target.value]; + if (tpl) { + document.getElementById('script-code').value = tpl; + } + }); + + // Interactive Regex Presets & Visual Constructor + document.getElementById('regex-preset-select').addEventListener('change', (e) => { + const presetId = e.target.value; + const preset = (currentState.presets || []).find(p => p.id === presetId); + if (!preset) return; + document.getElementById('regex-pattern').value = preset.pattern; + document.getElementById('regex-replacement').value = preset.replacement; + if (preset.sampleInput) { + document.getElementById('regex-sample-input').value = preset.sampleInput; + } + setRegexFlagsInModal(preset.flags || 'g'); + updateLiveRegexPreview(); + }); + + document.getElementById('regex-builder-mode').addEventListener('change', (e) => { + const mode = e.target.value; + const arg1Label = document.getElementById('regex-builder-arg1-label'); + const arg2Wrap = document.getElementById('regex-builder-arg2-wrap'); + const arg1Input = document.getElementById('regex-builder-arg1'); + if (mode === 'between_delimiters') { + arg1Label.textContent = 'Start Tag / Delimiter'; + arg1Input.placeholder = 'e.g. '; + arg2Wrap.style.display = 'block'; + } else if (mode === 'word_list') { + arg1Label.textContent = 'Comma-Separated Words'; + arg1Input.placeholder = 'e.g. foo, bar, secret'; + arg2Wrap.style.display = 'none'; + } else if (mode === 'line_prefix') { + arg1Label.textContent = 'Line Prefix'; + arg1Input.placeholder = 'e.g. DEBUG:'; + arg2Wrap.style.display = 'none'; + } else if (mode === 'line_containing') { + arg1Label.textContent = 'Contained Text'; + arg1Input.placeholder = 'e.g. CONFIDENTIAL'; + arg2Wrap.style.display = 'none'; + } + }); + + function escapeRegexLiteral(s) { + return String(s).replace(/[.*+?^\${}()|[\\]\\\\]/g, '\\\\$&'); + } + + document.getElementById('apply-regex-builder-btn').addEventListener('click', () => { + const mode = document.getElementById('regex-builder-mode').value; + const arg1 = document.getElementById('regex-builder-arg1').value; + const arg2 = document.getElementById('regex-builder-arg2').value; + if (!arg1) { + showToast('Enter a value in the pattern constructor first.', 'warning'); + return; + } + + if (mode === 'between_delimiters') { + const startEsc = escapeRegexLiteral(arg1); + const endEsc = escapeRegexLiteral(arg2 || arg1); + document.getElementById('regex-pattern').value = startEsc + '[\\\\s\\\\S]*?' + endEsc + '\\\\s*'; + setRegexFlagsInModal('gi'); + } else if (mode === 'word_list') { + const words = arg1.split(',').map(w => escapeRegexLiteral(w.trim())).filter(Boolean); + document.getElementById('regex-pattern').value = '\\\\b(?:' + words.join('|') + ')\\\\b'; + setRegexFlagsInModal('gi'); + } else if (mode === 'line_prefix') { + document.getElementById('regex-pattern').value = '^\\\\s*' + escapeRegexLiteral(arg1) + '.*(?:\\\\r?\\\\n)?'; + setRegexFlagsInModal('gm'); + } else if (mode === 'line_containing') { + document.getElementById('regex-pattern').value = '^.*' + escapeRegexLiteral(arg1) + '.*(?:\\\\r?\\\\n)?'; + setRegexFlagsInModal('gmi'); + } + updateLiveRegexPreview(); + showToast('Regex pattern constructed!', 'success'); + }); + + function getRegexFlagsFromModal() { + const flags = []; + document.querySelectorAll('.regex-flag-cb').forEach(cb => { + if (cb.checked) flags.push(cb.value); + }); + return flags.join(''); + } + + function setRegexFlagsInModal(flagsStr) { + const set = new Set((flagsStr || 'g').split('')); + document.querySelectorAll('.regex-flag-cb').forEach(cb => { + cb.checked = set.has(cb.value); + }); + } + + function updateLiveRegexPreview() { + const pattern = document.getElementById('regex-pattern').value; + const flags = getRegexFlagsFromModal(); + const replacement = document.getElementById('regex-replacement').value; + const sample = document.getElementById('regex-sample-input').value || ''; + const highlightEl = document.getElementById('regex-highlight-preview'); + const outputEl = document.getElementById('regex-output-preview'); + const statusBadge = document.getElementById('regex-live-status'); + + if (!pattern) { + highlightEl.textContent = sample; + outputEl.textContent = sample; + statusBadge.className = 'badge badge-info'; + statusBadge.textContent = 'Enter pattern'; + return; + } + + try { + const matchFlags = flags.includes('g') ? flags : flags + 'g'; + const re = new RegExp(pattern, matchFlags); + const execRe = new RegExp(pattern, flags); + + let matchCount = 0; + let lastIndex = 0; + let htmlParts = []; + let m; + + while ((m = re.exec(sample)) !== null) { + if (m[0].length === 0) { + re.lastIndex++; + continue; + } + matchCount++; + htmlParts.push(escapeHtml(sample.slice(lastIndex, m.index))); + htmlParts.push('' + escapeHtml(m[0]) + ''); + lastIndex = m.index + m[0].length; + if (matchCount > 200) break; + } + htmlParts.push(escapeHtml(sample.slice(lastIndex))); + + highlightEl.innerHTML = htmlParts.join(''); + outputEl.textContent = sample.replace(execRe, replacement); + statusBadge.className = 'badge ' + (matchCount > 0 ? 'badge-success' : 'badge-warning'); + statusBadge.textContent = matchCount + ' match' + (matchCount === 1 ? '' : 'es'); + } catch (err) { + highlightEl.textContent = sample; + outputEl.textContent = 'Regex Syntax Error: ' + err.message; + statusBadge.className = 'badge badge-danger'; + statusBadge.textContent = 'Invalid Regex'; + } + } + + ['regex-pattern', 'regex-replacement', 'regex-sample-input'].forEach(id => { + document.getElementById(id).addEventListener('input', updateLiveRegexPreview); + }); + document.querySelectorAll('.regex-flag-cb').forEach(cb => { + cb.addEventListener('change', updateLiveRegexPreview); + }); + + // Trigger Rules Builder inside Modal + function renderModalTriggers() { + const container = document.getElementById('trigger-rules-container'); + container.innerHTML = ''; + + modalTriggers.forEach((rule, idx) => { + const row = document.createElement('div'); + row.className = 'rule-row'; + const needsValue = rule.type !== 'always' && rule.type !== 'no_system_prompt'; + + row.innerHTML = \` + + + \${modalTriggers.length > 1 ? \`\` : ''} + \`; + container.appendChild(row); + }); + + container.querySelectorAll('.trigger-type-sel').forEach(sel => { + sel.addEventListener('change', (e) => { + const i = parseInt(e.target.getAttribute('data-idx')); + modalTriggers[i].type = e.target.value; + renderModalTriggers(); + }); + }); + container.querySelectorAll('.trigger-val-inp').forEach(inp => { + inp.addEventListener('input', (e) => { + const i = parseInt(e.target.getAttribute('data-idx')); + modalTriggers[i].value = e.target.value; + }); + }); + container.querySelectorAll('.remove-trigger-btn').forEach(btn => { + btn.addEventListener('click', () => { + const i = parseInt(btn.getAttribute('data-idx')); + modalTriggers.splice(i, 1); + renderModalTriggers(); + }); + }); + } + + document.getElementById('add-trigger-rule-btn').addEventListener('click', () => { + modalTriggers.push({ type: 'contains', value: '' }); + renderModalTriggers(); + }); + + // Literal Find/Replace Rules Builder inside Modal + function renderModalLiteralRules() { + const container = document.getElementById('literal-rules-container'); + container.innerHTML = ''; + + modalLiteralRules.forEach((rule, idx) => { + const row = document.createElement('div'); + row.className = 'rule-row'; + row.innerHTML = \` + + + + \${modalLiteralRules.length > 1 ? \`\` : ''} + \`; + container.appendChild(row); + }); + + container.querySelectorAll('.literal-find-inp').forEach(inp => { + inp.addEventListener('input', (e) => { + const i = parseInt(e.target.getAttribute('data-idx')); + modalLiteralRules[i].find = e.target.value; + }); + }); + container.querySelectorAll('.literal-replace-inp').forEach(inp => { + inp.addEventListener('input', (e) => { + const i = parseInt(e.target.getAttribute('data-idx')); + modalLiteralRules[i].replace = e.target.value; + }); + }); + container.querySelectorAll('.remove-literal-btn').forEach(btn => { + btn.addEventListener('click', () => { + const i = parseInt(btn.getAttribute('data-idx')); + modalLiteralRules.splice(i, 1); + renderModalLiteralRules(); + }); + }); + } + + document.getElementById('add-literal-rule-btn').addEventListener('click', () => { + modalLiteralRules.push({ find: '', replace: '' }); + renderModalLiteralRules(); + }); + + function renderModelAssignmentCheckboxes(selectedModelIds = []) { + const container = document.getElementById('filter-models-checkboxes'); + container.innerHTML = ''; + const set = new Set(selectedModelIds); + + (currentState.customModels || []).forEach(m => { + const lbl = document.createElement('label'); + lbl.className = 'flag-chip'; + lbl.innerHTML = \` + + \${escapeHtml(m.name)} + \`; + container.appendChild(lbl); + }); + } + + // Open Modal for New Filter + document.getElementById('add-filter-btn').addEventListener('click', () => { + document.getElementById('filter-modal-title').innerHTML = 'Create New Text Filter'; + document.getElementById('filter-id').value = ''; + document.getElementById('filter-name').value = ''; + document.getElementById('filter-desc').value = ''; + document.getElementById('filter-direction').value = 'output'; + document.getElementById('filter-input-target').value = 'last_user'; + document.getElementById('filter-stream-mode').value = 'buffer_full'; + document.getElementById('filter-enabled').checked = true; + document.getElementById('filter-is-global').checked = false; + document.getElementById('filter-type-select').value = 'literal_replace'; + document.getElementById('trigger-match-mode').value = 'all'; + + modalTriggers = [{ type: 'always', value: '' }]; + modalLiteralRules = [{ find: '', replace: '' }]; + document.getElementById('literal-case-sensitive').checked = false; + document.getElementById('literal-whole-word').checked = false; + + document.getElementById('regex-pattern').value = ''; + document.getElementById('regex-replacement').value = ''; + setRegexFlagsInModal('gi'); + + document.getElementById('instruction-position').value = 'prepend_system'; + document.getElementById('instruction-separator').value = '\\\\n\\\\n'; + document.getElementById('instruction-content').value = ''; + document.getElementById('instruction-wrap-suffix').value = ''; + document.getElementById('instruction-suffix-group').style.display = 'none'; + + document.getElementById('script-code').value = scriptStarterTemplates.clean_text; + document.getElementById('script-timeout').value = '500'; + + renderModalTriggers(); + renderModalLiteralRules(); + renderModelAssignmentCheckboxes((currentState.customModels || []).map(m => m.id)); + updateModalVisibilityByType(); + openModal('filter-modal'); + }); + + function openEditFilterModal(id) { + const f = (currentState.filters || []).find(x => x.id === id); + if (!f) return; + + document.getElementById('filter-modal-title').innerHTML = 'Edit Text Filter'; + document.getElementById('filter-id').value = f.id; + document.getElementById('filter-name').value = f.name || ''; + document.getElementById('filter-desc').value = f.description || ''; + document.getElementById('filter-direction').value = f.direction || 'output'; + document.getElementById('filter-input-target').value = f.inputTarget || 'last_user'; + document.getElementById('filter-stream-mode').value = f.streamMode || 'buffer_full'; + document.getElementById('filter-enabled').checked = !!f.enabled; + document.getElementById('filter-is-global').checked = !!f.isGlobal; + document.getElementById('filter-type-select').value = f.type || 'literal_replace'; + document.getElementById('trigger-match-mode').value = f.triggers?.matchMode || 'all'; + + modalTriggers = (f.triggers?.rules && f.triggers.rules.length > 0) + ? JSON.parse(JSON.stringify(f.triggers.rules)) + : [{ type: 'always', value: '' }]; + + modalLiteralRules = (f.literalConfig?.rules && f.literalConfig.rules.length > 0) + ? JSON.parse(JSON.stringify(f.literalConfig.rules)) + : [{ find: '', replace: '' }]; + document.getElementById('literal-case-sensitive').checked = !!f.literalConfig?.caseSensitive; + document.getElementById('literal-whole-word').checked = !!f.literalConfig?.wholeWord; + + document.getElementById('regex-pattern').value = f.regexConfig?.pattern || ''; + document.getElementById('regex-replacement').value = f.regexConfig?.replacement || ''; + setRegexFlagsInModal(f.regexConfig?.flags || 'g'); + + const pos = f.instructionConfig?.position || 'prepend_system'; + document.getElementById('instruction-position').value = pos; + const rawSep = f.instructionConfig?.separator !== undefined ? f.instructionConfig.separator : '\\n\\n'; + document.getElementById('instruction-separator').value = rawSep.replace(/\\n/g, '\\\\n'); + document.getElementById('instruction-content').value = f.instructionConfig?.content || ''; + document.getElementById('instruction-wrap-suffix').value = f.instructionConfig?.wrapSuffix || ''; + document.getElementById('instruction-suffix-group').style.display = pos === 'wrap_target' ? 'flex' : 'none'; + + document.getElementById('script-code').value = f.scriptConfig?.code || ''; + document.getElementById('script-timeout').value = String(f.scriptConfig?.timeoutMs || 500); + + const boundModelIds = (currentState.customModels || []) + .filter(m => Array.isArray(m.filterIds) && m.filterIds.includes(f.id)) + .map(m => m.id); + + renderModalTriggers(); + renderModalLiteralRules(); + renderModelAssignmentCheckboxes(boundModelIds); + updateModalVisibilityByType(); + openModal('filter-modal'); + } + + function collectFilterPayloadFromModal() { + const id = document.getElementById('filter-id').value.trim(); + const name = document.getElementById('filter-name').value.trim() || 'Draft Filter'; + const description = document.getElementById('filter-desc').value.trim(); + const direction = document.getElementById('filter-direction').value; + const inputTarget = document.getElementById('filter-input-target').value; + const streamMode = document.getElementById('filter-stream-mode').value; + const enabled = document.getElementById('filter-enabled').checked; + const isGlobal = document.getElementById('filter-is-global').checked; + const type = document.getElementById('filter-type-select').value; + const matchMode = document.getElementById('trigger-match-mode').value; + + const assignedModelIds = []; + document.querySelectorAll('.assign-model-cb').forEach(cb => { + if (cb.checked) assignedModelIds.push(cb.value); + }); + + const rawSepInput = document.getElementById('instruction-separator').value; + const parsedSeparator = rawSepInput.replace(/\\\\n/g, '\\n').replace(/\\\\t/g, '\\t'); + + return { + id: id || undefined, + name, + description, + enabled, + isGlobal, + direction, + inputTarget, + streamMode, + triggers: { + matchMode, + rules: modalTriggers + }, + type, + literalConfig: { + rules: modalLiteralRules.filter(r => r.find && r.find.length > 0), + caseSensitive: document.getElementById('literal-case-sensitive').checked, + wholeWord: document.getElementById('literal-whole-word').checked + }, + regexConfig: { + pattern: document.getElementById('regex-pattern').value, + flags: getRegexFlagsFromModal() || 'g', + replacement: document.getElementById('regex-replacement').value + }, + instructionConfig: { + position: document.getElementById('instruction-position').value, + content: document.getElementById('instruction-content').value, + wrapSuffix: document.getElementById('instruction-wrap-suffix').value, + separator: parsedSeparator + }, + scriptConfig: { + code: document.getElementById('script-code').value, + timeoutMs: parseInt(document.getElementById('script-timeout').value) || 500 + }, + assignedModelIds + }; + } + + // Quick Test button inside Modal + document.getElementById('modal-test-filter-btn').addEventListener('click', async () => { + const draft = collectFilterPayloadFromModal(); + draft.id = draft.id || 'draft-preview'; + draft.enabled = true; + const sampleInputText = document.getElementById('sandbox-input-text').value; + const sampleOutputText = document.getElementById('sandbox-output-text').value; + + await executeDryRunAndRender({ + filtersOverride: [draft], + sampleInputText, + sampleOutputText + }); + showToast('Simulated draft filter in Dry-Run Sandbox (scroll down to inspect).', 'info'); + }); + + // Save Filter Form Submit + document.getElementById('filter-form').addEventListener('submit', async (e) => { + e.preventDefault(); + const payload = collectFilterPayloadFromModal(); + + if (payload.type === 'literal_replace' && (!payload.literalConfig.rules || payload.literalConfig.rules.length === 0)) { + showToast('Please add at least one non-empty Find/Replace rule.', 'error'); + return; + } + if (payload.type === 'regex_replace' && !payload.regexConfig.pattern) { + showToast('Please enter a regular expression pattern.', 'error'); + return; + } + if (payload.type === 'instruction_inject' && !payload.instructionConfig.content) { + showToast('Please enter instruction or template content to inject.', 'error'); + return; + } + if (payload.type === 'custom_script' && !payload.scriptConfig.code.trim()) { + showToast('Please provide JavaScript filter code.', 'error'); + return; + } + + try { + const res = await apiRequest('/api/admin/filters', { + method: 'POST', + body: payload + }); + const data = await res.json(); + if (!res.ok) { + throw new Error(data.error || 'Failed to save filter'); + } + showToast('Text filter saved successfully!', 'success'); + closeModal('filter-modal'); + await loadFiltersData(); + } catch (err) { + showToast(err.message, 'error'); + } + }); + `; + + return renderAdminLayout({ + activePage: 'filters', + pageTitle: 'Text Processing Filters', + bodyHtml, + modalsHtml, + pageScript, + extraStyles + }); +} diff --git a/src/admin/layout.ts b/src/admin/layout.ts index 012f080..f4fe08b 100644 --- a/src/admin/layout.ts +++ b/src/admin/layout.ts @@ -1,4 +1,4 @@ -export type AdminPageId = 'models' | 'providers' | 'playground' | 'telemetry' | 'live_logs'; +export type AdminPageId = 'models' | 'providers' | 'filters' | 'playground' | 'telemetry' | 'live_logs'; export interface AdminLayoutOptions { activePage: AdminPageId; @@ -643,6 +643,10 @@ export function renderAdminLayout(options: AdminLayoutOptions): string { API Providers + + + Text Filters + Revolver Playground diff --git a/src/admin/modelsPage.ts b/src/admin/modelsPage.ts index 711e7b7..676b96d 100644 --- a/src/admin/modelsPage.ts +++ b/src/admin/modelsPage.ts @@ -177,6 +177,30 @@ export function renderModelsPage(): string { + +
+
+
+ Text Processing Filters Pipeline +

Attach and order Input/Output filters for this model, or manage filter definitions in Text Filters.

+
+ +
+ +
+ + +
+ +
+ +
+
-
+
Token Usage:
+
+ Applied Text Filters: +
+
@@ -172,6 +176,18 @@ export function renderPlaygroundPage(): string { document.getElementById('trace-duration').textContent = data.trace.durationMs + ' ms'; const tok = data.trace.tokens; document.getElementById('trace-tokens').textContent = tok ? tok.promptTokens + ' in / ' + tok.completionTokens + ' out (' + tok.totalTokens + ' total)' : 'N/A'; + + const filtersEl = document.getElementById('trace-filters'); + const appliedFilters = data.trace.appliedFilters || []; + if (appliedFilters.length === 0) { + filtersEl.innerHTML = 'None'; + } else { + filtersEl.innerHTML = appliedFilters.map(f => { + const cls = f.error ? 'badge-danger' : (f.modified ? 'badge-success' : (f.triggered ? 'badge-info' : '')); + const statusLabel = f.error ? 'Error' : (f.modified ? 'Modified' : (f.triggered ? 'No change' : 'Skipped')); + return '[' + escapeHtml(f.direction.toUpperCase()) + '] ' + escapeHtml(f.filterName) + ' (' + statusLabel + ')'; + }).join(''); + } } showToast('Revolver pipeline executed successfully!', 'success'); } catch (err) { diff --git a/src/adminRoutes.ts b/src/adminRoutes.ts index ae14dba..6c92d5b 100644 --- a/src/adminRoutes.ts +++ b/src/adminRoutes.ts @@ -1,7 +1,9 @@ import { Router, Request, Response } from 'express'; +import vm from 'vm'; import { configStore } from './configStore'; import { revolverEngine } from './revolverEngine'; -import { ProviderType } from './revolverTypes'; +import { filterEngine, REGEX_FILTER_PRESETS } from './filterEngine'; +import { ProviderType, FilterType } from './revolverTypes'; import { liveWatcher } from './liveWatcher'; import { telemetryTracker } from './telemetryTracker'; import { modelCircuitBreaker } from './modelCircuitBreaker'; @@ -100,7 +102,7 @@ router.post('/providers/:id/test-key', async (req: Request, res: Response) => { // POST /api/admin/models (Create or Update custom model) router.post('/models', (req: Request, res: Response) => { - const { id, name, description, isDefault, tiers } = req.body; + const { id, name, description, isDefault, tiers, filterIds, disableGlobalFilters } = req.body; if (!name || typeof name !== 'string') { res.status(400).json({ error: 'Model name is required.' }); @@ -118,7 +120,9 @@ router.post('/models', (req: Request, res: Response) => { name, description, isDefault, - tiers + tiers, + filterIds: Array.isArray(filterIds) ? filterIds : undefined, + disableGlobalFilters: typeof disableGlobalFilters === 'boolean' ? disableGlobalFilters : undefined }); res.json(saved); } catch (err: any) { @@ -136,6 +140,166 @@ router.delete('/models/:id', (req: Request, res: Response) => { } }); +// POST /api/admin/models/:id/filters (Update a model's ordered filter pipeline) +router.post('/models/:id/filters', (req: Request, res: Response) => { + const { filterIds, disableGlobalFilters } = req.body; + + if (!Array.isArray(filterIds)) { + res.status(400).json({ error: 'filterIds must be an array of filter ID strings.' }); + return; + } + + const updated = configStore.updateModelFilterPipeline( + req.params.id, + filterIds, + typeof disableGlobalFilters === 'boolean' ? disableGlobalFilters : undefined + ); + + if (!updated) { + res.status(404).json({ error: 'Custom model not found.' }); + return; + } + + res.json(updated); +}); + +// GET /api/admin/filters (List all filters, customModels, and regex presets) +router.get('/filters', (req: Request, res: Response) => { + res.json({ + filters: configStore.getFilters(), + customModels: configStore.getCustomModels(), + presets: REGEX_FILTER_PRESETS + }); +}); + +// POST /api/admin/filters (Create or Update a text filter) +router.post('/filters', (req: Request, res: Response) => { + const { + id, + name, + description, + enabled, + isGlobal, + direction, + inputTarget, + streamMode, + triggers, + type, + literalConfig, + regexConfig, + instructionConfig, + scriptConfig, + assignedModelIds + } = req.body; + + if (!name || typeof name !== 'string') { + res.status(400).json({ error: 'Filter name is required.' }); + return; + } + + const validTypes: FilterType[] = ['literal_replace', 'regex_replace', 'instruction_inject', 'custom_script']; + if (!type || !validTypes.includes(type)) { + res.status(400).json({ error: `Invalid filter type. Must be one of: ${validTypes.join(', ')}` }); + return; + } + + // Validate regex syntax if regex_replace + if (type === 'regex_replace' && regexConfig?.pattern) { + try { + new RegExp(regexConfig.pattern, regexConfig.flags || 'g'); + } catch (err: any) { + res.status(400).json({ error: `Invalid regular expression: ${err.message}` }); + return; + } + } + + // Validate custom script JavaScript syntax if custom_script + if (type === 'custom_script' && scriptConfig?.code) { + try { + new vm.Script(`(function(text, messages, context) {\n${scriptConfig.code}\n})`); + } catch (err: any) { + res.status(400).json({ error: `JavaScript syntax error in filter code: ${err.message}` }); + return; + } + } + + // Validate any regex trigger rules + if (triggers && Array.isArray(triggers.rules)) { + for (const r of triggers.rules) { + if ((r.type === 'regex_match' || r.type === 'not_regex_match') && r.value) { + try { + new RegExp(r.value, r.flags || 'i'); + } catch (err: any) { + res.status(400).json({ error: `Invalid trigger regular expression (${r.value}): ${err.message}` }); + return; + } + } + } + } + + try { + const saved = configStore.saveFilter({ + id, + name, + description, + enabled, + isGlobal, + direction, + inputTarget, + streamMode, + triggers, + type, + literalConfig, + regexConfig, + instructionConfig, + scriptConfig, + assignedModelIds + }); + res.json(saved); + } catch (err: any) { + res.status(500).json({ error: err.message || 'Failed to save filter.' }); + } +}); + +// POST /api/admin/filters/reorder (Reorder filter library) +router.post('/filters/reorder', (req: Request, res: Response) => { + const { orderedIds } = req.body; + if (!Array.isArray(orderedIds)) { + res.status(400).json({ error: 'orderedIds must be an array of filter IDs.' }); + return; + } + const reordered = configStore.reorderFilters(orderedIds); + res.json({ filters: reordered }); +}); + +// POST /api/admin/filters/dry-run (Interactive sandbox preview for single filter or model pipeline) +router.post('/filters/dry-run', (req: Request, res: Response) => { + const { customModelId, filtersOverride, sampleMessages, sampleInputText, sampleOutputText } = req.body || {}; + + try { + const result = filterEngine.dryRun({ + customModelId, + filtersOverride: Array.isArray(filtersOverride) ? filtersOverride : undefined, + sampleMessages: Array.isArray(sampleMessages) ? sampleMessages : undefined, + sampleInputText: typeof sampleInputText === 'string' ? sampleInputText : undefined, + sampleOutputText: typeof sampleOutputText === 'string' ? sampleOutputText : undefined + }); + res.json(result); + } catch (err: any) { + res.status(500).json({ error: err.message || 'Filter dry-run failed.' }); + } +}); + +// DELETE /api/admin/filters/:id +router.delete('/filters/:id', (req: Request, res: Response) => { + const deleted = configStore.deleteFilter(req.params.id); + if (deleted) { + res.json({ success: true, message: 'Filter deleted successfully.' }); + } else { + res.status(404).json({ error: 'Filter not found.' }); + } +}); + // POST /api/admin/test-run (Test prompt through Revolver fallback pipeline) router.post('/test-run', async (req: Request, res: Response) => { const { customModelId, customModelName, prompt } = req.body; diff --git a/src/adminView.ts b/src/adminView.ts index d865c6e..f76f464 100644 --- a/src/adminView.ts +++ b/src/adminView.ts @@ -1,5 +1,6 @@ import { renderModelsPage } from './admin/modelsPage'; import { renderProvidersPage } from './admin/providersPage'; +import { renderFiltersPage } from './admin/filtersPage'; import { renderPlaygroundPage } from './admin/playgroundPage'; import { renderTelemetryPage } from './admin/telemetryPage'; import { renderLiveLogsPage } from './admin/liveLogsPage'; @@ -7,6 +8,7 @@ import { renderLiveLogsPage } from './admin/liveLogsPage'; export { renderModelsPage, renderProvidersPage, + renderFiltersPage, renderPlaygroundPage, renderTelemetryPage, renderLiveLogsPage diff --git a/src/configStore.ts b/src/configStore.ts index 26d06ca..5d4a9a5 100644 --- a/src/configStore.ts +++ b/src/configStore.ts @@ -7,7 +7,17 @@ import { ProviderConfig, ProviderKeyConfig, CustomModelConfig, - ProviderType + ProviderType, + TextFilterConfig, + FilterDirection, + FilterType, + FilterInputTarget, + FilterStreamMode, + FilterTriggersConfig, + LiteralReplaceConfig, + RegexReplaceConfig, + InstructionInjectConfig, + CustomScriptConfig } from './revolverTypes'; export class ConfigStore { @@ -16,7 +26,8 @@ export class ConfigStore { version: 1, defaultModelId: undefined, providers: [], - customModels: [] + customModels: [], + filters: [] }; private saveTimeout: NodeJS.Timeout | null = null; @@ -45,7 +56,10 @@ export class ConfigStore { try { const raw = fs.readFileSync(this.configFilePath, 'utf8'); this.data = JSON.parse(raw); - console.log(`[CONFIG_STORE] Loaded configuration from ${this.configFilePath} (${this.data.providers.length} providers, ${this.data.customModels.length} custom models)`); + if (!Array.isArray(this.data.providers)) this.data.providers = []; + if (!Array.isArray(this.data.customModels)) this.data.customModels = []; + if (!Array.isArray(this.data.filters)) this.data.filters = []; + console.log(`[CONFIG_STORE] Loaded configuration from ${this.configFilePath} (${this.data.providers.length} providers, ${this.data.customModels.length} custom models, ${this.data.filters.length} filters)`); return; } catch (err) { console.error(`[CONFIG_STORE] Error reading ${this.configFilePath}, creating backup and re-initializing:`, err); @@ -60,7 +74,8 @@ export class ConfigStore { version: 1, defaultModelId: undefined, providers: [], - customModels: [] + customModels: [], + filters: [] }; // Auto-migrate from .env if GEMINI_API_KEYS are provided @@ -270,6 +285,8 @@ export class ConfigStore { name?: string; targets: { providerId: string; model: string }[]; }[]; + filterIds?: string[]; + disableGlobalFilters?: boolean; }): CustomModelConfig { const now = new Date().toISOString(); const existingIndex = modelInput.id ? this.data.customModels.findIndex(m => m.id === modelInput.id) : -1; @@ -292,12 +309,19 @@ export class ConfigStore { } if (existingIndex >= 0) { + const existing = this.data.customModels[existingIndex]; const updated: CustomModelConfig = { - ...this.data.customModels[existingIndex], + ...existing, name: modelInput.name.trim(), description: modelInput.description?.trim(), isDefault: !!modelInput.isDefault, tiers: processedTiers, + filterIds: Array.isArray(modelInput.filterIds) + ? modelInput.filterIds.map(id => String(id).trim()).filter(Boolean) + : existing.filterIds, + disableGlobalFilters: typeof modelInput.disableGlobalFilters === 'boolean' + ? modelInput.disableGlobalFilters + : existing.disableGlobalFilters, updatedAt: now }; this.data.customModels[existingIndex] = updated; @@ -317,6 +341,10 @@ export class ConfigStore { description: modelInput.description?.trim(), isDefault: isDefault, tiers: processedTiers, + filterIds: Array.isArray(modelInput.filterIds) + ? modelInput.filterIds.map(id => String(id).trim()).filter(Boolean) + : [], + disableGlobalFilters: !!modelInput.disableGlobalFilters, createdAt: now, updatedAt: now }; @@ -345,6 +373,185 @@ export class ConfigStore { return false; } + public getFilters(): TextFilterConfig[] { + if (!Array.isArray(this.data.filters)) { + this.data.filters = []; + } + return this.data.filters; + } + + public getFilterById(id: string): TextFilterConfig | undefined { + return this.getFilters().find(f => f.id === id); + } + + public saveFilter(filterInput: { + id?: string; + name: string; + description?: string; + enabled?: boolean; + isGlobal?: boolean; + direction?: FilterDirection; + inputTarget?: FilterInputTarget; + streamMode?: FilterStreamMode; + triggers?: FilterTriggersConfig; + type: FilterType; + literalConfig?: LiteralReplaceConfig; + regexConfig?: RegexReplaceConfig; + instructionConfig?: InstructionInjectConfig; + scriptConfig?: CustomScriptConfig; + assignedModelIds?: string[]; + }): TextFilterConfig { + const now = new Date().toISOString(); + const filters = this.getFilters(); + const existingIndex = filterInput.id ? filters.findIndex(f => f.id === filterInput.id) : -1; + + const normalizedTriggers: FilterTriggersConfig = filterInput.triggers && Array.isArray(filterInput.triggers.rules) + ? { + matchMode: filterInput.triggers.matchMode === 'any' ? 'any' : 'all', + rules: filterInput.triggers.rules.map(r => ({ + type: r.type || 'always', + value: r.value !== undefined ? String(r.value) : undefined, + flags: r.flags !== undefined ? String(r.flags) : undefined, + caseSensitive: r.caseSensitive + })) + } + : { matchMode: 'all', rules: [{ type: 'always' }] }; + + let savedFilter: TextFilterConfig; + + if (existingIndex >= 0) { + const existing = filters[existingIndex]; + savedFilter = { + ...existing, + name: filterInput.name.trim(), + description: filterInput.description?.trim(), + enabled: filterInput.enabled !== undefined ? !!filterInput.enabled : existing.enabled, + isGlobal: filterInput.isGlobal !== undefined ? !!filterInput.isGlobal : existing.isGlobal, + direction: filterInput.direction || existing.direction || 'output', + inputTarget: filterInput.inputTarget || existing.inputTarget || 'last_user', + streamMode: filterInput.streamMode || existing.streamMode || 'buffer_full', + triggers: normalizedTriggers, + type: filterInput.type, + literalConfig: filterInput.literalConfig ?? existing.literalConfig, + regexConfig: filterInput.regexConfig ?? existing.regexConfig, + instructionConfig: filterInput.instructionConfig ?? existing.instructionConfig, + scriptConfig: filterInput.scriptConfig ?? existing.scriptConfig, + updatedAt: now + }; + filters[existingIndex] = savedFilter; + } else { + const newId = filterInput.id || `flt-${crypto.randomBytes(6).toString('hex')}`; + savedFilter = { + id: newId, + name: filterInput.name.trim(), + description: filterInput.description?.trim(), + enabled: filterInput.enabled !== undefined ? !!filterInput.enabled : true, + isGlobal: !!filterInput.isGlobal, + direction: filterInput.direction || 'output', + inputTarget: filterInput.inputTarget || 'last_user', + streamMode: filterInput.streamMode || 'buffer_full', + triggers: normalizedTriggers, + type: filterInput.type, + literalConfig: filterInput.literalConfig, + regexConfig: filterInput.regexConfig, + instructionConfig: filterInput.instructionConfig, + scriptConfig: filterInput.scriptConfig, + createdAt: now, + updatedAt: now + }; + filters.push(savedFilter); + } + + // If assignedModelIds is explicitly provided, sync model attachments while preserving relative order + if (Array.isArray(filterInput.assignedModelIds)) { + const targetSet = new Set(filterInput.assignedModelIds); + for (const model of this.data.customModels) { + const currentIds = Array.isArray(model.filterIds) ? [...model.filterIds] : []; + const hasId = currentIds.includes(savedFilter.id); + if (targetSet.has(model.id) && !hasId) { + currentIds.push(savedFilter.id); + model.filterIds = currentIds; + model.updatedAt = now; + } else if (!targetSet.has(model.id) && hasId) { + model.filterIds = currentIds.filter(id => id !== savedFilter.id); + model.updatedAt = now; + } + } + } + + this.saveSync(); + return savedFilter; + } + + public deleteFilter(id: string): boolean { + const filters = this.getFilters(); + const initialLen = filters.length; + this.data.filters = filters.filter(f => f.id !== id); + if (this.data.filters.length !== initialLen) { + for (const model of this.data.customModels) { + if (Array.isArray(model.filterIds)) { + model.filterIds = model.filterIds.filter(fid => fid !== id); + } + } + this.saveSync(); + return true; + } + return false; + } + + public reorderFilters(orderedIds: string[]): TextFilterConfig[] { + const filters = this.getFilters(); + const filterMap = new Map(); + for (const f of filters) { + filterMap.set(f.id, f); + } + + const reordered: TextFilterConfig[] = []; + for (const id of orderedIds) { + const f = filterMap.get(id); + if (f) { + reordered.push(f); + filterMap.delete(id); + } + } + // Append any remaining filters that weren't in orderedIds + for (const f of filterMap.values()) { + reordered.push(f); + } + + this.data.filters = reordered; + this.saveSync(); + return this.data.filters; + } + + public updateModelFilterPipeline( + modelId: string, + filterIds: string[], + disableGlobalFilters?: boolean + ): CustomModelConfig | undefined { + const model = this.data.customModels.find(m => m.id === modelId); + if (!model) return undefined; + + const validFilterIds = new Set(this.getFilters().map(f => f.id)); + const seen = new Set(); + const normalizedIds: string[] = []; + for (const fid of filterIds) { + const trimmed = String(fid).trim(); + if (trimmed && validFilterIds.has(trimmed) && !seen.has(trimmed)) { + seen.add(trimmed); + normalizedIds.push(trimmed); + } + } + + model.filterIds = normalizedIds; + if (typeof disableGlobalFilters === 'boolean') { + model.disableGlobalFilters = disableGlobalFilters; + } + model.updatedAt = new Date().toISOString(); + this.saveSync(); + return model; + } + public updateKeyStats( providerId: string, apiKey: string, diff --git a/src/filterEngine.ts b/src/filterEngine.ts new file mode 100644 index 0000000..1396408 --- /dev/null +++ b/src/filterEngine.ts @@ -0,0 +1,840 @@ +import vm from 'vm'; +import { configStore, ConfigStore } from './configStore'; +import { + CustomModelConfig, + TextFilterConfig, + FilterExecutionStepTrace, + FilterTriggerRule +} from './revolverTypes'; +import { OpenAIMessage } from './openaiTypes'; + +export interface RegexPreset { + id: string; + name: string; + description: string; + pattern: string; + flags: string; + replacement: string; + sampleInput: string; +} + +export const REGEX_FILTER_PRESETS: RegexPreset[] = [ + { + id: 'strip_think_tags', + name: 'Strip ... Reasoning Blocks', + description: 'Removes chain-of-thought ... or ... blocks from model outputs.', + pattern: '[\\s\\S]*?<\\/think(?:ing)?>\\s*', + flags: 'gi', + replacement: '', + sampleInput: '\nLet me analyze the user question first...\n\nHere is the final answer!' + }, + { + id: 'strip_markdown_fences', + name: 'Unwrap Markdown Code Fences', + description: 'Strips outer ```language ... ``` code block wrappers while preserving the inner code.', + pattern: '^\\s*```(?:[a-zA-Z0-9_-]+)?\\s*\\n([\\s\\S]*?)\\n?```\\s*$', + flags: 'g', + replacement: '$1', + sampleInput: '```json\n{\n "status": "ok"\n}\n```' + }, + { + id: 'remove_ai_disclaimer', + name: 'Remove "As an AI..." Boilerplate', + description: 'Removes common AI self-reference disclaimers at the start of sentences.', + pattern: '(?:^|\\n)\\s*As an AI(?: language model| assistant)?,?\\s*', + flags: 'gi', + replacement: '\n', + sampleInput: 'As an AI language model, I can help you summarize this article.' + }, + { + id: 'collapse_blank_lines', + name: 'Collapse Excessive Blank Lines', + description: 'Normalizes 3 or more consecutive newlines down to a clean double newline.', + pattern: '\\n{3,}', + flags: 'g', + replacement: '\n\n', + sampleInput: 'Paragraph 1\n\n\n\n\nParagraph 2' + }, + { + id: 'redact_emails', + name: 'Redact Email Addresses', + description: 'Replaces email addresses with [REDACTED_EMAIL].', + pattern: '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}', + flags: 'gi', + replacement: '[REDACTED_EMAIL]', + sampleInput: 'Contact support at alice@example.com or bob.smith@company.org for details.' + }, + { + id: 'redact_api_keys', + name: 'Redact API Keys & Bearer Tokens', + description: 'Masks common API keys (sk-..., AIza..., gsk_...) with [REDACTED_KEY].', + pattern: '\\b(?:sk-[a-zA-Z0-9_-]{16,}|AIza[0-9A-Za-z_-]{25,}|gsk_[a-zA-Z0-9]{20,})\\b', + flags: 'g', + replacement: '[REDACTED_KEY]', + sampleInput: 'Using key AIzaSyD1234567890abcdefghijklmno_pqrstuv and sk-proj-1234567890abcdefghijklmnop' + } +]; + +const VALID_REGEX_FLAGS = new Set(['g', 'i', 'm', 's', 'u']); + +function escapeRegExp(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function sanitizeFlags(flags: string | undefined, ensureGlobal = false): string { + const out = new Set(); + if (flags) { + for (const ch of flags) { + if (VALID_REGEX_FLAGS.has(ch)) out.add(ch); + } + } + if (ensureGlobal) out.add('g'); + return Array.from(out).join(''); +} + +export function extractMessageText(content: any): string { + if (typeof content === 'string') return content; + if (content === null || content === undefined) return ''; + if (Array.isArray(content)) { + return content + .filter((part: any) => part && part.type === 'text' && typeof part.text === 'string') + .map((part: any) => part.text) + .join('\n'); + } + return String(content); +} + +export function updateMessageContent(originalContent: any, newText: string): any { + if (typeof originalContent === 'string' || originalContent === null || originalContent === undefined) { + return newText; + } + if (Array.isArray(originalContent)) { + // Clone array and update the text part(s) while preserving image_url and other multimodal parts + const cloned = JSON.parse(JSON.stringify(originalContent)); + let textUpdated = false; + for (const part of cloned) { + if (part && part.type === 'text') { + part.text = newText; + textUpdated = true; + break; + } + } + if (!textUpdated) { + cloned.unshift({ type: 'text', text: newText }); + } + return cloned; + } + return newText; +} + +function truncatePreview(text: string, maxLen = 240): string { + if (!text) return ''; + if (text.length <= maxLen) return text; + return text.slice(0, maxLen) + '...'; +} + +export class FilterEngine { + private store: ConfigStore; + + constructor(store?: ConfigStore) { + this.store = store || configStore; + } + + /** + * Resolves the ordered list of active filters for a CustomModelConfig and direction. + * Preserves the exact order in customModel.filterIds, and appends any remaining + * enabled Global filters (unless customModel.disableGlobalFilters is true). + */ + public resolveFiltersForModel( + customModel: CustomModelConfig, + direction: 'input' | 'output' + ): TextFilterConfig[] { + const allFilters = this.store.getFilters(); + const filterMap = new Map(); + for (const f of allFilters) { + filterMap.set(f.id, f); + } + + const resolved: TextFilterConfig[] = []; + const seen = new Set(); + + const matchesDirection = (f: TextFilterConfig) => + f.enabled && (f.direction === direction || f.direction === 'both'); + + // 1. Add filters explicitly bound & ordered on the CustomModel + if (Array.isArray(customModel.filterIds)) { + for (const fid of customModel.filterIds) { + const f = filterMap.get(fid); + if (f && !seen.has(f.id)) { + seen.add(f.id); + if (matchesDirection(f)) { + resolved.push(f); + } + } + } + } + + // 2. Add any enabled Global filters not already positioned in customModel.filterIds + if (!customModel.disableGlobalFilters) { + for (const f of allFilters) { + if (f.isGlobal && !seen.has(f.id)) { + seen.add(f.id); + if (matchesDirection(f)) { + resolved.push(f); + } + } + } + } + + return resolved; + } + + /** + * Determines how streaming (SSE) output should be handled for a Custom Model. + * - 'none': no active output filters + * - 'buffer_full': at least one active output filter uses smart full buffering + * - 'chunk_by_chunk': active output filters only use chunk-by-chunk mode + */ + public getStreamingStrategy(customModel: CustomModelConfig): { + mode: 'none' | 'buffer_full' | 'chunk_by_chunk'; + filters: TextFilterConfig[]; + } { + const filters = this.resolveFiltersForModel(customModel, 'output'); + if (filters.length === 0) { + return { mode: 'none', filters: [] }; + } + + const needsFullBuffer = filters.some(f => (f.streamMode || 'buffer_full') === 'buffer_full'); + return { + mode: needsFullBuffer ? 'buffer_full' : 'chunk_by_chunk', + filters + }; + } + + /** + * Evaluates a single trigger rule against targetText and messages. + */ + private evaluateSingleTriggerRule( + rule: FilterTriggerRule, + targetText: string, + messages: OpenAIMessage[] + ): boolean { + const type = rule.type || 'always'; + const val = rule.value ?? ''; + + switch (type) { + case 'always': + return true; + + case 'contains': { + if (!val) return true; + if (rule.caseSensitive) { + return targetText.includes(val); + } + return targetText.toLowerCase().includes(val.toLowerCase()); + } + + case 'not_contains': { + if (!val) return true; + if (rule.caseSensitive) { + return !targetText.includes(val); + } + return !targetText.toLowerCase().includes(val.toLowerCase()); + } + + case 'regex_match': { + if (!val) return true; + try { + const flags = sanitizeFlags(rule.flags || (rule.caseSensitive ? '' : 'i')); + const re = new RegExp(val, flags); + return re.test(targetText); + } catch { + return false; + } + } + + case 'not_regex_match': { + if (!val) return true; + try { + const flags = sanitizeFlags(rule.flags || (rule.caseSensitive ? '' : 'i')); + const re = new RegExp(val, flags); + return !re.test(targetText); + } catch { + return false; + } + } + + case 'length_gt': { + const threshold = Number(val) || 0; + return targetText.length > threshold; + } + + case 'length_lt': { + const threshold = Number(val) || 0; + return targetText.length < threshold; + } + + case 'no_system_prompt': { + const hasSystem = messages.some( + m => m.role === 'system' && extractMessageText(m.content).trim().length > 0 + ); + return !hasSystem; + } + + case 'message_count_gt': { + const threshold = Number(val) || 0; + return messages.length > threshold; + } + + default: + return true; + } + } + + /** + * Evaluates all trigger rules for a filter using AND ('all') or OR ('any') logic. + */ + public evaluateTriggers( + filter: TextFilterConfig, + targetText: string, + messages: OpenAIMessage[] + ): boolean { + const triggers = filter.triggers; + if (!triggers || !Array.isArray(triggers.rules) || triggers.rules.length === 0) { + return true; + } + + if (triggers.matchMode === 'any') { + return triggers.rules.some(rule => this.evaluateSingleTriggerRule(rule, targetText, messages)); + } + + return triggers.rules.every(rule => this.evaluateSingleTriggerRule(rule, targetText, messages)); + } + + private interpolateTemplate( + template: string, + context: { + originalText: string; + modelName: string; + } + ): string { + const now = new Date(); + const dateStr = now.toISOString().slice(0, 10); + const isoStr = now.toISOString(); + + return template + .replace(/\{\{\s*(?:original_text|input|text)\s*\}\}/gi, () => context.originalText) + .replace(/\{\{\s*model\s*\}\}/gi, () => context.modelName) + .replace(/\{\{\s*date\s*\}\}/gi, () => dateStr) + .replace(/\{\{\s*iso_timestamp\s*\}\}/gi, () => isoStr); + } + + /** + * Applies a single filter's transformation logic to `text` (and optionally `messages`). + */ + public executeFilterTransform(params: { + filter: TextFilterConfig; + text: string; + messages: OpenAIMessage[]; + direction: 'input' | 'output'; + modelName: string; + role?: string; + messageIndex?: number; + }): { text: string; messages: OpenAIMessage[] } { + const { filter, messages, direction, modelName, role, messageIndex } = params; + let currentText = params.text; + + switch (filter.type) { + case 'literal_replace': { + const cfg = filter.literalConfig; + if (!cfg || !Array.isArray(cfg.rules)) break; + const flags = cfg.caseSensitive ? 'g' : 'gi'; + + for (const rule of cfg.rules) { + if (!rule || !rule.find) continue; + const escaped = escapeRegExp(rule.find); + const pattern = cfg.wholeWord ? `\\b${escaped}\\b` : escaped; + const re = new RegExp(pattern, flags); + currentText = currentText.replace(re, () => rule.replace ?? ''); + } + break; + } + + case 'regex_replace': { + const cfg = filter.regexConfig; + if (!cfg || !cfg.pattern) break; + const flags = sanitizeFlags(cfg.flags || 'g'); + const re = new RegExp(cfg.pattern, flags); + currentText = currentText.replace(re, cfg.replacement ?? ''); + break; + } + + case 'instruction_inject': { + const cfg = filter.instructionConfig; + if (!cfg || !cfg.content) break; + const sep = cfg.separator !== undefined ? cfg.separator : '\n\n'; + const hasPlaceholder = /\{\{\s*(?:original_text|input|text)\s*\}\}/i.test(cfg.content); + const interpolated = this.interpolateTemplate(cfg.content, { + originalText: currentText, + modelName + }); + + if (direction === 'input' && (cfg.position === 'prepend_system' || cfg.position === 'append_system')) { + const sysIdx = messages.findIndex(m => m.role === 'system'); + if (sysIdx >= 0) { + const existingSys = String(messages[sysIdx].content || ''); + messages[sysIdx].content = cfg.position === 'prepend_system' + ? (existingSys ? `${interpolated}${sep}${existingSys}` : interpolated) + : (existingSys ? `${existingSys}${sep}${interpolated}` : interpolated); + } else { + messages.unshift({ + role: 'system', + content: interpolated + }); + } + } else if (cfg.position === 'prepend_target' || cfg.position === 'prepend_system') { + currentText = hasPlaceholder + ? interpolated + : (currentText ? `${interpolated}${sep}${currentText}` : interpolated); + } else if (cfg.position === 'append_target' || cfg.position === 'append_system') { + currentText = hasPlaceholder + ? interpolated + : (currentText ? `${currentText}${sep}${interpolated}` : interpolated); + } else if (cfg.position === 'wrap_target') { + const suffixInterpolated = cfg.wrapSuffix + ? this.interpolateTemplate(cfg.wrapSuffix, { originalText: currentText, modelName }) + : ''; + if (hasPlaceholder) { + currentText = suffixInterpolated ? `${interpolated}${sep}${suffixInterpolated}` : interpolated; + } else { + currentText = `${interpolated}${sep}${currentText}${suffixInterpolated ? `${sep}${suffixInterpolated}` : ''}`; + } + } + break; + } + + case 'custom_script': { + const cfg = filter.scriptConfig; + if (!cfg || !cfg.code || !cfg.code.trim()) break; + const timeoutMs = Math.min(Math.max(cfg.timeoutMs || 500, 50), 2000); + + const clonedMessages: OpenAIMessage[] = JSON.parse(JSON.stringify(messages)); + const sandboxContext = { + text: currentText, + messages: clonedMessages, + context: { + direction, + model: modelName, + role: role || (direction === 'output' ? 'assistant' : 'user'), + messageIndex: messageIndex ?? -1, + timestamp: new Date().toISOString() + }, + replaceAll: (str: string, find: string, replace: string) => + String(str || '').split(String(find)).join(String(replace ?? '')), + replaceRegex: (str: string, pattern: string, flags: string, replacement: string) => + String(str || '').replace(new RegExp(pattern, sanitizeFlags(flags)), String(replacement ?? '')), + prependSystem: (instruction: string) => { + const idx = clonedMessages.findIndex(m => m.role === 'system'); + if (idx >= 0) { + clonedMessages[idx].content = clonedMessages[idx].content + ? `${instruction}\n\n${clonedMessages[idx].content}` + : instruction; + } else { + clonedMessages.unshift({ role: 'system', content: instruction }); + } + }, + appendSystem: (instruction: string) => { + const idx = clonedMessages.findIndex(m => m.role === 'system'); + if (idx >= 0) { + clonedMessages[idx].content = clonedMessages[idx].content + ? `${clonedMessages[idx].content}\n\n${instruction}` + : instruction; + } else { + clonedMessages.unshift({ role: 'system', content: instruction }); + } + }, + JSON, + Math, + Date, + RegExp, + String, + Number, + Boolean, + Array, + Object, + parseInt, + parseFloat, + encodeURIComponent, + decodeURIComponent + }; + + const wrappedScript = `(function(text, messages, context) {\n${cfg.code}\n})(text, messages, context)`; + const result = vm.runInNewContext(wrappedScript, sandboxContext, { + timeout: timeoutMs, + displayErrors: true + }); + + if (typeof result === 'string') { + currentText = result; + } else if (result && typeof result === 'object') { + if (typeof result.text === 'string') { + currentText = result.text; + } + if (Array.isArray(result.messages)) { + messages.splice(0, messages.length, ...result.messages); + return { text: currentText, messages }; + } + } else if (typeof sandboxContext.text === 'string' && sandboxContext.text !== params.text) { + currentText = sandboxContext.text; + } + + // Propagate any direct mutations made to clonedMessages (such as prependSystem / appendSystem) + messages.splice(0, messages.length, ...clonedMessages); + break; + } + } + + return { text: currentText, messages }; + } + + /** + * Resolves which message indices in `messages` are targeted by an input filter. + */ + private getTargetMessageIndices(messages: OpenAIMessage[], inputTarget: string | undefined): number[] { + const target = inputTarget || 'last_user'; + const indices: number[] = []; + + if (target === 'last_user') { + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].role === 'user') { + return [i]; + } + } + if (messages.length > 0) { + return [messages.length - 1]; + } + return []; + } + + for (let i = 0; i < messages.length; i++) { + const role = messages[i].role; + if ( + target === 'all_messages' || + (target === 'all_user' && role === 'user') || + (target === 'system' && role === 'system') || + (target === 'assistant' && role === 'assistant') + ) { + indices.push(i); + } + } + + return indices; + } + + /** + * Applies all ordered Input Filters for a CustomModel to the request's messages array. + */ + public applyInputFilters(params: { + messages: OpenAIMessage[]; + customModel: CustomModelConfig; + filtersOverride?: TextFilterConfig[]; + }): { + messages: OpenAIMessage[]; + traces: FilterExecutionStepTrace[]; + modified: boolean; + } { + const { customModel, filtersOverride } = params; + const messages: OpenAIMessage[] = JSON.parse(JSON.stringify(params.messages || [])); + const traces: FilterExecutionStepTrace[] = []; + let anyModified = false; + + const filters = filtersOverride + ? filtersOverride.filter(f => f.enabled && (f.direction === 'input' || f.direction === 'both')) + : this.resolveFiltersForModel(customModel, 'input'); + + for (const filter of filters) { + const startTime = Date.now(); + const beforeSnapshot = JSON.stringify(messages); + const targetIndices = this.getTargetMessageIndices(messages, filter.inputTarget); + + // Compute combined target text for trigger evaluation + const combinedTargetText = targetIndices.length > 0 + ? targetIndices.map(idx => extractMessageText(messages[idx]?.content)).join('\n') + : messages.map(m => extractMessageText(m.content)).join('\n'); + + try { + const triggered = this.evaluateTriggers(filter, combinedTargetText, messages); + if (!triggered) { + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'input', + triggered: false, + modified: false, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(combinedTargetText), + afterPreview: truncatePreview(combinedTargetText) + }); + continue; + } + + // Special handling when instruction_inject targets system prompt directly or when targetIndices is empty (e.g., no system message yet) + const isSystemDirective = + filter.type === 'instruction_inject' && + (filter.instructionConfig?.position === 'prepend_system' || + filter.instructionConfig?.position === 'append_system'); + + if (isSystemDirective || (filter.inputTarget === 'system' && targetIndices.length === 0)) { + this.executeFilterTransform({ + filter, + text: combinedTargetText, + messages, + direction: 'input', + modelName: customModel.name, + role: 'system', + messageIndex: 0 + }); + } else { + let cumulativeOffset = 0; + for (const origIdx of targetIndices) { + const currentIdx = origIdx + cumulativeOffset; + if (!messages[currentIdx]) continue; + const originalMsgText = extractMessageText(messages[currentIdx].content); + + const prevLen = messages.length; + const res = this.executeFilterTransform({ + filter, + text: originalMsgText, + messages, + direction: 'input', + modelName: customModel.name, + role: messages[currentIdx].role, + messageIndex: currentIdx + }); + + // Adjust index if system/other messages were inserted + const added = messages.length - prevLen; + cumulativeOffset += added; + const targetIndexInUpdated = currentIdx + added; + if (messages[targetIndexInUpdated]) { + messages[targetIndexInUpdated].content = updateMessageContent( + messages[targetIndexInUpdated].content, + res.text + ); + } + } + } + + const afterSnapshot = JSON.stringify(messages); + const modified = beforeSnapshot !== afterSnapshot; + if (modified) anyModified = true; + + const updatedTargetIndices = this.getTargetMessageIndices(messages, filter.inputTarget); + const afterTargetText = isSystemDirective + ? String(messages.find(m => m.role === 'system')?.content ?? '') + : (updatedTargetIndices.length > 0 + ? updatedTargetIndices.map(idx => String(messages[idx]?.content ?? '')).join('\n') + : messages.map(m => String(m.content ?? '')).join('\n')); + + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'input', + triggered: true, + modified, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(combinedTargetText), + afterPreview: truncatePreview(afterTargetText) + }); + } catch (err: any) { + console.error(`[FILTER_ENGINE] Input filter '${filter.name}' (${filter.id}) error:`, err?.message || err); + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'input', + triggered: true, + modified: false, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(combinedTargetText), + afterPreview: truncatePreview(combinedTargetText), + error: err?.message || String(err) + }); + } + } + + return { messages, traces, modified: anyModified }; + } + + /** + * Applies ordered Output Filters for a CustomModel to the completion text. + */ + public applyOutputFilters(params: { + text: string; + customModel: CustomModelConfig; + messages?: OpenAIMessage[]; + filtersOverride?: TextFilterConfig[]; + onlyChunkByChunk?: boolean; + }): { + text: string; + traces: FilterExecutionStepTrace[]; + modified: boolean; + } { + const { customModel, filtersOverride, onlyChunkByChunk } = params; + let currentText = params.text ?? ''; + const contextMessages = params.messages || []; + const traces: FilterExecutionStepTrace[] = []; + let anyModified = false; + + let filters = filtersOverride + ? filtersOverride.filter(f => f.enabled && (f.direction === 'output' || f.direction === 'both')) + : this.resolveFiltersForModel(customModel, 'output'); + + if (onlyChunkByChunk) { + filters = filters.filter(f => f.streamMode === 'chunk_by_chunk'); + } + + for (const filter of filters) { + const startTime = Date.now(); + const beforeText = currentText; + + try { + const triggered = this.evaluateTriggers(filter, beforeText, contextMessages); + if (!triggered) { + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'output', + triggered: false, + modified: false, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(beforeText), + afterPreview: truncatePreview(beforeText) + }); + continue; + } + + const res = this.executeFilterTransform({ + filter, + text: beforeText, + messages: [...contextMessages], + direction: 'output', + modelName: customModel.name, + role: 'assistant' + }); + + currentText = res.text; + const modified = currentText !== beforeText; + if (modified) anyModified = true; + + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'output', + triggered: true, + modified, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(beforeText), + afterPreview: truncatePreview(currentText) + }); + } catch (err: any) { + console.error(`[FILTER_ENGINE] Output filter '${filter.name}' (${filter.id}) error:`, err?.message || err); + traces.push({ + filterId: filter.id, + filterName: filter.name, + filterType: filter.type, + direction: 'output', + triggered: true, + modified: false, + durationMs: Date.now() - startTime, + beforePreview: truncatePreview(beforeText), + afterPreview: truncatePreview(beforeText), + error: err?.message || String(err) + }); + } + } + + return { text: currentText, traces, modified: anyModified }; + } + + /** + * Dry-Run Sandbox for testing either a single filter draft or a full model's pipeline + * on sample input messages and sample output text without calling upstream LLM APIs. + */ + public dryRun(params: { + customModelId?: string; + filtersOverride?: TextFilterConfig[]; + sampleMessages?: OpenAIMessage[]; + sampleInputText?: string; + sampleOutputText?: string; + }): { + modelName: string; + inputResult: { + beforeMessages: OpenAIMessage[]; + afterMessages: OpenAIMessage[]; + traces: FilterExecutionStepTrace[]; + modified: boolean; + }; + outputResult: { + beforeText: string; + afterText: string; + traces: FilterExecutionStepTrace[]; + modified: boolean; + }; + } { + let customModel = params.customModelId + ? this.store.getCustomModelById(params.customModelId) + : this.store.getDefaultModel(); + + if (!customModel) { + customModel = { + id: 'sandbox-model', + name: 'sandbox-model', + tiers: [], + filterIds: [], + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString() + }; + } + + const initialMessages: OpenAIMessage[] = Array.isArray(params.sampleMessages) && params.sampleMessages.length > 0 + ? JSON.parse(JSON.stringify(params.sampleMessages)) + : [{ role: 'user', content: params.sampleInputText ?? '' }]; + + const inputRes = this.applyInputFilters({ + messages: initialMessages, + customModel, + filtersOverride: params.filtersOverride + }); + + const beforeOutputText = params.sampleOutputText ?? ''; + const outputRes = this.applyOutputFilters({ + text: beforeOutputText, + customModel, + messages: inputRes.messages, + filtersOverride: params.filtersOverride + }); + + return { + modelName: customModel.name, + inputResult: { + beforeMessages: initialMessages, + afterMessages: inputRes.messages, + traces: inputRes.traces, + modified: inputRes.modified + }, + outputResult: { + beforeText: beforeOutputText, + afterText: outputRes.text, + traces: outputRes.traces, + modified: outputRes.modified + } + }; + } +} + +export const filterEngine = new FilterEngine(); diff --git a/src/liveWatcher.ts b/src/liveWatcher.ts index 3139731..0306844 100644 --- a/src/liveWatcher.ts +++ b/src/liveWatcher.ts @@ -1,5 +1,6 @@ import { Response } from 'express'; import { FallbackStep, RequestFallbackJourney } from './telemetryTracker'; +import { FilterExecutionStepTrace } from './revolverTypes'; export type LiveRequestStatus = 'streaming' | 'completed' | 'fallback_completed' | 'failed' | 'cancelled'; @@ -31,6 +32,7 @@ export interface LiveRequestMetadata { resolvedCustomModelName?: string; totalCandidatesAttempted: number; fallbackOccurred: boolean; + appliedFilters?: FilterExecutionStepTrace[]; servedBy?: { tierIndex: number; tierName: string; @@ -275,6 +277,53 @@ export class LiveWatcher { }); } + public recordFilterTraces( + requestId: string, + direction: 'input' | 'output', + traces: FilterExecutionStepTrace[], + updatedMessages?: any[] + ): void { + if (!this.isWatcherActive || !traces || traces.length === 0) return; + const entry = this.buffer.find(e => e.id === requestId); + if (!entry) return; + + if (!Array.isArray(entry.metadata.appliedFilters)) { + entry.metadata.appliedFilters = []; + } + entry.metadata.appliedFilters.push(...traces); + + if (direction === 'input' && Array.isArray(updatedMessages)) { + entry.input.messages = updatedMessages; + } + + const triggeredCount = traces.filter(t => t.triggered).length; + const modifiedCount = traces.filter(t => t.modified).length; + + entry.debug.events.push({ + time: new Date().toISOString(), + message: `${direction.toUpperCase()} filters executed: ${traces.length} evaluated (${triggeredCount} triggered, ${modifiedCount} modified text)`, + level: traces.some(t => t.error) ? 'warn' : 'info', + details: { + direction, + traces: traces.map(t => ({ + name: t.filterName, + type: t.filterType, + triggered: t.triggered, + modified: t.modified, + durationMs: t.durationMs, + error: t.error + })) + } + }); + + this.broadcast({ + type: 'filter_traces', + requestId, + direction, + traces + }); + } + public recordKeepAlive(requestId: string, type: 'sse_comment' | 'whitespace'): void { if (!this.isWatcherActive) return; const entry = this.buffer.find(e => e.id === requestId); diff --git a/src/revolverEngine.ts b/src/revolverEngine.ts index d8ea6e9..3b1f609 100644 --- a/src/revolverEngine.ts +++ b/src/revolverEngine.ts @@ -8,12 +8,14 @@ import { ProviderKeyConfig, ModelTarget, FallbackTier, - ExecutionDiagnosticTrace + ExecutionDiagnosticTrace, + FilterExecutionStepTrace } from './revolverTypes'; import { OpenAIChatRequest, OpenAIChatResponse } from './openaiTypes'; import { telemetryTracker, FallbackStep, RequestFallbackJourney } from './telemetryTracker'; import { liveWatcher } from './liveWatcher'; import { modelCircuitBreaker } from './modelCircuitBreaker'; +import { FilterEngine } from './filterEngine'; export const GEMINI_SAFETY_SETTINGS_BLOCK_NONE = [ { @@ -44,12 +46,14 @@ interface CandidateExecution { export class RevolverEngine { private store: ConfigStore; + private filterEngine: FilterEngine; private geminiClients: Map = new Map(); // Per-tier round-robin pointer: Map<`${modelId}_tier_${tierIndex}`, number> private roundRobinPointers: Map = new Map(); constructor(store?: ConfigStore) { this.store = store || configStore; + this.filterEngine = new FilterEngine(this.store); } private getGeminiClient(apiKey: string): GoogleGenerativeAI { @@ -321,6 +325,19 @@ export class RevolverEngine { const { requestBody, requestId, res, isStreaming, onSuccess, onFailure, onCancelled } = params; const { customModel, requestedModelName } = this.resolveCustomModel(requestBody.model); + // Apply Input Text Processing Filters before routing to candidates + const inputFilterResult = this.filterEngine.applyInputFilters({ + messages: requestBody.messages || [], + customModel + }); + const processedRequestBody: OpenAIChatRequest = { + ...requestBody, + messages: inputFilterResult.messages + }; + if (inputFilterResult.traces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'input', inputFilterResult.traces, inputFilterResult.messages); + } + let streamStarted = false; let isCancelled = false; let keepAliveTimer: NodeJS.Timeout | null = null; @@ -462,7 +479,8 @@ export class RevolverEngine { if (isStreaming) { const streamResult = await this.executeStreaming({ candidate, - requestBody, + requestBody: processedRequestBody, + customModel, requestedModelName, requestId, res, @@ -496,7 +514,7 @@ export class RevolverEngine { fallbackSteps.push(successStep); liveWatcher.recordCandidateStep(requestId, successStep); - const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(requestBody.messages).length / 4); + const promptTokens = streamResult?.promptTokens || Math.ceil(JSON.stringify(processedRequestBody.messages).length / 4); const completionTokens = streamResult?.completionTokens || 0; const journey: RequestFallbackJourney = { requestId, @@ -537,7 +555,8 @@ export class RevolverEngine { } else { const responseData = await this.executeNonStreaming({ candidate, - requestBody, + requestBody: processedRequestBody, + customModel, requestedModelName, requestId }); @@ -890,26 +909,52 @@ export class RevolverEngine { private async executeNonStreaming(params: { candidate: CandidateExecution; requestBody: OpenAIChatRequest; + customModel?: CustomModelConfig; requestedModelName: string; requestId: string; + onOutputFilterTraces?: (traces: FilterExecutionStepTrace[]) => void; }): Promise { - const { candidate, requestBody, requestedModelName, requestId } = params; + const { candidate, requestBody, customModel, requestedModelName, requestId, onOutputFilterTraces } = params; + let responseData: OpenAIChatResponse; if (candidate.provider.type === 'gemini') { - return this.executeGeminiNonStreaming({ + responseData = await this.executeGeminiNonStreaming({ candidate, requestBody, requestedModelName, requestId }); } else { - return this.executeOpenAICompatibleNonStreaming({ + responseData = await this.executeOpenAICompatibleNonStreaming({ candidate, requestBody, requestedModelName, requestId }); } + + if (customModel && responseData.choices?.[0]?.message) { + const rawContent = responseData.choices[0].message.content || ''; + const outputFilterResult = this.filterEngine.applyOutputFilters({ + text: rawContent, + customModel, + messages: requestBody.messages + }); + responseData.choices[0].message.content = outputFilterResult.text; + if (outputFilterResult.modified && responseData.usage) { + const adjustedCompletionTokens = Math.ceil(outputFilterResult.text.length / 4); + responseData.usage.completion_tokens = adjustedCompletionTokens; + responseData.usage.total_tokens = (responseData.usage.prompt_tokens || 0) + adjustedCompletionTokens; + } + if (outputFilterResult.traces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'output', outputFilterResult.traces); + if (onOutputFilterTraces) { + onOutputFilterTraces(outputFilterResult.traces); + } + } + } + + return responseData; } private async executeGeminiNonStreaming(params: { @@ -1083,6 +1128,7 @@ export class RevolverEngine { private async executeStreaming(params: { candidate: CandidateExecution; requestBody: OpenAIChatRequest; + customModel?: CustomModelConfig; requestedModelName: string; requestId: string; res: Response; @@ -1092,12 +1138,13 @@ export class RevolverEngine { details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } ) => void; }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; + const { candidate, requestBody, customModel, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; if (candidate.provider.type === 'gemini') { return this.executeGeminiStreaming({ candidate, requestBody, + customModel, requestedModelName, requestId, res, @@ -1108,6 +1155,7 @@ export class RevolverEngine { return this.executeOpenAICompatibleStreaming({ candidate, requestBody, + customModel, requestedModelName, requestId, res, @@ -1120,6 +1168,7 @@ export class RevolverEngine { private async executeGeminiStreaming(params: { candidate: CandidateExecution; requestBody: OpenAIChatRequest; + customModel?: CustomModelConfig; requestedModelName: string; requestId: string; res: Response; @@ -1129,7 +1178,7 @@ export class RevolverEngine { details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } ) => void; }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; + const { candidate, requestBody, customModel, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const genAI = this.getGeminiClient(candidate.keyConfig.key); const { systemInstruction, geminiMessages } = this.convertToGeminiContent(requestBody.messages); @@ -1166,6 +1215,10 @@ export class RevolverEngine { let fullContent = ''; let promptTokens = 0; let completionTokens = 0; + const streamStrategy = customModel + ? this.filterEngine.getStreamingStrategy(customModel) + : { mode: 'none' as const, filters: [] }; + const collectedChunkTraces: FilterExecutionStepTrace[] = []; const streamIterator = result.stream[Symbol.asyncIterator](); @@ -1203,18 +1256,26 @@ export class RevolverEngine { } } - if (!firstResult.done && firstResult.value) { - let text = ''; - try { - text = firstResult.value.text(); - } catch (err: any) { - if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { - throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); - } - throw err; + const handleGeminiChunk = (rawChunkText: string) => { + if (streamStrategy.mode === 'buffer_full') { + fullContent += rawChunkText; + return; } - fullContent += text; - liveWatcher.appendStreamChunk(requestId, text); + + let emittedText = rawChunkText; + if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { + const chunkRes = this.filterEngine.applyOutputFilters({ + text: rawChunkText, + customModel, + messages: requestBody.messages, + onlyChunkByChunk: true + }); + emittedText = chunkRes.text; + collectedChunkTraces.push(...chunkRes.traces); + } + + fullContent += emittedText; + liveWatcher.appendStreamChunk(requestId, emittedText); onStreamStart(); const chunkResponse = { @@ -1225,13 +1286,26 @@ export class RevolverEngine { choices: [ { index: 0, - delta: { content: text }, + delta: { content: emittedText }, finish_reason: null } ] }; res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); + }; + + if (!firstResult.done && firstResult.value) { + let text = ''; + try { + text = firstResult.value.text(); + } catch (err: any) { + if (err?.message?.includes('SAFETY') || err?.message?.includes('blocked')) { + throw new Error(`Gemini stream blocked by upstream safety policy: ${err.message}`); + } + throw err; + } + handleGeminiChunk(text); } while (true) { @@ -1248,25 +1322,39 @@ export class RevolverEngine { } throw err; } - fullContent += text; - liveWatcher.appendStreamChunk(requestId, text); - onStreamStart(); + handleGeminiChunk(text); + } - const chunkResponse = { - id: `chatcmpl-${requestId}`, - object: 'chat.completion.chunk', - created: Math.floor(Date.now() / 1000), - model: requestedModelName, - choices: [ - { - index: 0, - delta: { content: text }, - finish_reason: null - } - ] - }; - - res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); + if (streamStrategy.mode === 'buffer_full' && customModel) { + const outputFilterResult = this.filterEngine.applyOutputFilters({ + text: fullContent, + customModel, + messages: requestBody.messages + }); + fullContent = outputFilterResult.text; + if (outputFilterResult.traces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'output', outputFilterResult.traces); + } + if (!res.destroyed) { + liveWatcher.appendStreamChunk(requestId, fullContent); + onStreamStart(); + const chunkResponse = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModelName, + choices: [ + { + index: 0, + delta: { role: 'assistant', content: fullContent }, + finish_reason: null + } + ] + }; + res.write(`data: ${JSON.stringify(chunkResponse)}\n\n`); + } + } else if (collectedChunkTraces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'output', collectedChunkTraces); } if (!res.destroyed) { @@ -1289,16 +1377,22 @@ export class RevolverEngine { } // Try to get token counts from final response + let rawCandidatesTokens = 0; try { const finalResp = await result.response; if (finalResp?.usageMetadata) { promptTokens = finalResp.usageMetadata.promptTokenCount || 0; - completionTokens = finalResp.usageMetadata.candidatesTokenCount || 0; + rawCandidatesTokens = finalResp.usageMetadata.candidatesTokenCount || 0; } } catch {} + if (streamStrategy.mode === 'buffer_full') { + completionTokens = Math.ceil(fullContent.length / 4); + } else { + completionTokens = rawCandidatesTokens || Math.ceil(fullContent.length / 4); + } + if (!promptTokens) promptTokens = Math.ceil(JSON.stringify(requestBody.messages).length / 4); - if (!completionTokens) completionTokens = Math.ceil(fullContent.length / 4); this.store.updateKeyStats(candidate.provider.id, candidate.keyConfig.key, { incrementCount: true, @@ -1323,6 +1417,7 @@ export class RevolverEngine { private async executeOpenAICompatibleStreaming(params: { candidate: CandidateExecution; requestBody: OpenAIChatRequest; + customModel?: CustomModelConfig; requestedModelName: string; requestId: string; res: Response; @@ -1332,7 +1427,7 @@ export class RevolverEngine { details?: { completionText: string; finishReason: string; responseData?: OpenAIChatResponse } ) => void; }): Promise<{ promptTokens: number; completionTokens: number; finishReason: string; completionText: string }> { - const { candidate, requestBody, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; + const { candidate, requestBody, customModel, requestedModelName, requestId, res, onStreamStart, onSuccess } = params; const baseUrl = (candidate.provider.baseUrl || this.store.getDefaultBaseUrl(candidate.provider.type)).replace(/\/+$/, ''); const url = `${baseUrl}/chat/completions`; @@ -1393,6 +1488,10 @@ export class RevolverEngine { let fullContent = ''; let finishReason = 'stop'; let streamHasStarted = false; + const streamStrategy = customModel + ? this.filterEngine.getStreamingStrategy(customModel) + : { mode: 'none' as const, filters: [] }; + const collectedChunkTraces: FilterExecutionStepTrace[] = []; const processText = (textChunk: string) => { buffer += textChunk; @@ -1402,14 +1501,18 @@ export class RevolverEngine { for (const line of lines) { const trimmed = line.trim(); if (!trimmed) { - res.write('\n'); + if (streamStrategy.mode !== 'buffer_full') { + res.write('\n'); + } continue; } if (trimmed.startsWith('data: ')) { const dataStr = trimmed.slice(6); if (dataStr === '[DONE]') { - res.write('data: [DONE]\n\n'); + if (streamStrategy.mode !== 'buffer_full') { + res.write('data: [DONE]\n\n'); + } continue; } @@ -1420,18 +1523,41 @@ export class RevolverEngine { finishReason = parsed.choices[0].finish_reason; } if (parsed.choices?.[0]?.delta?.content) { + const rawDelta = parsed.choices[0].delta.content; + if (streamStrategy.mode === 'buffer_full') { + fullContent += rawDelta; + totalOutputChars += rawDelta.length; + continue; + } + + let emittedDelta = rawDelta; + if (streamStrategy.mode === 'chunk_by_chunk' && customModel) { + const chunkRes = this.filterEngine.applyOutputFilters({ + text: rawDelta, + customModel, + messages: requestBody.messages, + onlyChunkByChunk: true + }); + emittedDelta = chunkRes.text; + parsed.choices[0].delta.content = emittedDelta; + collectedChunkTraces.push(...chunkRes.traces); + } + onStreamStart(); streamHasStarted = true; - const delta = parsed.choices[0].delta.content; - totalOutputChars += delta.length; - fullContent += delta; - liveWatcher.appendStreamChunk(requestId, delta); + totalOutputChars += emittedDelta.length; + fullContent += emittedDelta; + liveWatcher.appendStreamChunk(requestId, emittedDelta); + } + if (streamStrategy.mode !== 'buffer_full') { + res.write(`data: ${JSON.stringify(parsed)}\n\n`); } - res.write(`data: ${JSON.stringify(parsed)}\n\n`); } catch { - res.write(`${line}\n`); + if (streamStrategy.mode !== 'buffer_full') { + res.write(`${line}\n`); + } } - } else { + } else if (streamStrategy.mode !== 'buffer_full') { res.write(`${line}\n`); } } @@ -1475,6 +1601,62 @@ export class RevolverEngine { processText(text); } + // Flush any remaining partial line in buffer + if (buffer.trim()) { + processText('\n'); + } + + if (streamStrategy.mode === 'buffer_full' && customModel) { + const outputFilterResult = this.filterEngine.applyOutputFilters({ + text: fullContent, + customModel, + messages: requestBody.messages + }); + fullContent = outputFilterResult.text; + totalOutputChars = fullContent.length; + if (outputFilterResult.traces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'output', outputFilterResult.traces); + } + + if (!res.destroyed) { + onStreamStart(); + streamHasStarted = true; + liveWatcher.appendStreamChunk(requestId, fullContent); + const contentChunk = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModelName, + choices: [ + { + index: 0, + delta: { role: 'assistant', content: fullContent }, + finish_reason: null + } + ] + }; + res.write(`data: ${JSON.stringify(contentChunk)}\n\n`); + + const finalChunk = { + id: `chatcmpl-${requestId}`, + object: 'chat.completion.chunk', + created: Math.floor(Date.now() / 1000), + model: requestedModelName, + choices: [ + { + index: 0, + delta: {}, + finish_reason: finishReason || 'stop' + } + ] + }; + res.write(`data: ${JSON.stringify(finalChunk)}\n\n`); + res.write('data: [DONE]\n\n'); + } + } else if (collectedChunkTraces.length > 0) { + liveWatcher.recordFilterTraces(requestId, 'output', collectedChunkTraces); + } + if (!res.destroyed) { res.end(); } @@ -1528,6 +1710,11 @@ export class RevolverEngine { throw new Error('No custom model found to test.'); } + const inputFilterRes = this.filterEngine.applyInputFilters({ + messages: [{ role: 'user', content: params.prompt }], + customModel + }); + const sortedTiers = [...customModel.tiers].sort((a, b) => a.tierIndex - b.tierIndex); let lastError: any = null; @@ -1551,14 +1738,19 @@ export class RevolverEngine { try { const testRequest: OpenAIChatRequest = { model: candidate.target.model, - messages: [{ role: 'user', content: params.prompt }] + messages: inputFilterRes.messages }; + let outputTraces: FilterExecutionStepTrace[] = []; const resp = await this.executeNonStreaming({ candidate, requestBody: testRequest, + customModel, requestedModelName: customModel.name, - requestId: `test-${Date.now()}` + requestId: `test-${Date.now()}`, + onOutputFilterTraces: (traces) => { + outputTraces = traces; + } }); const content = resp.choices?.[0]?.message?.content || ''; @@ -1584,7 +1776,8 @@ export class RevolverEngine { promptTokens: resp.usage?.prompt_tokens || 0, completionTokens: resp.usage?.completion_tokens || 0, totalTokens: resp.usage?.total_tokens || 0 - } + }, + appliedFilters: [...inputFilterRes.traces, ...outputTraces] }; return { trace, content, fullResponse: resp }; diff --git a/src/revolverTypes.ts b/src/revolverTypes.ts index 6f6bbe4..e42f96d 100644 --- a/src/revolverTypes.ts +++ b/src/revolverTypes.ts @@ -30,12 +30,111 @@ export interface FallbackTier { targets: ModelTarget[]; } +export type FilterDirection = 'input' | 'output' | 'both'; +export type FilterType = 'literal_replace' | 'regex_replace' | 'instruction_inject' | 'custom_script'; +export type FilterInputTarget = 'last_user' | 'all_user' | 'system' | 'assistant' | 'all_messages'; +export type FilterStreamMode = 'buffer_full' | 'chunk_by_chunk'; + +export type FilterTriggerType = + | 'always' + | 'contains' + | 'not_contains' + | 'regex_match' + | 'not_regex_match' + | 'length_gt' + | 'length_lt' + | 'no_system_prompt' + | 'message_count_gt'; + +export interface FilterTriggerRule { + type: FilterTriggerType; + value?: string; + flags?: string; + caseSensitive?: boolean; +} + +export interface FilterTriggersConfig { + matchMode: 'all' | 'any'; + rules: FilterTriggerRule[]; +} + +export interface LiteralReplaceRule { + find: string; + replace: string; +} + +export interface LiteralReplaceConfig { + rules: LiteralReplaceRule[]; + caseSensitive?: boolean; + wholeWord?: boolean; +} + +export interface RegexReplaceConfig { + pattern: string; + flags: string; + replacement: string; + presetId?: string; +} + +export type InstructionInjectPosition = + | 'prepend_system' + | 'append_system' + | 'prepend_target' + | 'append_target' + | 'wrap_target'; + +export interface InstructionInjectConfig { + position: InstructionInjectPosition; + content: string; + wrapSuffix?: string; + separator?: string; +} + +export interface CustomScriptConfig { + code: string; + timeoutMs?: number; +} + +export interface TextFilterConfig { + id: string; + name: string; + description?: string; + enabled: boolean; + isGlobal?: boolean; + direction: FilterDirection; + inputTarget?: FilterInputTarget; + streamMode?: FilterStreamMode; + triggers: FilterTriggersConfig; + type: FilterType; + literalConfig?: LiteralReplaceConfig; + regexConfig?: RegexReplaceConfig; + instructionConfig?: InstructionInjectConfig; + scriptConfig?: CustomScriptConfig; + createdAt: string; + updatedAt: string; +} + +export interface FilterExecutionStepTrace { + filterId: string; + filterName: string; + filterType: FilterType; + direction: 'input' | 'output'; + triggered: boolean; + modified: boolean; + durationMs: number; + beforePreview?: string; + afterPreview?: string; + error?: string; +} + export interface CustomModelConfig { id: string; name: string; // The model identifier passed by client e.g. "my-smart-model" description?: string; isDefault?: boolean; tiers: FallbackTier[]; // Tier 0 = Main, Tier 1 = Fallback 1, Tier 2 = Fallback 2... + filterIds?: string[]; // Ordered list of filter IDs bound to this custom model + disableGlobalFilters?: boolean; // Optional toggle to opt out of global filters createdAt: string; updatedAt: string; } @@ -45,6 +144,7 @@ export interface RevolverConfigFile { defaultModelId?: string; providers: ProviderConfig[]; customModels: CustomModelConfig[]; + filters?: TextFilterConfig[]; } export interface ExecutionDiagnosticTrace { @@ -62,4 +162,5 @@ export interface ExecutionDiagnosticTrace { completionTokens: number; totalTokens: number; }; + appliedFilters?: FilterExecutionStepTrace[]; } diff --git a/src/routes.ts b/src/routes.ts index 206a581..12993db 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -9,6 +9,7 @@ import adminRoutes from './adminRoutes'; import { renderModelsPage, renderProvidersPage, + renderFiltersPage, renderPlaygroundPage, renderTelemetryPage, renderLiveLogsPage @@ -39,6 +40,11 @@ router.get('/admin/providers', (req: Request, res: Response) => { res.send(renderProvidersPage()); }); +router.get('/admin/filters', (req: Request, res: Response) => { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.send(renderFiltersPage()); +}); + router.get('/admin/playground', (req: Request, res: Response) => { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.send(renderPlaygroundPage()); diff --git a/test-filters.ts b/test-filters.ts new file mode 100644 index 0000000..5ed83b0 --- /dev/null +++ b/test-filters.ts @@ -0,0 +1,510 @@ +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 ... blocks on Output) + const fRegexThink = store.saveFilter({ + name: 'Strip Think Reasoning Tags', + direction: 'output', + streamMode: 'buffer_full', + type: 'regex_replace', + regexConfig: { + pattern: '[\\s\\S]*?<\\/think(?:ing)?>\\s*', + flags: 'gi', + replacement: '' + }, + triggers: { + matchMode: 'all', + rules: [{ type: 'regex_match', value: '...' is at the start! + // But in modelA's resolved pipeline: [fLiteral, fRegexThink, fScript, fGlobal] -> fRegexThink strips 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 , 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: 'reasoning\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 ... across multiple SSE chunks! + const chunks = [ + '\nMulti-chunk internal reasoning...\n\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: 'Hidden thought\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((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 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((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 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 & 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 & 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((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); +});