Esempio n. 1
0
    def send_unsupported_skill(self, envelope: Envelope) -> None:
        """
        Handle the received envelope in case the skill is not supported.

        :param envelope: the envelope
        :return: None
        """
        if envelope.skill_id is None:
            self.context.logger.warning(
                "Cannot handle envelope: no active handler registered for the protocol_id='{}'."
                .format(envelope.protocol_id))
        else:
            self.context.logger.warning(
                "Cannot handle envelope: no active handler registered for the protocol_id='{}' and skill_id='{}'."
                .format(envelope.protocol_id, envelope.skill_id))
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.UNSUPPORTED_SKILL,
            error_msg="Unsupported skill.",
            error_data={"envelope": encoded_envelope},
        )
        reply.counterparty = envelope.sender
        reply.sender = self.context.agent_address
        self.context.outbox.put_message(message=reply)
Esempio n. 2
0
    def send_unsupported_protocol(self, envelope: Envelope) -> None:
        """
        Handle the received envelope in case the protocol is not supported.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Unsupported protocol: {}. You might want to add a handler for this protocol."
            .format(envelope.protocol_id))
        encoded_protocol_id = base64.b85encode(
            str.encode(str(envelope.protocol_id)))
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.UNSUPPORTED_PROTOCOL,
            error_msg="Unsupported protocol.",
            error_data={
                "protocol_id": encoded_protocol_id,
                "envelope": encoded_envelope,
            },
        )
        reply.counterparty = envelope.sender
        reply.sender = self.context.agent_address
        self.context.outbox.put_message(message=reply)
Esempio n. 3
0
def test_outbox_put():
    """Tests that an envelope is putted into the queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.counterparty = receiver_address
    msg.sender = agent_address
    dummy_connection = _make_dummy_connection()
    multiplexer = Multiplexer([dummy_connection])
    outbox = OutBox(multiplexer, agent_address)
    inbox = InBox(multiplexer)
    multiplexer.connect()
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=DefaultMessage.protocol_id,
        message=msg,
    )
    outbox.put(envelope)
    time.sleep(0.5)
    assert not inbox.empty(
    ), "Inbox must not be empty after putting an envelope"
    multiplexer.disconnect()
