plato-i2i 0.1.0

I2I inter-agent protocol — message formatting, routing, trust-weighted delivery
Documentation
o

���i&�@svdZddlmZddlZddlZddlmZmZmZddl	m
Z
mZeGdd�d��ZGdd	�d	�Z
Gd
d�d�ZdS)z7Core protocol definitions for the I2I messaging system.�)�annotationsN)�asdict�	dataclass�field)�Any�Optionalc@sdeZdZUdZded<ded<ded<ded<dZded<eejd	�Zd
ed<ee	d	�Z
ded
<dS)�
I2IMessagea�A single I2I inter-agent message.

    Attributes:
        sender: Identifier of the sending agent.
        recipient: Identifier of the intended receiving agent.
        msg_type: Logical message type (e.g., ``QUERY``, ``RESPONSE``).
        content: Payload of the message.
        priority: Priority level -- ``P0``, ``P1``, or ``P2`` (lowest).
        timestamp: Unix epoch timestamp (float) when the message was created.
        metadata: Additional key/value context attached to the message.
    �str�sender�	recipient�msg_type�content�P2�priority)�default_factory�float�	timestamp�dict[str, Any]�metadataN)�__name__�
__module__�__qualname__�__doc__�__annotations__rr�timer�dictr�rr�'/tmp/kimi-i2i/src/plato_i2i/protocol.pyrs
rc@sveZdZdZdddd�Ze	d d!dd��Zed"dd��Zed#dd��Z	ed"dd��Z
ed$dd��Zed d%dd��ZdS)&�I2IProtocolzEMessage formatting, parsing, serialization, and validation utilities.r��)�P0�P1rrr
r	rrr
r�returnrcCst|||||d�S)a�Create a fully populated :class:`I2IMessage`.

        Args:
            sender: Sending agent identifier.
            recipient: Target agent identifier.
            msg_type: Message type discriminator.
            content: Message body.
            priority: ``P0`` / ``P1`` / ``P2`` (default ``P2``).

        Returns:
            A new :class:`I2IMessage` instance with the current timestamp.
        �r
rrr
r)rr$rrr�format_message's�zI2IProtocol.format_message�rawcCs|�d�s	td��|�dd�}|dkrtd��|d|���}||dd���}|�d	�}|dkr6td
��|d|���}||dd���}|�d�}|dkrq|�d
�}|dkr^td��|d|���}	||dd���}
n|d|���}	||dd���}
t||	||
d�S)u;Parse a human-readable ``[I2I:TYPE] sender -> recipient — content`` string.

        Args:
            raw: Input string in the human-readable format.

        Returns:
            The parsed :class:`I2IMessage`.

        Raises:
            ValueError: If *raw* does not conform to the expected pattern.
        z[I2I:zMessage must start with '[I2I:'�]������z$Missing closing ']' for message typerNz->zMissing '->' separatorr u—z- uMissing '—' content separator)r
rrr
)�
startswith�
ValueError�find�stripr)�clsr&�type_endr�	remainder�arrowr
�after_arrow�em_dashrr
rrr�
parse_messageCs6



�zI2IProtocol.parse_message�messagecCstjt|�dd�S)z�Convert an :class:`I2IMessage` to a wire-format JSON string.

        Args:
            message: Message to serialize.

        Returns:
            JSON-encoded string suitable for network transmission.
        )�,�:)�
separators)�json�dumpsr)r5rrr�	serializeus
zI2IProtocol.serializecCs�zt�|�}Wntjy}ztd|���|�d}~wwhd�}|t|���}|r2td|����t|d|d|d|d|�d	d
�|�dt���|�di�d
�S)aDReconstruct an :class:`I2IMessage` from a JSON wire-format string.

        Args:
            raw: JSON string previously produced by :meth:`serialize`.

        Returns:
            The reconstructed :class:`I2IMessage`.

        Raises:
            ValueError: If *raw* is not valid JSON or missing required keys.
        zInvalid JSON: N>r
r
rrzMissing required fields: r
rrr
rrrr)r
rrr
rrr)	r9�loads�JSONDecodeErrorr+�set�keysr�getr)r.r&�payload�exc�required�missingrrr�deserialize�s&
��

