import { asValue, createContainer } from 'awilix' import { z } from 'zod' import type { ToolExecutionOptions } from 'ai' import { resolveAiAgentTools } from '../agent-tools' import { resetAgentRegistryForTests, seedAgentRegistryForTests } from '../agent-registry' import { registerMcpTool, toolRegistry } from '../tool-registry' import { toSafeZodSchema } from '../schema-utils' import type { AiToolDefinition } from '../types' import type { AiAgentDefinition } from '../ai-agent-definition' const prepareMutationMock = jest.fn() const container = createContainer() container.register({ rbacService: asValue({}) }) jest.mock('@open-mercato/shared/lib/di/container', () => ({ createRequestContainer: async () => container, })) jest.mock('../tool-loader', () => ({ ensureModuleToolsLoaded: async () => undefined, })) jest.mock('../prepare-mutation', () => ({ prepareMutation: (...args: unknown[]) => prepareMutationMock(...args), })) const authContext = { tenantId: 'tenant-1', organizationId: 'org-1', userId: 'user-1', features: ['test.records.manage'], isSuperAdmin: false, } const executionOptions: ToolExecutionOptions = { toolCallId: 'call-1', messages: [], context: undefined } function seedAgent(overrides: Partial = {}) { const agent: AiAgentDefinition = { id: 'test.assistant', moduleId: 'test', label: 'Test assistant', description: 'Approval path fixture', systemPrompt: 'Test', allowedTools: ['test.mutation'], readOnly: false, mutationPolicy: 'confirm-required', ...overrides, } seedAgentRegistryForTests([agent]) } describe('agent approval paths alongside the direct HTTP refusal', () => { let handler: jest.Mock beforeEach(() => { jest.clearAllMocks() resetAgentRegistryForTests() toolRegistry.clear() handler = jest.fn(async () => ({ written: true })) const tool: AiToolDefinition = { name: 'test.mutation', description: 'Mutation fixture', inputSchema: z.object({ title: z.string() }), isMutation: true, isDestructive: false, requiredFeatures: ['test.records.manage'], handler, } registerMcpTool(tool, { moduleId: 'test' }) prepareMutationMock.mockResolvedValue({ uiPart: { type: 'mutation-preview-card', data: { pendingActionId: 'action-1' } }, pendingAction: { id: 'action-1', expiresAt: new Date('2099-01-01'), status: 'pending' }, reused: false, }) }) afterEach(() => { resetAgentRegistryForTests() toolRegistry.clear() }) it.each(['chat', 'object'] as const)('still stages confirm-required mutations for %s agents', async (requestedExecutionMode) => { seedAgent({ executionMode: requestedExecutionMode }) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container, requestedExecutionMode, }) const result = await resolved.tools.test__mutation.execute?.({ title: 'Changed' }, executionOptions) expect(handler).not.toHaveBeenCalled() expect(prepareMutationMock).toHaveBeenCalledWith( expect.objectContaining({ toolCallArgs: { title: 'Changed' }, agent: expect.objectContaining({ id: 'test.assistant' }) }), expect.objectContaining({ tenantId: 'tenant-1', organizationId: 'org-1', userId: 'user-1', container }), ) expect(result).toEqual(expect.stringContaining('pending-confirmation')) expect(resolved.uiPartQueue.drain()).toEqual([ { type: 'mutation-preview-card', data: { pendingActionId: 'action-1' } }, ]) }) it('preserves policy-permitted non-destructive writes through the shared executor', async () => { seedAgent({ mutationPolicy: 'destructive-confirm-required' }) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) const result = await resolved.tools.test__mutation.execute?.({ title: 'Changed' }, executionOptions) expect(prepareMutationMock).not.toHaveBeenCalled() expect(handler).toHaveBeenCalledWith({ title: 'Changed' }, expect.objectContaining({ tenantId: 'tenant-1', organizationId: 'org-1', userId: 'user-1', })) expect(result).toEqual(expect.stringContaining('"written": true')) }) it.each(['mcp', 'tools-api'] as const)( 'queues non-destructive writes of a destructive-confirm-required agent on %s in approval mode', async (channel) => { seedAgent({ mutationPolicy: 'destructive-confirm-required' }) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container, channel, mutationMode: 'approval', apiKeyId: 'key-1', correlationId: 'corr-1', }) const result = await resolved.tools.test__mutation.execute?.({ title: 'Changed' }, executionOptions) expect(handler).not.toHaveBeenCalled() expect(prepareMutationMock).toHaveBeenCalledWith( expect.objectContaining({ toolCallArgs: { title: 'Changed' }, channel, apiKeyId: 'key-1', correlationId: 'corr-1' }), expect.anything(), ) expect(result).toEqual(expect.stringContaining('pending-confirmation')) expect(resolved.pendingActionIds).toEqual(['action-1']) }, ) it.each([ { mutationPolicyOverride: 'read-only' as const }, { authContext: { ...authContext, features: [] } }, ])('keeps tenant policy downgrades and tool ACL filtering', async (overrides) => { seedAgent() const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container, ...overrides }) expect(resolved.tools).toEqual({}) expect(handler).not.toHaveBeenCalled() expect(prepareMutationMock).not.toHaveBeenCalled() }) }) describe('confirm-required mutation input validation', () => { const inputSchema = z.object({ personId: z.string().uuid().optional(), note: z.string().min(1), subtitle: z.string().max(255).nullable().optional(), }) let handler: jest.Mock beforeEach(() => { jest.clearAllMocks() resetAgentRegistryForTests() toolRegistry.clear() handler = jest.fn(async () => ({ written: true })) const tool: AiToolDefinition = { name: 'test.mutation', description: 'Mutation fixture', inputSchema, isMutation: true, requiredFeatures: ['test.records.manage'], handler, } registerMcpTool(tool, { moduleId: 'test' }) prepareMutationMock.mockResolvedValue({ uiPart: { type: 'mutation-preview-card', data: { pendingActionId: 'action-1' } }, pendingAction: { id: 'action-1', expiresAt: new Date('2099-01-01'), status: 'pending' }, reused: false, }) seedAgent() }) afterEach(() => { resetAgentRegistryForTests() toolRegistry.clear() }) it('refuses to stage a pending action whose input fails the tool schema', async () => { const args = { personId: 'not-a-uuid', note: '' } expect(toSafeZodSchema(inputSchema).safeParse(args).success).toBe(true) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) await expect(resolved.tools.test__mutation.execute?.(args, executionOptions)).rejects.toThrow( /could not be prepared for confirmation: Invalid input: .*personId.*note/, ) expect(prepareMutationMock).not.toHaveBeenCalled() expect(handler).not.toHaveBeenCalled() expect(resolved.uiPartQueue.drain()).toEqual([]) }) it('refuses schema-invalid input when a destructive-confirm-required predicate gates the call', async () => { toolRegistry.clear() const tool: AiToolDefinition = { name: 'test.mutation', description: 'Mutation fixture', inputSchema, isMutation: true, isDestructive: () => true, requiredFeatures: ['test.records.manage'], handler, } registerMcpTool(tool, { moduleId: 'test' }) seedAgent({ mutationPolicy: 'destructive-confirm-required' }) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) await expect( resolved.tools.test__mutation.execute?.({ personId: 'not-a-uuid', note: 'hello' }, executionOptions), ).rejects.toThrow(/could not be prepared for confirmation: Invalid input: personId/) expect(prepareMutationMock).not.toHaveBeenCalled() expect(handler).not.toHaveBeenCalled() }) it('refuses the same input on the direct path when the predicate does not gate the call', async () => { toolRegistry.clear() const tool: AiToolDefinition = { name: 'test.mutation', description: 'Mutation fixture', inputSchema, isMutation: true, isDestructive: () => false, requiredFeatures: ['test.records.manage'], handler, } registerMcpTool(tool, { moduleId: 'test' }) seedAgent({ mutationPolicy: 'destructive-confirm-required' }) const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) await expect( resolved.tools.test__mutation.execute?.({ personId: 'not-a-uuid', note: 'hello' }, executionOptions), ).rejects.toThrow(/failed: Invalid input: personId/) expect(prepareMutationMock).not.toHaveBeenCalled() expect(handler).not.toHaveBeenCalled() }) it('stages sanitized input with blank optional values dropped', async () => { const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) await resolved.tools.test__mutation.execute?.({ personId: '', note: 'hello' }, executionOptions) expect(prepareMutationMock).toHaveBeenCalledTimes(1) const stagedArgs = prepareMutationMock.mock.calls[0]?.[0].toolCallArgs expect(stagedArgs).toEqual({ note: 'hello' }) expect(inputSchema.safeParse(stagedArgs).success).toBe(true) }) it('stages input the schema already accepts as sent, blank values included', async () => { const resolved = await resolveAiAgentTools({ agentId: 'test.assistant', authContext, container }) await resolved.tools.test__mutation.execute?.({ note: 'hello', subtitle: '' }, executionOptions) expect(prepareMutationMock.mock.calls[0]?.[0].toolCallArgs).toEqual({ note: 'hello', subtitle: '' }) }) })