Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test: add tests for `context-engine` (#9679)

Arvin Xu941b6ec4cbe7
diff --git a/packages/context-engine/src/__tests__/pipeline.test.ts b/packages/context-engine/src/__tests__/pipeline.test.ts
new file mode 100644
index 00000000000..99ae21fe863
--- /dev/null
+++ b/packages/context-engine/src/__tests__/pipeline.test.ts
@@ -0,0 +1,485 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ContextEngine } from '../pipeline';
+import type { ContextProcessor, PipelineContext } from '../types';
+import { PipelineError } from '../types';
+
+describe('ContextEngine', () => {
+ const createMockProcessor = (name: string, delay = 0): ContextProcessor => ({
+ name,
+ process: vi.fn(async (context) => {
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
+ return {
+ ...context,
+ metadata: {
+ ...context.metadata,
+ [name]: true,
+ },
+ };
+ }),
+ });
+
+ const createAbortingProcessor = (name: string, reason = 'test abort'): ContextProcessor => ({
+ name,
+ process: vi.fn(async (context) => ({
+ ...context,
+ abortReason: reason,
+ isAborted: true,
+ })),
+ });
+
+ const createErrorProcessor = (name: string, error: Error): ContextProcessor => ({
+ name,
+ process: vi.fn(async () => {
+ throw error;
+ }),
+ });
+
+ const createInitialContext = (): {
+ initialState: any;
+ maxTokens: number;
+ messages: any[];
+ model: string;
+ } => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ maxTokens: 4000,
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'test-model',
+ });
+
+ describe('constructor', () => {
+ it('should initialize with pipeline and options', () => {
+ const processor1 = createMockProcessor('processor1');
+ const processor2 = createMockProcessor('processor2');
+
+ const engine = new ContextEngine({
+ debug: true,
+ pipeline: [processor1, processor2],
+ });
+
+ expect(engine.getProcessors()).toHaveLength(2);
+ expect(engine.getProcessors()[0]).toBe(processor1);
+ expect(engine.getProcessors()[1]).toBe(processor2);
+ });
+
+ it('should initialize with empty pipeline', () => {
+ const engine = new ContextEngine({ pipeline: [] });
+ expect(engine.getProcessors()).toHaveLength(0);
+ });
+ });
+
+ describe('addProcessor', () => {
+ it('should add processor to pipeline', () => {
+ const engine = new ContextEngine({ pipeline: [] });
+ const processor = createMockProcessor('test');
+
+ engine.addProcessor(processor);
+
+ expect(engine.getProcessors()).toHaveLength(1);
+ expect(engine.getProcessors()[0]).toBe(processor);
+ });
+
+ it('should support chaining', () => {
+ const engine = new ContextEngine({ pipeline: [] });
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+
+ const result = engine.addProcessor(processor1).addProcessor(processor2);
+
+ expect(result).toBe(engine);
+ expect(engine.getProcessors()).toHaveLength(2);
+ });
+ });
+
+ describe('removeProcessor', () => {
+ it('should remove processor by name', () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+ const processor3 = createMockProcessor('p3');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2, processor3],
+ });
+
+ engine.removeProcessor('p2');
+
+ const processors = engine.getProcessors();
+ expect(processors).toHaveLength(2);
+ expect(processors[0].name).toBe('p1');
+ expect(processors[1].name).toBe('p3');
+ });
+
+ it('should support chaining', () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const result = engine.removeProcessor('p1').removeProcessor('p2');
+
+ expect(result).toBe(engine);
+ expect(engine.getProcessors()).toHaveLength(0);
+ });
+
+ it('should do nothing if processor not found', () => {
+ const processor = createMockProcessor('p1');
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ engine.removeProcessor('nonexistent');
+
+ expect(engine.getProcessors()).toHaveLength(1);
+ });
+ });
+
+ describe('getProcessors', () => {
+ it('should return copy of processor list', () => {
+ const processor = createMockProcessor('test');
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ const processors = engine.getProcessors();
+ processors.push(createMockProcessor('new'));
+
+ expect(engine.getProcessors()).toHaveLength(1);
+ });
+ });
+
+ describe('clear', () => {
+ it('should remove all processors', () => {
+ const engine = new ContextEngine({
+ pipeline: [createMockProcessor('p1'), createMockProcessor('p2')],
+ });
+
+ engine.clear();
+
+ expect(engine.getProcessors()).toHaveLength(0);
+ });
+
+ it('should support chaining', () => {
+ const engine = new ContextEngine({
+ pipeline: [createMockProcessor('p1')],
+ });
+
+ const result = engine.clear();
+
+ expect(result).toBe(engine);
+ });
+ });
+
+ describe('process', () => {
+ it('should execute processors in sequence', async () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+ const processor3 = createMockProcessor('p3');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2, processor3],
+ });
+
+ const input = createInitialContext();
+ const result = await engine.process(input);
+
+ expect(result.isAborted).toBe(false);
+ expect(result.messages).toEqual(input.messages);
+ expect(result.metadata.p1).toBe(true);
+ expect(result.metadata.p2).toBe(true);
+ expect(result.metadata.p3).toBe(true);
+ expect(result.stats.processedCount).toBe(3);
+ });
+
+ it('should handle messages array correctly', async () => {
+ const processor = createMockProcessor('p1');
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ const input = createInitialContext();
+ const result = await engine.process(input);
+
+ expect(result.messages).toEqual(input.messages);
+ });
+
+ it('should handle empty messages', async () => {
+ const processor = createMockProcessor('p1');
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ const input = { ...createInitialContext(), messages: undefined };
+ const result = await engine.process(input);
+
+ expect(result.messages).toEqual([]);
+ });
+
+ it('should include metadata in context', async () => {
+ const processor: ContextProcessor = {
+ name: 'test',
+ process: vi.fn(async (context) => {
+ expect(context.metadata.maxTokens).toBe(4000);
+ expect(context.metadata.model).toBe('test-model');
+ expect(context.metadata.customKey).toBe('customValue');
+ return context;
+ }),
+ };
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ await engine.process({
+ ...createInitialContext(),
+ metadata: { customKey: 'customValue' },
+ });
+ });
+
+ it('should track execution stats', async () => {
+ const processor1 = createMockProcessor('p1', 10);
+ const processor2 = createMockProcessor('p2', 20);
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const result = await engine.process(createInitialContext());
+
+ expect(result.stats.processedCount).toBe(2);
+ expect(result.stats.totalDuration).toBeGreaterThanOrEqual(30);
+ expect(result.stats.processorDurations.p1).toBeGreaterThanOrEqual(10);
+ expect(result.stats.processorDurations.p2).toBeGreaterThanOrEqual(20);
+ });
+
+ it('should stop processing when aborted', async () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createAbortingProcessor('p2', 'user requested');
+ const processor3 = createMockProcessor('p3');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2, processor3],
+ });
+
+ const result = await engine.process(createInitialContext());
+
+ expect(result.isAborted).toBe(true);
+ expect(result.abortReason).toBe('user requested');
+ expect(result.stats.processedCount).toBe(2);
+ expect(processor1.process).toHaveBeenCalled();
+ expect(processor2.process).toHaveBeenCalled();
+ expect(processor3.process).not.toHaveBeenCalled();
+ });
+
+ it('should skip remaining processors if context is already aborted', async () => {
+ const processor1: ContextProcessor = {
+ name: 'p1',
+ process: vi.fn(async (context) => ({
+ ...context,
+ isAborted: true,
+ })),
+ };
+ const processor2 = createMockProcessor('p2');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const input = {
+ ...createInitialContext(),
+ };
+ input.initialState = { ...input.initialState, messages: [] };
+
+ const result = await engine.process(input);
+
+ expect(result.isAborted).toBe(true);
+ expect(result.stats.processedCount).toBe(1);
+ expect(processor2.process).not.toHaveBeenCalled();
+ });
+
+ it('should throw PipelineError when processor fails', async () => {
+ const error = new Error('processor failed');
+ const processor = createErrorProcessor('failing-processor', error);
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ await expect(engine.process(createInitialContext())).rejects.toThrow(PipelineError);
+ await expect(engine.process(createInitialContext())).rejects.toThrow(
+ 'Processor [failing-processor] execution failed',
+ );
+ });
+
+ it('should include processor stats even when it fails', async () => {
+ const error = new Error('test error');
+ const processor = createErrorProcessor('failing', error);
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ try {
+ await engine.process(createInitialContext());
+ } catch (e) {
+ expect(e).toBeInstanceOf(PipelineError);
+ if (e instanceof PipelineError) {
+ expect(e.processorName).toBe('failing');
+ expect(e.originalError).toBe(error);
+ }
+ }
+ });
+
+ it('should handle non-Error objects thrown by processor', async () => {
+ const processor: ContextProcessor = {
+ name: 'thrower',
+ process: vi.fn(async () => {
+ throw 'string error';
+ }),
+ };
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ await expect(engine.process(createInitialContext())).rejects.toThrow(PipelineError);
+ });
+
+ it('should preserve initial state', async () => {
+ const processor: ContextProcessor = {
+ name: 'test',
+ process: vi.fn(async (context) => {
+ expect(context.initialState).toEqual(createInitialContext().initialState);
+ return context;
+ }),
+ };
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+ await engine.process(createInitialContext());
+ });
+ });
+
+ describe('getStats', () => {
+ it('should return processor count and names', () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const stats = engine.getStats();
+
+ expect(stats.processorCount).toBe(2);
+ expect(stats.processorNames).toEqual(['p1', 'p2']);
+ });
+
+ it('should return empty stats for empty pipeline', () => {
+ const engine = new ContextEngine({ pipeline: [] });
+
+ const stats = engine.getStats();
+
+ expect(stats.processorCount).toBe(0);
+ expect(stats.processorNames).toEqual([]);
+ });
+ });
+
+ describe('clone', () => {
+ it('should create independent copy of engine', () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+
+ const engine1 = new ContextEngine({
+ debug: true,
+ pipeline: [processor1, processor2],
+ });
+
+ const engine2 = engine1.clone();
+
+ expect(engine2).not.toBe(engine1);
+ expect(engine2.getProcessors()).toHaveLength(2);
+ expect(engine2.getProcessors()[0]).toBe(processor1);
+ expect(engine2.getProcessors()[1]).toBe(processor2);
+
+ // Modify cloned engine
+ engine2.addProcessor(createMockProcessor('p3'));
+
+ // Original should be unchanged
+ expect(engine1.getProcessors()).toHaveLength(2);
+ expect(engine2.getProcessors()).toHaveLength(3);
+ });
+ });
+
+ describe('validate', () => {
+ it('should return valid for correct pipeline', () => {
+ const processor1 = createMockProcessor('p1');
+ const processor2 = createMockProcessor('p2');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should detect duplicate processor names', () => {
+ const processor1 = createMockProcessor('duplicate');
+ const processor2 = createMockProcessor('duplicate');
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2],
+ });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain('Found duplicate processor names: duplicate');
+ });
+
+ it('should detect empty pipeline', () => {
+ const engine = new ContextEngine({ pipeline: [] });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain('No processors in pipeline');
+ });
+
+ it('should detect missing processor name', () => {
+ const processor: ContextProcessor = {
+ name: '',
+ process: vi.fn(),
+ };
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain('Processor missing name');
+ });
+
+ it('should detect missing process method', () => {
+ const processor = {
+ name: 'test',
+ } as any;
+
+ const engine = new ContextEngine({ pipeline: [processor] });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors).toContain('Processor [test] missing process method');
+ });
+
+ it('should detect multiple errors', () => {
+ const processor1 = createMockProcessor('duplicate');
+ const processor2 = createMockProcessor('duplicate');
+ const processor3: ContextProcessor = {
+ name: '',
+ process: vi.fn(),
+ };
+
+ const engine = new ContextEngine({
+ pipeline: [processor1, processor2, processor3],
+ });
+
+ const result = engine.validate();
+
+ expect(result.valid).toBe(false);
+ expect(result.errors.length).toBeGreaterThan(1);
+ });
+ });
+});
diff --git a/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts b/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts
new file mode 100644
index 00000000000..537c7a35057
--- /dev/null
+++ b/packages/context-engine/src/base/__tests__/BaseProcessor.test.ts
@@ -0,0 +1,381 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { ProcessorError } from '../../types';
+import { BaseProcessor } from '../BaseProcessor';
+
+class TestProcessor extends BaseProcessor {
+ readonly name = 'TestProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ return this.cloneContext(context);
+ }
+}
+
+class AbortingProcessor extends BaseProcessor {
+ readonly name = 'AbortingProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ return this.abort(context, 'test abort reason');
+ }
+}
+
+class InvalidOutputProcessor extends BaseProcessor {
+ readonly name = 'InvalidOutputProcessor';
+
+ protected async doProcess(_context: PipelineContext): Promise<PipelineContext> {
+ return {} as PipelineContext;
+ }
+}
+
+class ErrorThrowingProcessor extends BaseProcessor {
+ readonly name = 'ErrorThrowingProcessor';
+
+ protected async doProcess(_context: PipelineContext): Promise<PipelineContext> {
+ throw new Error('test error');
+ }
+}
+
+class MessageCheckingProcessor extends BaseProcessor {
+ readonly name = 'MessageCheckingProcessor';
+ public lastEmptyCheck: boolean | null = null;
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+
+ // Test isEmptyMessage
+ if (cloned.messages.length > 0) {
+ const content = cloned.messages[0].content;
+ this.lastEmptyCheck = this.isEmptyMessage(typeof content === 'string' ? content : undefined);
+ }
+
+ return this.markAsExecuted(cloned);
+ }
+}
+
+describe('BaseProcessor', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ describe('constructor', () => {
+ it('should initialize with options', () => {
+ const processor = new TestProcessor({ debug: true });
+ expect(processor.name).toBe('TestProcessor');
+ });
+
+ it('should initialize without options', () => {
+ const processor = new TestProcessor();
+ expect(processor.name).toBe('TestProcessor');
+ });
+ });
+
+ describe('process', () => {
+ it('should process valid context', async () => {
+ const processor = new TestProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('test');
+ });
+
+ it('should validate input context', async () => {
+ const processor = new TestProcessor();
+ const invalidContext = { messages: 'not an array' } as any;
+
+ await expect(processor.process(invalidContext)).rejects.toThrow(ProcessorError);
+ await expect(processor.process(invalidContext)).rejects.toThrow('无效的上下文');
+ });
+
+ it('should validate output context', async () => {
+ const processor = new InvalidOutputProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ await expect(processor.process(context)).rejects.toThrow(ProcessorError);
+ await expect(processor.process(context)).rejects.toThrow('无效的输出上下文');
+ });
+
+ it('should wrap errors in ProcessorError', async () => {
+ const processor = new ErrorThrowingProcessor();
+ const context = createContext();
+
+ await expect(processor.process(context)).rejects.toThrow(ProcessorError);
+
+ try {
+ await processor.process(context);
+ } catch (error) {
+ expect(error).toBeInstanceOf(ProcessorError);
+ if (error instanceof ProcessorError) {
+ expect(error.processorName).toBe('ErrorThrowingProcessor');
+ expect(error.originalError).toBeInstanceOf(Error);
+ expect(error.originalError?.message).toBe('test error');
+ }
+ }
+ });
+
+ it('should handle non-Error throws', async () => {
+ class StringThrowingProcessor extends BaseProcessor {
+ readonly name = 'StringThrowingProcessor';
+
+ protected async doProcess(_context: PipelineContext): Promise<PipelineContext> {
+ throw 'string error';
+ }
+ }
+
+ const processor = new StringThrowingProcessor();
+ const context = createContext();
+
+ await expect(processor.process(context)).rejects.toThrow(ProcessorError);
+ });
+ });
+
+ describe('validateInput', () => {
+ it('should reject null context', async () => {
+ const processor = new TestProcessor();
+
+ await expect(processor.process(null as any)).rejects.toThrow('无效的上下文');
+ });
+
+ it('should reject undefined context', async () => {
+ const processor = new TestProcessor();
+
+ await expect(processor.process(undefined as any)).rejects.toThrow('无效的上下文');
+ });
+
+ it('should reject context without messages array', async () => {
+ const processor = new TestProcessor();
+ const invalidContext = {
+ initialState: {},
+ isAborted: false,
+ metadata: {},
+ } as any;
+
+ await expect(processor.process(invalidContext)).rejects.toThrow('无效的上下文');
+ });
+ });
+
+ describe('cloneContext', () => {
+ it('should create shallow copy of context', async () => {
+ const processor = new TestProcessor();
+ const context = createContext([
+ { content: 'test1', role: 'user' },
+ { content: 'test2', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result).not.toBe(context);
+ expect(result.messages).not.toBe(context.messages);
+ expect(result.metadata).not.toBe(context.metadata);
+ expect(result.initialState).toBe(context.initialState); // initialState is readonly, so it's shared
+ });
+
+ it('should preserve all context properties', async () => {
+ const processor = new TestProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+ context.metadata.customField = 'customValue';
+
+ const result = await processor.process(context);
+
+ expect(result.isAborted).toBe(context.isAborted);
+ expect(result.metadata.model).toBe(context.metadata.model);
+ expect(result.metadata.maxTokens).toBe(context.metadata.maxTokens);
+ expect(result.metadata.customField).toBe('customValue');
+ });
+ });
+
+ describe('abort', () => {
+ it('should set isAborted to true', async () => {
+ const processor = new AbortingProcessor();
+ const context = createContext();
+
+ const result = await processor.process(context);
+
+ expect(result.isAborted).toBe(true);
+ });
+
+ it('should set abort reason', async () => {
+ const processor = new AbortingProcessor();
+ const context = createContext();
+
+ const result = await processor.process(context);
+
+ expect(result.abortReason).toBe('test abort reason');
+ });
+
+ it('should preserve other context properties', async () => {
+ const processor = new AbortingProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toEqual(context.messages);
+ expect(result.metadata).toEqual(context.metadata);
+ });
+ });
+
+ describe('isEmptyMessage', () => {
+ it('should return true for empty string', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: '', role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(true);
+ });
+
+ it('should return true for whitespace-only string', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: ' \n\t ', role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(true);
+ });
+
+ it('should return true for null', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: null, role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(true);
+ });
+
+ it('should return true for undefined', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: undefined, role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(true);
+ });
+
+ it('should return false for non-empty string', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: 'hello', role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(false);
+ });
+
+ it('should return false for string with content after trim', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: ' hello ', role: 'user' }]);
+
+ await processor.process(context);
+
+ expect(processor.lastEmptyCheck).toBe(false);
+ });
+ });
+
+ describe('markAsExecuted', () => {
+ it('should return context unchanged by default', async () => {
+ const processor = new MessageCheckingProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result = await processor.process(context);
+
+ // Since markAsExecuted is called in doProcess, verify context is returned
+ expect(result.messages).toEqual(context.messages);
+ });
+
+ it('should be callable multiple times', async () => {
+ class MultiMarkProcessor extends BaseProcessor {
+ readonly name = 'MultiMarkProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ let result = this.cloneContext(context);
+ result = this.markAsExecuted(result);
+ result = this.markAsExecuted(result);
+ return result;
+ }
+ }
+
+ const processor = new MultiMarkProcessor();
+ const context = createContext();
+
+ const result = await processor.process(context);
+
+ expect(result).toBeDefined();
+ expect(result.messages).toEqual([]);
+ });
+ });
+
+ describe('integration scenarios', () => {
+ it('should handle complex processing pipeline', async () => {
+ class ComplexProcessor extends BaseProcessor {
+ readonly name = 'ComplexProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+
+ // Check first message
+ if (cloned.messages.length > 0) {
+ const firstContent = cloned.messages[0].content;
+ if (this.isEmptyMessage(typeof firstContent === 'string' ? firstContent : undefined)) {
+ return this.abort(cloned, 'First message is empty');
+ }
+ }
+
+ // Process messages
+ cloned.messages = cloned.messages.map((msg) => ({
+ ...msg,
+ content: typeof msg.content === 'string' ? msg.content.toUpperCase() : msg.content,
+ }));
+
+ return this.markAsExecuted(cloned);
+ }
+ }
+
+ const processor = new ComplexProcessor();
+ const context = createContext([
+ { content: 'hello', role: 'user' },
+ { content: 'world', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.isAborted).toBe(false);
+ expect(result.messages[0].content).toBe('HELLO');
+ expect(result.messages[1].content).toBe('WORLD');
+ });
+
+ it('should abort when condition met', async () => {
+ class ConditionalAbortProcessor extends BaseProcessor {
+ readonly name = 'ConditionalAbortProcessor';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+
+ if (cloned.messages.length === 0) {
+ return this.abort(cloned, 'No messages to process');
+ }
+
+ return cloned;
+ }
+ }
+
+ const processor = new ConditionalAbortProcessor();
+ const context = createContext([]);
+
+ const result = await processor.process(context);
+
+ expect(result.isAborted).toBe(true);
+ expect(result.abortReason).toBe('No messages to process');
+ });
+ });
+});
diff --git a/packages/context-engine/src/base/__tests__/BaseProvider.test.ts b/packages/context-engine/src/base/__tests__/BaseProvider.test.ts
new file mode 100644
index 00000000000..eeb2cd5eff3
--- /dev/null
+++ b/packages/context-engine/src/base/__tests__/BaseProvider.test.ts
@@ -0,0 +1,392 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { BaseProvider } from '../BaseProvider';
+
+class TestProvider extends BaseProvider {
+ readonly name = 'TestProvider';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ return context;
+ }
+}
+
+class ContextBuildingProvider extends BaseProvider {
+ readonly name = 'ContextBuildingProvider';
+
+ protected async buildContext(_context: PipelineContext): Promise<string | null> {
+ return 'Test context content';
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const content = await this.buildContext(context);
+ if (content && this.shouldInject(context)) {
+ const systemMessage = this.createSystemMessage(content);
+ return {
+ ...context,
+ messages: [systemMessage, ...context.messages],
+ };
+ }
+ return context;
+ }
+}
+
+class ConditionalProvider extends BaseProvider {
+ readonly name = 'ConditionalProvider';
+
+ constructor(private shouldInjectFlag: boolean) {
+ super();
+ }
+
+ protected shouldInject(_context: PipelineContext): boolean {
+ return this.shouldInjectFlag;
+ }
+
+ protected async buildContext(_context: PipelineContext): Promise<string | null> {
+ return 'Conditional content';
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const content = await this.buildContext(context);
+ if (content && this.shouldInject(context)) {
+ const systemMessage = this.createSystemMessage(content);
+ return {
+ ...context,
+ messages: [systemMessage, ...context.messages],
+ };
+ }
+ return context;
+ }
+}
+
+class NullContextProvider extends BaseProvider {
+ readonly name = 'NullContextProvider';
+
+ protected async buildContext(_context: PipelineContext): Promise<string | null> {
+ return null;
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const content = await this.buildContext(context);
+ if (content) {
+ const systemMessage = this.createSystemMessage(content);
+ return {
+ ...context,
+ messages: [systemMessage, ...context.messages],
+ };
+ }
+ return context;
+ }
+}
+
+describe('BaseProvider', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ describe('constructor', () => {
+ it('should initialize with options', () => {
+ const provider = new TestProvider({ debug: true });
+ expect(provider.name).toBe('TestProvider');
+ });
+
+ it('should initialize without options', () => {
+ const provider = new TestProvider();
+ expect(provider.name).toBe('TestProvider');
+ });
+ });
+
+ describe('buildContext', () => {
+ it('should return null by default', async () => {
+ const provider = new TestProvider();
+ const context = createContext();
+
+ // Access protected method through a derived class
+ class AccessibleProvider extends TestProvider {
+ async testBuildContext(ctx: PipelineContext) {
+ return this.buildContext(ctx);
+ }
+ }
+
+ const accessibleProvider = new AccessibleProvider();
+ const result = await accessibleProvider.testBuildContext(context);
+
+ expect(result).toBeNull();
+ });
+
+ it('should allow override to return content', async () => {
+ const provider = new ContextBuildingProvider();
+ const context = createContext([{ content: 'user message', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[0].content).toBe('Test context content');
+ expect(result.messages[1].content).toBe('user message');
+ });
+
+ it('should allow returning null to skip injection', async () => {
+ const provider = new NullContextProvider();
+ const context = createContext([{ content: 'user message', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('user message');
+ });
+ });
+
+ describe('shouldInject', () => {
+ it('should return true by default', async () => {
+ const provider = new TestProvider();
+ const context = createContext();
+
+ // Access protected method
+ class AccessibleProvider extends TestProvider {
+ testShouldInject(ctx: PipelineContext) {
+ return this.shouldInject(ctx);
+ }
+ }
+
+ const accessibleProvider = new AccessibleProvider();
+ const result = accessibleProvider.testShouldInject(context);
+
+ expect(result).toBe(true);
+ });
+
+ it('should allow override to control injection', async () => {
+ const provider1 = new ConditionalProvider(true);
+ const provider2 = new ConditionalProvider(false);
+
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result1 = await provider1.process(context);
+ const result2 = await provider2.process(context);
+
+ expect(result1.messages).toHaveLength(2);
+ expect(result1.messages[0].role).toBe('system');
+
+ expect(result2.messages).toHaveLength(1);
+ expect(result2.messages[0].role).toBe('user');
+ });
+ });
+
+ describe('createSystemMessage', () => {
+ it('should create system message with content', async () => {
+ const provider = new TestProvider();
+
+ // Access protected method
+ class AccessibleProvider extends TestProvider {
+ testCreateSystemMessage(content: string) {
+ return this.createSystemMessage(content);
+ }
+ }
+
+ const accessibleProvider = new AccessibleProvider();
+ const message = accessibleProvider.testCreateSystemMessage('Test system prompt');
+
+ expect(message).toEqual({
+ content: 'Test system prompt',
+ role: 'system',
+ });
+ });
+
+ it('should handle empty content', async () => {
+ class AccessibleProvider extends TestProvider {
+ testCreateSystemMessage(content: string) {
+ return this.createSystemMessage(content);
+ }
+ }
+
+ const provider = new AccessibleProvider();
+ const message = provider.testCreateSystemMessage('');
+
+ expect(message).toEqual({
+ content: '',
+ role: 'system',
+ });
+ });
+
+ it('should handle multiline content', async () => {
+ class AccessibleProvider extends TestProvider {
+ testCreateSystemMessage(content: string) {
+ return this.createSystemMessage(content);
+ }
+ }
+
+ const provider = new AccessibleProvider();
+ const content = 'Line 1\nLine 2\nLine 3';
+ const message = provider.testCreateSystemMessage(content);
+
+ expect(message).toEqual({
+ content,
+ role: 'system',
+ });
+ });
+ });
+
+ describe('integration scenarios', () => {
+ it('should work with full provider pattern', async () => {
+ class FullProvider extends BaseProvider {
+ readonly name = 'FullProvider';
+
+ protected async buildContext(context: PipelineContext): Promise<string | null> {
+ if (context.initialState.systemRole) {
+ return `System: ${context.initialState.systemRole}`;
+ }
+ return null;
+ }
+
+ protected shouldInject(context: PipelineContext): boolean {
+ return context.messages.length > 0;
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const content = await this.buildContext(context);
+
+ if (content && this.shouldInject(context)) {
+ const systemMessage = this.createSystemMessage(content);
+ cloned.messages = [systemMessage, ...cloned.messages];
+ }
+
+ return cloned;
+ }
+ }
+
+ const provider = new FullProvider();
+ const context = createContext([{ content: 'hello', role: 'user' }]);
+ context.initialState.systemRole = 'You are a helpful assistant';
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[0].content).toBe('System: You are a helpful assistant');
+ expect(result.messages[1].content).toBe('hello');
+ });
+
+ it('should skip injection when shouldInject returns false', async () => {
+ class SkipProvider extends BaseProvider {
+ readonly name = 'SkipProvider';
+
+ protected async buildContext(_context: PipelineContext): Promise<string | null> {
+ return 'System prompt';
+ }
+
+ protected shouldInject(context: PipelineContext): boolean {
+ return context.messages.length > 1;
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const content = await this.buildContext(context);
+
+ if (content && this.shouldInject(context)) {
+ const systemMessage = this.createSystemMessage(content);
+ cloned.messages = [systemMessage, ...cloned.messages];
+ }
+
+ return cloned;
+ }
+ }
+
+ const provider = new SkipProvider();
+ const context = createContext([{ content: 'hello', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('user');
+ });
+
+ it('should handle complex context building', async () => {
+ class ComplexProvider extends BaseProvider {
+ readonly name = 'ComplexProvider';
+
+ protected async buildContext(context: PipelineContext): Promise<string | null> {
+ const { model, provider } = context.initialState;
+ const { maxTokens } = context.metadata;
+
+ return `Model: ${model}, Provider: ${provider}, Max Tokens: ${maxTokens}`;
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const content = await this.buildContext(context);
+
+ if (content && this.shouldInject(context)) {
+ const systemMessage = this.createSystemMessage(content);
+ cloned.messages = [systemMessage, ...cloned.messages];
+ }
+
+ return cloned;
+ }
+ }
+
+ const provider = new ComplexProvider();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toBe(
+ 'Model: test-model, Provider: test-provider, Max Tokens: 4000',
+ );
+ });
+ });
+
+ describe('inheritance from BaseProcessor', () => {
+ it('should inherit all BaseProcessor functionality', async () => {
+ class InheritanceTestProvider extends BaseProvider {
+ readonly name = 'InheritanceTest';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+
+ // Use inherited methods
+ if (cloned.messages.length === 0) {
+ return this.abort(cloned, 'No messages');
+ }
+
+ const firstContent = cloned.messages[0].content;
+ if (this.isEmptyMessage(typeof firstContent === 'string' ? firstContent : undefined)) {
+ return this.abort(cloned, 'Empty message');
+ }
+
+ return this.markAsExecuted(cloned);
+ }
+ }
+
+ const provider = new InheritanceTestProvider();
+
+ // Test with empty messages
+ const context1 = createContext([]);
+ const result1 = await provider.process(context1);
+ expect(result1.isAborted).toBe(true);
+ expect(result1.abortReason).toBe('No messages');
+
+ // Test with empty content
+ const context2 = createContext([{ content: '', role: 'user' }]);
+ const result2 = await provider.process(context2);
+ expect(result2.isAborted).toBe(true);
+ expect(result2.abortReason).toBe('Empty message');
+
+ // Test with valid content
+ const context3 = createContext([{ content: 'hello', role: 'user' }]);
+ const result3 = await provider.process(context3);
+ expect(result3.isAborted).toBe(false);
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
new file mode 100644
index 00000000000..8df0f34adf5
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/MessageCleanup.test.ts
@@ -0,0 +1,346 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { MessageCleanupProcessor } from '../MessageCleanup';
+
+describe('MessageCleanupProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ describe('constructor', () => {
+ it('should initialize with default options', () => {
+ const processor = new MessageCleanupProcessor();
+ expect(processor.name).toBe('MessageCleanupProcessor');
+ });
+
+ it('should initialize with custom options', () => {
+ const processor = new MessageCleanupProcessor({ debug: true });
+ expect(processor.name).toBe('MessageCleanupProcessor');
+ });
+ });
+
+ describe('process', () => {
+ it('should clean system messages', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'You are a helpful assistant',
+ extraField: 'should be removed',
+ id: 'msg1',
+ role: 'system',
+ timestamp: Date.now(),
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'You are a helpful assistant',
+ role: 'system',
+ });
+ expect(result.messages[0]).not.toHaveProperty('extraField');
+ expect(result.messages[0]).not.toHaveProperty('id');
+ expect(result.messages[0]).not.toHaveProperty('timestamp');
+ });
+
+ it('should clean user messages', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'Hello, world!',
+ extraField: 'remove me',
+ id: 'msg2',
+ role: 'user',
+ timestamp: Date.now(),
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'Hello, world!',
+ role: 'user',
+ });
+ });
+
+ it('should clean assistant messages without tool_calls', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'I can help you with that',
+ extraField: 'unnecessary',
+ id: 'msg3',
+ role: 'assistant',
+ timestamp: Date.now(),
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'I can help you with that',
+ role: 'assistant',
+ });
+ });
+
+ it('should preserve tool_calls in assistant messages', async () => {
+ const processor = new MessageCleanupProcessor();
+ const toolCalls = [
+ {
+ function: {
+ arguments: '{"query":"test"}',
+ name: 'search',
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ];
+
+ const context = createContext([
+ {
+ content: '',
+ extraField: 'remove',
+ id: 'msg4',
+ role: 'assistant',
+ timestamp: Date.now(),
+ tool_calls: toolCalls,
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: '',
+ role: 'assistant',
+ tool_calls: toolCalls,
+ });
+ });
+
+ it('should clean tool messages with name', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'Search result: ...',
+ extraField: 'extra',
+ id: 'msg5',
+ name: 'search',
+ role: 'tool',
+ timestamp: Date.now(),
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'Search result: ...',
+ name: 'search',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ });
+ });
+
+ it('should clean tool messages without name', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'Tool result',
+ extraField: 'extra',
+ id: 'msg6',
+ role: 'tool',
+ timestamp: Date.now(),
+ tool_call_id: 'call_2',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: 'Tool result',
+ role: 'tool',
+ tool_call_id: 'call_2',
+ });
+ });
+
+ it('should keep unknown role messages unchanged', async () => {
+ const processor = new MessageCleanupProcessor();
+ const unknownMessage = {
+ content: 'Unknown message',
+ customField: 'keep this',
+ id: 'msg7',
+ role: 'custom_role',
+ };
+
+ const context = createContext([unknownMessage]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual(unknownMessage);
+ });
+
+ it('should clean multiple messages', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'System prompt',
+ extra: 'remove',
+ id: 'msg1',
+ role: 'system',
+ },
+ {
+ content: 'User question',
+ extra: 'remove',
+ id: 'msg2',
+ role: 'user',
+ },
+ {
+ content: 'Assistant response',
+ extra: 'remove',
+ id: 'msg3',
+ role: 'assistant',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages.every((msg) => !('extra' in msg))).toBe(true);
+ expect(result.messages.every((msg) => !('id' in msg))).toBe(true);
+ });
+
+ it('should update metadata with cleanup stats', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: 'Test',
+ extraField: 'remove',
+ id: 'msg1',
+ role: 'user',
+ },
+ {
+ content: 'Response',
+ extraField: 'remove',
+ id: 'msg2',
+ role: 'assistant',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.messageCleanup).toEqual({
+ cleanedCount: 2,
+ totalMessages: 2,
+ });
+ });
+
+ it('should track messages that were not modified', async () => {
+ const processor = new MessageCleanupProcessor();
+ const cleanMessage = {
+ content: 'Already clean',
+ role: 'user',
+ };
+
+ const context = createContext([
+ cleanMessage,
+ {
+ content: 'Needs cleaning',
+ extra: 'field',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ // Both messages are "cleaned" because comparison is done by reference
+ expect(result.metadata.messageCleanup.cleanedCount).toBe(2);
+ expect(result.metadata.messageCleanup.totalMessages).toBe(2);
+ });
+
+ it('should handle empty messages array', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ expect(result.metadata.messageCleanup).toEqual({
+ cleanedCount: 0,
+ totalMessages: 0,
+ });
+ });
+
+ it('should not mutate original context', async () => {
+ const processor = new MessageCleanupProcessor();
+ const originalMessage = {
+ content: 'Test',
+ extra: 'field',
+ id: 'msg1',
+ role: 'user',
+ };
+ const context = createContext([originalMessage]);
+
+ await processor.process(context);
+
+ // Original message should be unchanged
+ expect(originalMessage).toHaveProperty('extra');
+ expect(originalMessage).toHaveProperty('id');
+ });
+
+ it('should handle messages with array content', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([
+ {
+ content: [
+ { text: 'Hello', type: 'text' },
+ { image_url: { url: 'http://example.com/image.jpg' }, type: 'image_url' },
+ ],
+ extra: 'remove',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0]).toEqual({
+ content: [
+ { text: 'Hello', type: 'text' },
+ { image_url: { url: 'http://example.com/image.jpg' }, type: 'image_url' },
+ ],
+ role: 'user',
+ });
+ });
+
+ it('should return valid context after processing', async () => {
+ const processor = new MessageCleanupProcessor();
+ const context = createContext([{ content: 'test', role: 'user' }]);
+
+ const result = await processor.process(context);
+
+ expect(result).toBeDefined();
+ expect(result.messages).toBeDefined();
+ expect(result.metadata).toBeDefined();
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/__tests__/ToolCall.test.ts b/packages/context-engine/src/processors/__tests__/ToolCall.test.ts
new file mode 100644
index 00000000000..dc78c4cf2cf
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/ToolCall.test.ts
@@ -0,0 +1,552 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { ToolCallProcessor } from '../ToolCall';
+import type { ToolCallConfig } from '../ToolCall';
+
+describe('ToolCallProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ const defaultConfig: ToolCallConfig = {
+ model: 'gpt-4',
+ provider: 'openai',
+ };
+
+ describe('constructor', () => {
+ it('should initialize with config', () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ expect(processor.name).toBe('ToolCallProcessor');
+ });
+
+ it('should initialize with custom options', () => {
+ const processor = new ToolCallProcessor(defaultConfig, { debug: true });
+ expect(processor.name).toBe('ToolCallProcessor');
+ });
+ });
+
+ describe('process - assistant messages', () => {
+ it('should convert tools to tool_calls format', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: '',
+ id: 'msg1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"test"}',
+ id: 'call_1',
+ identifier: 'web',
+ type: 'builtin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].tool_calls).toEqual([
+ {
+ function: {
+ arguments: '{"query":"test"}',
+ name: 'web.search',
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ ]);
+ });
+
+ it('should use custom genToolCallingName function', async () => {
+ const genToolCallingName = vi.fn(
+ (identifier, apiName, type) => `custom_${identifier}_${apiName}_${type}`,
+ );
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ genToolCallingName,
+ });
+
+ const context = createContext([
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'web',
+ type: 'builtin',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(genToolCallingName).toHaveBeenCalledWith('web', 'search', 'builtin');
+ expect(result.messages[0].tool_calls[0].function.name).toBe('custom_web_search_builtin');
+ });
+
+ it('should handle multiple tool calls', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"test1"}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ {
+ apiName: 'translate',
+ arguments: '{"text":"hello"}',
+ id: 'call_2',
+ identifier: 'utils',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].tool_calls).toHaveLength(2);
+ expect(result.messages[0].tool_calls[0].function.name).toBe('web.search');
+ expect(result.messages[0].tool_calls[1].function.name).toBe('utils.translate');
+ });
+
+ it('should remove tool_calls and tools when not supported', async () => {
+ const isCanUseFC = vi.fn(() => false);
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ isCanUseFC,
+ });
+
+ const context = createContext([
+ {
+ content: 'Using a tool',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(isCanUseFC).toHaveBeenCalledWith('gpt-4', 'openai');
+ expect(result.messages[0]).not.toHaveProperty('tools');
+ expect(result.messages[0]).not.toHaveProperty('tool_calls');
+ expect(result.messages[0].content).toBe('Using a tool');
+ expect(result.messages[0].role).toBe('assistant');
+ });
+
+ it('should remove empty tool_calls when not supported', async () => {
+ const isCanUseFC = vi.fn(() => false);
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ isCanUseFC,
+ });
+
+ const context = createContext([
+ {
+ content: 'Test',
+ role: 'assistant',
+ tool_calls: [],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0]).not.toHaveProperty('tool_calls');
+ expect(result.messages[0]).not.toHaveProperty('tools');
+ });
+
+ it('should keep message when no tools present', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'Regular message',
+ role: 'assistant',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0]).toEqual({
+ content: 'Regular message',
+ role: 'assistant',
+ });
+ });
+ });
+
+ describe('process - tool messages', () => {
+ it('should generate tool name from plugin', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'Tool result',
+ plugin: {
+ apiName: 'search',
+ identifier: 'web',
+ type: 'builtin',
+ },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].name).toBe('web.search');
+ expect(result.messages[0].tool_call_id).toBe('call_1');
+ expect(result.messages[0].role).toBe('tool');
+ });
+
+ it('should use custom genToolCallingName for tool messages', async () => {
+ const genToolCallingName = vi.fn(
+ (identifier, apiName, type) => `tool_${identifier}_${apiName}_${type}`,
+ );
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ genToolCallingName,
+ });
+
+ const context = createContext([
+ {
+ content: 'Result',
+ plugin: {
+ apiName: 'search',
+ identifier: 'web',
+ type: 'plugin',
+ },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(genToolCallingName).toHaveBeenCalledWith('web', 'search', 'plugin');
+ expect(result.messages[0].name).toBe('tool_web_search_plugin');
+ });
+
+ it('should convert tool message to user message when not supported', async () => {
+ const isCanUseFC = vi.fn(() => false);
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ isCanUseFC,
+ });
+
+ const context = createContext([
+ {
+ content: 'Tool result',
+ name: 'web.search',
+ plugin: {
+ apiName: 'search',
+ identifier: 'web',
+ },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toBe('Tool result');
+ expect(result.messages[0].name).toBeUndefined();
+ expect(result.messages[0].plugin).toBeUndefined();
+ expect(result.messages[0].tool_call_id).toBeUndefined();
+ });
+
+ it('should handle tool message without plugin', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'Result',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].name).toBeUndefined();
+ expect(result.messages[0].role).toBe('tool');
+ expect(result.messages[0].tool_call_id).toBe('call_1');
+ });
+ });
+
+ describe('process - metadata', () => {
+ it('should update metadata with processing stats', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ ],
+ },
+ {
+ content: 'Result',
+ plugin: {
+ apiName: 'search',
+ identifier: 'web',
+ },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.toolCallProcessed).toBe(2);
+ expect(result.metadata.toolCallsConverted).toBe(1);
+ expect(result.metadata.toolMessagesConverted).toBe(1);
+ expect(result.metadata.supportTools).toBe(true);
+ });
+
+ it('should track supportTools when function calling not supported', async () => {
+ const isCanUseFC = vi.fn(() => false);
+
+ const processor = new ToolCallProcessor({
+ ...defaultConfig,
+ isCanUseFC,
+ });
+
+ const context = createContext([
+ {
+ content: 'Test',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.supportTools).toBe(false);
+ });
+
+ it('should count zero when no tool messages processed', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'Regular message',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.toolCallProcessed).toBe(0);
+ expect(result.metadata.toolCallsConverted).toBe(0);
+ expect(result.metadata.toolMessagesConverted).toBe(0);
+ });
+ });
+
+ describe('process - error handling', () => {
+ it('should continue processing when message processing fails', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+
+ // Create a message that might cause an error but should be handled gracefully
+ const context = createContext([
+ {
+ content: 'Valid message',
+ role: 'user',
+ },
+ {
+ content: '',
+ // Invalid tools structure
+ role: 'assistant',
+ tools: null,
+ },
+ {
+ content: 'Another valid message',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ // Should process all messages despite potential errors
+ expect(result.messages).toHaveLength(3);
+ });
+ });
+
+ describe('process - mixed scenarios', () => {
+ it('should handle conversation with mixed message types', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'System prompt',
+ role: 'system',
+ },
+ {
+ content: 'User question',
+ role: 'user',
+ },
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{"query":"test"}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ ],
+ },
+ {
+ content: 'Search results',
+ plugin: {
+ apiName: 'search',
+ identifier: 'web',
+ },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ {
+ content: 'Final response',
+ role: 'assistant',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(5);
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages[2].tool_calls).toBeDefined();
+ expect(result.messages[3].role).toBe('tool');
+ expect(result.messages[3].name).toBe('web.search');
+ expect(result.messages[4].role).toBe('assistant');
+ });
+
+ it('should not mutate original context', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const originalMessage = {
+ content: '',
+ id: 'msg1',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ ],
+ };
+ const context = createContext([originalMessage]);
+
+ await processor.process(context);
+
+ // Original message should be unchanged
+ expect(originalMessage).toHaveProperty('tools');
+ expect(originalMessage).not.toHaveProperty('tool_calls');
+ });
+
+ it('should return valid context after processing', async () => {
+ const processor = new ToolCallProcessor(defaultConfig);
+ const context = createContext([
+ {
+ content: 'Test',
+ role: 'user',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result).toBeDefined();
+ expect(result.messages).toBeDefined();
+ expect(result.metadata).toBeDefined();
+ expect(result.metadata.supportTools).toBeDefined();
+ });
+ });
+
+ describe('isCanUseFC integration', () => {
+ it('should call isCanUseFC with correct parameters', async () => {
+ const isCanUseFC = vi.fn(() => true);
+
+ const processor = new ToolCallProcessor({
+ isCanUseFC,
+ model: 'claude-3',
+ provider: 'anthropic',
+ });
+
+ const context = createContext([
+ {
+ content: 'Test',
+ role: 'user',
+ },
+ ]);
+
+ await processor.process(context);
+
+ expect(isCanUseFC).toHaveBeenCalledWith('claude-3', 'anthropic');
+ });
+
+ it('should default to supporting tools when isCanUseFC not provided', async () => {
+ const processor = new ToolCallProcessor({
+ model: 'test-model',
+ provider: 'test-provider',
+ });
+
+ const context = createContext([
+ {
+ content: '',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: 'search',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'web',
+ },
+ ],
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.supportTools).toBe(true);
+ expect(result.messages[0].tool_calls).toBeDefined();
+ });
+ });
+});