From 11b9aa9e2087eedbd1628f02b0fe6e5aa12c06b3 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 11 Sep 2025 13:04:24 -0500 Subject: [PATCH] DotAI: validate messages before saving to history --- src/lib/DotAI.test.ts | 106 ++++++++++++++++++++++++++++++++++++++++++ src/lib/DotAI.ts | 52 +++++++++++++++++++++ 2 files changed, 158 insertions(+) diff --git a/src/lib/DotAI.test.ts b/src/lib/DotAI.test.ts index 8543349b..f48abd82 100644 --- a/src/lib/DotAI.test.ts +++ b/src/lib/DotAI.test.ts @@ -188,6 +188,112 @@ invalid json line // Should not throw await expect(dotAI.setHistory('test-session', messages)).resolves.toBeUndefined(); }); + + it('should validate tool messages have matching tool_call_id', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + + const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { + role: 'assistant', + content: 'I need to use a tool', + tool_calls: [{ id: 'call_123', type: 'function', function: { name: 'test_tool', arguments: '{}' } }] + }, + { role: 'tool', content: 'Tool result', tool_call_id: 'call_123' } + ]; + + // Should not throw for valid messages + await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined(); + }); + + it('should throw error for tool message without preceding assistant message with tool_calls', async () => { + const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { role: 'assistant', content: 'Response without tool calls' }, + { role: 'tool', content: 'Tool result', tool_call_id: 'call_123' } + ]; + + await expect(dotAI.setHistory('test-session', invalidMessages)) + .rejects.toThrow('Tool message at index 2 with tool_call_id "call_123" must be preceded by an assistant message with a matching tool_call id'); + }); + + it('should throw error for tool message with non-matching tool_call_id', async () => { + const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { + role: 'assistant', + content: 'I need to use a tool', + tool_calls: [{ id: 'call_456', type: 'function', function: { name: 'test_tool', arguments: '{}' } }] + }, + { role: 'tool', content: 'Tool result', tool_call_id: 'call_123' } + ]; + + await expect(dotAI.setHistory('test-session', invalidMessages)) + .rejects.toThrow('Tool message at index 2 with tool_call_id "call_123" must be preceded by an assistant message with a matching tool_call id'); + }); + + it('should throw error for tool message without tool_call_id', async () => { + const invalidMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { + role: 'assistant', + content: 'I need to use a tool', + tool_calls: [{ id: 'call_123', type: 'function', function: { name: 'test_tool', arguments: '{}' } }] + }, + { role: 'tool', content: 'Tool result' } as OpenAI.Chat.Completions.ChatCompletionMessageParam + ]; + + await expect(dotAI.setHistory('test-session', invalidMessages)) + .rejects.toThrow('Tool message at index 2 is missing tool_call_id'); + }); + + it('should validate multiple tool messages correctly', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + + const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'Hello' }, + { + role: 'assistant', + content: 'I need to use tools', + tool_calls: [ + { id: 'call_123', type: 'function', function: { name: 'tool1', arguments: '{}' } }, + { id: 'call_456', type: 'function', function: { name: 'tool2', arguments: '{}' } } + ] + }, + { role: 'tool', content: 'Tool 1 result', tool_call_id: 'call_123' }, + { role: 'tool', content: 'Tool 2 result', tool_call_id: 'call_456' } + ]; + + // Should not throw for valid messages + await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined(); + }); + + it('should allow tool messages to reference tool calls from the most recent assistant message', async () => { + // Mock isEnabled to return true + vi.spyOn(dotAI, 'isEnabled').mockResolvedValue(true); + + const validMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [ + { role: 'user', content: 'First request' }, + { + role: 'assistant', + content: 'First response', + tool_calls: [{ id: 'call_old', type: 'function', function: { name: 'old_tool', arguments: '{}' } }] + }, + { role: 'tool', content: 'Old tool result', tool_call_id: 'call_old' }, + { role: 'user', content: 'Second request' }, + { + role: 'assistant', + content: 'Second response', + tool_calls: [{ id: 'call_new', type: 'function', function: { name: 'new_tool', arguments: '{}' } }] + }, + { role: 'tool', content: 'New tool result', tool_call_id: 'call_new' } + ]; + + // Should not throw for valid messages + await expect(dotAI.setHistory('test-session', validMessages)).resolves.toBeUndefined(); + }); }); describe('generateSessionName', () => { diff --git a/src/lib/DotAI.ts b/src/lib/DotAI.ts index b8bb4917..ecfd2bb4 100644 --- a/src/lib/DotAI.ts +++ b/src/lib/DotAI.ts @@ -86,6 +86,9 @@ export class DotAI { sessionName: string, messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[], ): Promise { + // Validate messages before saving + this.validateMessages(messages); + // Only save if history should be enabled based on the new criteria if (!(await this.isEnabled())) { return; @@ -111,6 +114,55 @@ export class DotAI { } } + /** Validate that tool messages are properly preceded by assistant messages with matching tool calls */ + private validateMessages(messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): void { + for (let i = 0; i < messages.length; i++) { + const message = messages[i]; + + // Check if this is a tool message + if (message.role === 'tool') { + // Tool messages must have tool_call_id + if (!('tool_call_id' in message) || !message.tool_call_id) { + throw new Error(`Tool message at index ${i} is missing tool_call_id`); + } + + // Find the preceding assistant message with tool calls + let foundMatchingToolCall = false; + + // Look backwards from the current position to find the assistant message with matching tool call + for (let j = i - 1; j >= 0; j--) { + const prevMessage = messages[j]; + + if (prevMessage.role === 'assistant') { + // Check if this assistant message has tool_calls + if ('tool_calls' in prevMessage && prevMessage.tool_calls) { + // Check if any tool call ID matches + const hasMatchingId = prevMessage.tool_calls.some( + toolCall => toolCall.id === message.tool_call_id + ); + + if (hasMatchingId) { + foundMatchingToolCall = true; + break; + } + } + + // If we found an assistant message without the matching tool call, stop looking + // (tool messages should be paired with the most recent assistant message with tool calls) + break; + } + } + + if (!foundMatchingToolCall) { + throw new Error( + `Tool message at index ${i} with tool_call_id "${message.tool_call_id}" ` + + `must be preceded by an assistant message with a matching tool_call id` + ); + } + } + } + } + /** * Creates .ai/history directory and ensures .ai/ is gitignored at the project root. */