File size: 7,589 Bytes
7a1ad33 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {
describe,
it,
expect,
beforeEach,
afterEach,
vi,
type Mock,
} from 'vitest';
import {
BaseToolInvocation,
BaseDeclarativeTool,
Kind,
type ToolResult,
} from './tools.js';
import { MessageBus } from '../confirmation-bus/message-bus.js';
import { PolicyEngine } from '../policy/policy-engine.js';
import {
MessageBusType,
type ToolConfirmationResponse,
} from '../confirmation-bus/types.js';
import { randomUUID } from 'node:crypto';
// Mock crypto module
vi.mock('node:crypto', () => ({
randomUUID: vi.fn(),
}));
interface TestParams {
testParam: string;
}
interface TestResult extends ToolResult {
testValue: string;
}
class TestToolInvocation extends BaseToolInvocation<TestParams, TestResult> {
getDescription(): string {
return `Test tool with param: ${this.params.testParam}`;
}
async execute(): Promise<TestResult> {
return {
llmContent: `Executed with ${this.params.testParam}`,
returnDisplay: `Test result: ${this.params.testParam}`,
testValue: this.params.testParam,
};
}
override async shouldConfirmExecute(
abortSignal: AbortSignal,
): Promise<false> {
const decision = await this.getMessageBusDecision(abortSignal);
if (decision === 'allow') {
return false;
}
if (decision === 'deny') {
throw new Error('Tool execution denied by policy');
}
return false;
}
}
class TestTool extends BaseDeclarativeTool<TestParams, TestResult> {
constructor(messageBus: MessageBus) {
super(
'test-tool',
'Test Tool',
'A test tool for message bus integration',
Kind.Other,
{
type: 'object',
properties: {
testParam: { type: 'string' },
},
required: ['testParam'],
},
messageBus,
true,
false,
);
}
protected createInvocation(
params: TestParams,
messageBus: MessageBus,
_toolName?: string,
_toolDisplayName?: string,
) {
return new TestToolInvocation(
params,
messageBus,
_toolName,
_toolDisplayName,
);
}
}
describe('Message Bus Integration', () => {
let policyEngine: PolicyEngine;
let messageBus: MessageBus;
let mockUUID: Mock;
beforeEach(() => {
vi.resetAllMocks();
policyEngine = new PolicyEngine();
messageBus = new MessageBus(policyEngine);
mockUUID = vi.mocked(randomUUID);
mockUUID.mockReturnValue('test-correlation-id');
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('BaseToolInvocation with MessageBus', () => {
it('should use message bus for confirmation when available', async () => {
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
// Mock message bus publish and subscribe
const publishSpy = vi.spyOn(messageBus, 'publish');
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const unsubscribeSpy = vi.spyOn(messageBus, 'unsubscribe');
// Start confirmation process
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
// Verify confirmation request was published
expect(publishSpy).toHaveBeenCalledWith({
type: MessageBusType.TOOL_CONFIRMATION_REQUEST,
toolCall: {
name: 'test-tool',
args: { testParam: 'test-value' },
},
correlationId: 'test-correlation-id',
});
// Verify subscription to response
expect(subscribeSpy).toHaveBeenCalledWith(
MessageBusType.TOOL_CONFIRMATION_RESPONSE,
expect.any(Function),
);
// Simulate confirmation response
const responseHandler = subscribeSpy.mock.calls[0][1];
const response: ToolConfirmationResponse = {
type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
correlationId: 'test-correlation-id',
confirmed: true,
};
responseHandler(response);
const result = await confirmationPromise;
expect(result).toBe(false); // No further confirmation needed
expect(unsubscribeSpy).toHaveBeenCalled();
});
it('should reject promise when confirmation is denied', async () => {
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
// Simulate denial response
const responseHandler = subscribeSpy.mock.calls[0][1];
const response: ToolConfirmationResponse = {
type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
correlationId: 'test-correlation-id',
confirmed: false,
};
responseHandler(response);
// Should reject with error when denied
await expect(confirmationPromise).rejects.toThrow(
'Tool execution denied by policy',
);
});
it('should handle timeout', async () => {
vi.useFakeTimers();
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
// Fast-forward past timeout
vi.advanceTimersByTime(30000);
const result = await confirmationPromise;
expect(result).toBe(false);
vi.useRealTimers();
});
it('should handle abort signal', async () => {
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
const abortController = new AbortController();
const confirmationPromise = invocation.shouldConfirmExecute(
abortController.signal,
);
// Abort the operation
abortController.abort();
await expect(confirmationPromise).rejects.toThrow(
'Tool execution denied by policy',
);
});
it('should ignore responses with wrong correlation ID', async () => {
vi.useFakeTimers();
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
const subscribeSpy = vi.spyOn(messageBus, 'subscribe');
const confirmationPromise = invocation.shouldConfirmExecute(
new AbortController().signal,
);
// Send response with wrong correlation ID
const responseHandler = subscribeSpy.mock.calls[0][1];
const wrongResponse: ToolConfirmationResponse = {
type: MessageBusType.TOOL_CONFIRMATION_RESPONSE,
correlationId: 'wrong-id',
confirmed: true,
};
responseHandler(wrongResponse);
// Should timeout since correct response wasn't received
vi.advanceTimersByTime(30000);
const result = await confirmationPromise;
expect(result).toBe(false);
vi.useRealTimers();
});
});
describe('Error Handling', () => {
it('should handle message bus publish errors gracefully', async () => {
const tool = new TestTool(messageBus);
const invocation = tool.build({ testParam: 'test-value' });
// Mock publish to throw error
vi.spyOn(messageBus, 'publish').mockImplementation(() => {
throw new Error('Message bus error');
});
const result = await invocation.shouldConfirmExecute(
new AbortController().signal,
);
expect(result).toBe(false); // Should gracefully fall back
});
});
});
|