Esempio n. 4
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        DEFAULT_PRIVATE_KEY_FILE)
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(DEFAULT_LEDGER, private_key_path)
        builder.add_protocol(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        local_connection_id = PublicId.from_str("fetchai/local:0.6.0")
        builder.set_default_connection(local_connection_id)
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        agent = builder.build(
            connection_ids=[PublicId.from_str("fetchai/local:0.6.0")])
        # This is a temporary workaround to feed the local node to the OEF Local connection
        # TODO remove it.
        local_connection = agent.resources.get_connection(local_connection_id)
        local_connection._local_node = node

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.counterparty = agent.identity.address
        msg.sender = agent.identity.address
        envelope = Envelope(
            to=msg.counterparty,
            sender=msg.sender,
            protocol_id=msg.protocol_id,
            message=msg,
        )

        with run_in_thread(agent.start, timeout=20, on_exit=agent.stop):
            wait_for_condition(lambda: agent.is_running, timeout=20)
            agent.outbox.put(envelope)
            default_protocol_public_id = DefaultMessage.protocol_id
            dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID
            handler = agent.resources.get_handler(default_protocol_public_id,
                                                  dummy_skill_public_id)
            assert handler is not None, "Handler is not set."
            wait_for_condition(
                lambda: len(handler.handled_messages) > 0,
                timeout=20,
                error_msg="The message is not inside the handled_messages.",
            )
Esempio n. 5
0
def _try_construct_envelope(agent_name: str, sender: str,
                            dialogues: DefaultDialogues) -> Optional[Envelope]:
    """Try construct an envelope from user input."""
    envelope = None  # type: Optional[Envelope]
    try:
        performative_str = "bytes"
        performative = DefaultMessage.Performative(performative_str)
        click.echo(
            "Provide message of protocol fetchai/default:0.4.0 for performative {}:"
            .format(performative_str))
        message_escaped = input()  # nosec
        message_escaped = message_escaped.strip()
        if message_escaped == "":
            raise InterruptInputException
        if performative == DefaultMessage.Performative.BYTES:
            message_decoded = codecs.decode(message_escaped.encode("utf-8"),
                                            "unicode-escape")
            message = message_decoded.encode(
                "utf-8")  # type: Union[str, bytes]
        else:
            message = message_escaped  # pragma: no cover
        dialogue_reference = dialogues.new_self_initiated_dialogue_reference()
        msg = DefaultMessage(
            performative=performative,
            dialogue_reference=dialogue_reference,
            content=message,
        )
        msg.counterparty = agent_name
        msg.sender = sender
        assert dialogues.update(msg) is not None
        envelope = Envelope(
            to=msg.counterparty,
            sender=msg.sender,
            protocol_id=msg.protocol_id,
            message=msg,
        )
    except InterruptInputException:
        click.echo("Interrupting input, checking inbox ...")
    except KeyboardInterrupt as e:
        raise e
    except BaseException as e:  # pylint: disable=broad-except # pragma: no cover
        click.echo(e)
    return envelope
Esempio n. 6
0
async def test_inbox_outbox():
    """Test InBox OutBox objects."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections, loop=asyncio.get_event_loop())
    msg = DefaultMessage(performative=DefaultMessage.Performative.BYTES, content=b"",)
    msg.counterparty = "to"
    msg.sender = "sender"
    context = EnvelopeContext(connection_id=connection_1.connection_id)
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_id=msg.protocol_id,
        message=msg,
        context=context,
    )
    try:
        await multiplexer.connect()
        inbox = InBox(multiplexer)
        outbox = OutBox(multiplexer, "default_address")

        assert inbox.empty()
        assert outbox.empty()

        outbox.put(envelope)
        received = await inbox.async_get()
        assert received == envelope

        assert inbox.empty()
        assert outbox.empty()

        outbox.put_message(msg, context=context)
        await inbox.async_wait()
        received = inbox.get_nowait()
        assert received == envelope

    finally:
        await multiplexer.disconnect()
Esempio n. 7
0
    def send_decoding_error(self, envelope: Envelope) -> None:
        """
        Handle a decoding error.

        :param envelope: the envelope
        :return: None
        """
        self.context.logger.warning(
            "Decoding error for envelope: {}. Protocol_id='{}' and message='{!r}' are inconsistent."
            .format(envelope, envelope.protocol_id, envelope.message))
        encoded_envelope = base64.b85encode(envelope.encode())
        reply = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.ERROR,
            error_code=DefaultMessage.ErrorCode.DECODING_ERROR,
            error_msg="Decoding error.",
            error_data={"envelope": encoded_envelope},
        )
        reply.counterparty = envelope.sender
        reply.sender = self.context.agent_address
        self.context.outbox.put_message(message=reply)
Esempio n. 8
0
def test_outbox_put_message():
    """Tests that an envelope is created from the message is in the queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.counterparty = receiver_address
    msg.sender = agent_address
    dummy_connection = _make_dummy_connection()
    multiplexer = Multiplexer([dummy_connection])
    outbox = OutBox(multiplexer, agent_address)
    inbox = InBox(multiplexer)
    multiplexer.connect()
    outbox.put_message(msg)
    time.sleep(0.5)
    assert not inbox.empty(
    ), "Inbox will not be empty after putting a message."
    multiplexer.disconnect()
Esempio n. 9
0
def test_initialize_aea_programmatically_build_resources():
    """Test that we can initialize the agent by building the resource object."""
    try:
        temp = tempfile.mkdtemp(prefix="test_aea_resources")
        with LocalNode() as node:
            agent_name = "MyAgent"
            private_key_path = os.path.join(CUR_PATH, "data",
                                            DEFAULT_PRIVATE_KEY_FILE)
            wallet = Wallet({DEFAULT_LEDGER: private_key_path})
            identity = Identity(agent_name,
                                address=wallet.addresses[DEFAULT_LEDGER])
            connection = _make_local_connection(agent_name, node)

            resources = Resources()
            aea = AEA(
                identity,
                wallet,
                resources=resources,
                default_connection=connection.public_id,
            )

            default_protocol = Protocol.from_dir(
                str(Path(AEA_DIR, "protocols", "default")))
            resources.add_protocol(default_protocol)
            resources.add_connection(connection)

            error_skill = Skill.from_dir(str(Path(AEA_DIR, "skills", "error")),
                                         agent_context=aea.context)
            dummy_skill = Skill.from_dir(str(
                Path(CUR_PATH, "data", "dummy_skill")),
                                         agent_context=aea.context)
            resources.add_skill(dummy_skill)
            resources.add_skill(error_skill)

            default_protocol_id = DefaultMessage.protocol_id

            expected_message = DefaultMessage(
                dialogue_reference=("", ""),
                message_id=1,
                target=0,
                performative=DefaultMessage.Performative.BYTES,
                content=b"hello",
            )
            expected_message.counterparty = agent_name
            expected_message.sender = agent_name

            with run_in_thread(aea.start, timeout=5, on_exit=aea.stop):
                wait_for_condition(lambda: aea.is_running, timeout=10)
                aea.outbox.put(
                    Envelope(
                        to=agent_name,
                        sender=agent_name,
                        protocol_id=default_protocol_id,
                        message=expected_message,
                    ))

                dummy_skill_id = DUMMY_SKILL_PUBLIC_ID
                dummy_behaviour_name = "dummy"
                dummy_behaviour = aea.resources.get_behaviour(
                    dummy_skill_id, dummy_behaviour_name)
                wait_for_condition(lambda: dummy_behaviour is not None,
                                   timeout=10)
                wait_for_condition(lambda: dummy_behaviour.nb_act_called > 0,
                                   timeout=10)

                dummy_task = DummyTask()
                task_id = aea.task_manager.enqueue_task(dummy_task)
                async_result = aea.task_manager.get_task_result(task_id)
                expected_dummy_task = async_result.get(10.0)
                wait_for_condition(
                    lambda: expected_dummy_task.nb_execute_called > 0,
                    timeout=10)
                dummy_handler_name = "dummy"
                dummy_handler = aea.resources._handler_registry.fetch(
                    (dummy_skill_id, dummy_handler_name))
                dummy_handler_alt = aea.resources.get_handler(
                    DefaultMessage.protocol_id, dummy_skill_id)
                wait_for_condition(lambda: dummy_handler == dummy_handler_alt,
                                   timeout=10)
                wait_for_condition(lambda: dummy_handler is not None,
                                   timeout=10)
                wait_for_condition(
                    lambda: len(dummy_handler.handled_messages) == 1,
                    timeout=10)
                wait_for_condition(
                    lambda: dummy_handler.handled_messages[0] ==
                    expected_message,
                    timeout=10,
                )
    finally:
        Path(temp).rmdir()
Esempio n. 10
0
def test_initialize_aea_programmatically():
    """Test that we can initialize an AEA programmatically."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        DEFAULT_PRIVATE_KEY_FILE)
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(DEFAULT_LEDGER, private_key_path)
        builder.add_protocol(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        local_connection_id = PublicId.from_str("fetchai/local:0.6.0")
        builder.set_default_connection(local_connection_id)
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        aea = builder.build(
            connection_ids=[PublicId.from_str("fetchai/local:0.6.0")])
        local_connection = aea.resources.get_connection(local_connection_id)
        local_connection._local_node = node

        expected_message = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        expected_message.counterparty = aea.identity.address
        expected_message.sender = aea.identity.address
        envelope = Envelope(
            to=expected_message.counterparty,
            sender=expected_message.sender,
            protocol_id=expected_message.protocol_id,
            message=expected_message,
        )

        with run_in_thread(aea.start, timeout=5, on_exit=aea.stop):
            wait_for_condition(lambda: aea.is_running, timeout=10)
            aea.outbox.put(envelope)

            dummy_skill_id = DUMMY_SKILL_PUBLIC_ID
            dummy_behaviour_name = "dummy"
            dummy_behaviour = aea.resources.get_behaviour(
                dummy_skill_id, dummy_behaviour_name)
            wait_for_condition(lambda: dummy_behaviour is not None, timeout=10)
            wait_for_condition(lambda: dummy_behaviour.nb_act_called > 0,
                               timeout=10)

            # TODO the previous code caused an error:
            #      _pickle.PicklingError: Can't pickle <class 'tasks.DummyTask'>: import of module 'tasks' failed
            dummy_task = DummyTask()
            task_id = aea.task_manager.enqueue_task(dummy_task)
            async_result = aea.task_manager.get_task_result(task_id)
            expected_dummy_task = async_result.get(10.0)
            wait_for_condition(
                lambda: expected_dummy_task.nb_execute_called > 0, timeout=10)

            dummy_handler = aea.resources.get_handler(
                DefaultMessage.protocol_id, dummy_skill_id)
            dummy_handler_alt = aea.resources._handler_registry.fetch(
                (dummy_skill_id, "dummy"))
            wait_for_condition(lambda: dummy_handler == dummy_handler_alt,
                               timeout=10)
            wait_for_condition(lambda: dummy_handler is not None, timeout=10)
            wait_for_condition(
                lambda: len(dummy_handler.handled_messages) == 1, timeout=10)
            wait_for_condition(
                lambda: dummy_handler.handled_messages[0] == expected_message,
                timeout=10,
            )
Esempio n. 11
0
def test_handle():
    """Tests handle method of an agent."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        DEFAULT_PRIVATE_KEY_FILE)
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(DEFAULT_LEDGER, private_key_path)
        builder.add_protocol(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        local_connection_id = PublicId.from_str("fetchai/local:0.6.0")
        builder.set_default_connection(local_connection_id)
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        aea = builder.build(
            connection_ids=[PublicId.from_str("fetchai/local:0.6.0")])
        # This is a temporary workaround to feed the local node to the OEF Local connection
        # TODO remove it.
        local_connection = aea.resources.get_connection(local_connection_id)
        local_connection._local_node = node

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.counterparty = aea.identity.address
        msg.sender = aea.identity.address
        envelope = Envelope(
            to=msg.counterparty,
            sender=msg.sender,
            protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
            message=msg,
        )

        with run_in_thread(aea.start, timeout=5):
            wait_for_condition(lambda: aea.is_running, timeout=10)
            dummy_skill = aea.resources.get_skill(DUMMY_SKILL_PUBLIC_ID)
            dummy_handler = dummy_skill.handlers["dummy"]

            aea.outbox.put(envelope)

            wait_for_condition(
                lambda: len(dummy_handler.handled_messages) == 1,
                timeout=1,
            )

            #   DECODING ERROR
            envelope = Envelope(
                to=aea.identity.address,
                sender=aea.identity.address,
                protocol_id=DefaultMessage.protocol_id,
                message=b"",
            )
            # send envelope via localnode back to agent/bypass `outbox` put consistency checks
            aea.outbox._multiplexer.put(envelope)
            """ inbox twice cause first message is invalid. generates error message and it accepted """
            wait_for_condition(
                lambda: len(dummy_handler.handled_messages) == 2,
                timeout=1,
            )
            #   UNSUPPORTED SKILL
            msg = FipaMessage(
                performative=FipaMessage.Performative.ACCEPT,
                message_id=1,
                dialogue_reference=(str(0), ""),
                target=0,
            )
            msg.counterparty = aea.identity.address
            msg.sender = aea.identity.address
            envelope = Envelope(
                to=msg.counterparty,
                sender=msg.sender,
                protocol_id=msg.protocol_id,
                message=msg,
            )
            # send envelope via localnode back to agent
            aea.outbox.put(envelope)
            wait_for_condition(
                lambda: len(dummy_handler.handled_messages) == 3,
                timeout=2,
            )
            aea.stop()