�zI2IProtocol.deserialize�boolcCshtt|jt�o
|j��dkt|jt�o|j��dkt|jt�o%|j��dkt|jt�o1|j��dkg�S)aCheck whether *message* has all required fields populated.

        A field is considered populated when it is a non-empty string.

        Args:
            message: Message to inspect.

        Returns:
            ``True`` if the message passes validation, else ``False``.
        �)�all�
isinstancer
r	r-rrr
)r.r5rrr�validate�s��zI2IProtocol.validate�min_prioritycCs&|j�|jd�}|j�|d�}||kS)adBlock messages whose priority is below the supplied threshold.

        Lower numeric rank == higher priority (``P0`` > ``P1`` > ``P2``).

        Args:
            message: Message to evaluate.
            min_priority: Minimum allowed priority (default ``P2``).

        Returns:
            ``True`` if *message* meets or exceeds the threshold.
        �c)�_PRIORITY_RANKr@r)r.r5rK�msg_rank�threshold_rankrrr�
priority_gate�s
zI2IProtocol.priority_gateN)r)r
r	rr	rr	r
r	rr	r#r)r&r	r#r)r5rr#r	)r5rr#rF)r5rrKr	r#rF)
rrrrrM�staticmethodr%�classmethodr4r;rErJrPrrrrr"s �1 rc@sNeZdZdZddd�Zdd
d�Zd dd
�Zd!dd�Zd"d#dd�Zd$dd�Z	dS)%�TrustRouterz�Routes messages to the most trusted agent among a set of candidates.

    Trust levels are floats in the inclusive range ``0.0`` to ``1.0``.
    r#�NonecCs
i|_dS)z Initialise an empty trust table.N)�_trust)�selfrrr�__init__�s
zTrustRouter.__init__�agent_idr	�trust_levelrcCs2d|kr
dkstd��td��||j|<dS)aRegister or update an agent's trust level.

        Args:
            agent_id: Unique agent identifier.
            trust_level: Trust score between ``0.0`` and ``1.0`` inclusive.

        Raises:
            ValueError: If *trust_level* is outside the ``[0.0, 1.0]`` range.
        �g�?z'trust_level must be between 0.0 and 1.0N)r+rU)rVrXrYrrr�	add_trust�s

�zTrustRouter.add_trustcCs|j�|d�S)z�Return the stored trust level for *agent_id*.

        Args:
            agent_id: Agent identifier.

        Returns:
            The trust level if known, otherwise ``0.0``.
        rZ)rUr@)rVrXrrr�	get_trust�s	zTrustRouter.get_trustr5r�available_agents�	list[str]�
Optional[str]cCsD|sdSd}d}|D]}|�|�}||kr|}|}q
|dkr dS|S)axPick the most-trusted agent from *available_agents*.

        Args:
            message: The message being routed (available for future extensibility).
            available_agents: Candidate agent identifiers.

        Returns:
            The identifier of the most trusted available agent, or ``None`` if
            no candidates are supplied or none are trusted.
        Ng�rZ�r\)rVr5r]�
best_agent�
best_score�agent�scorerrr�route�s
�zTrustRouter.route�333333�?�	min_trustrFcCs|�|�|kS)aCheck whether *agent_id* meets the minimum trust threshold.

        Args:
            agent_id: Agent identifier.
            min_trust: Minimum acceptable trust score (default ``0.3``).

        Returns:
            ``True`` if the agent's stored trust is >= *min_trust*.
        r`)rVrXrgrrr�
is_trusted	s
zTrustRouter.is_trustedrcCsH|js
ddddd�St|j���}t|�t|�t|�t|�t|�d�S)z�Return aggregate statistics for the trust table.

        Returns:
            Dictionary with keys ``count``, ``average_trust``, ``max_trust``,
            and ``min_trust``.  If the table is empty all numeric values are
            ``0.0``.
        rrZ)�count�
average_trust�	max_trustrg)rU�list�values�len�sum�max�min)rVrmrrr�statss��zTrustRouter.statsN)r#rT)rXr	rYrr#rT)rXr	r#r)r5rr]r^r#r_)rf)rXr	rgrr#rF)r#r)
rrrrrWr[r\rerhrrrrrrrS�s



rS)r�
__future__rr9r�dataclassesrrr�typingrrrrrSrrrr�<module>s(