Skip to content

unaiverse.networking.session.sess_msg

The Session between two nodes uses short messages of its own: the handshake (HELLO, PROFILE_OFFER and the others), the keep-alive (PING and PONG), the reconnection (RESUME) and the goodbye (GOAWAY). This module defines them as plain Python values together with the codec that turns them into bytes and back. It sits at the bottom of the session layer and imports nothing from it. The Session builds and reads SessMsg objects without ever encoding them. Only the transport (P2P.send_session and P2P.get_messages) calls to_bytes and from_bytes.

The module holds five groups of objects.

  1. The four protocol identifiers on which the Session messages travel and the set that groups them.
  2. The three capability bits that each side announces in its HELLO or HELLO_ACK.
  3. The reason codes that a refusal or a goodbye carries, their names and reason_name.
  4. The message class SessMsg and the wrapper SessionInbound that pairs an inbound message with its sender.
  5. The values that the decision hook of a responder receives and returns: VerifiedTokenClaims, ProfileDecisionResult and WorldGrantSpec.

A developer meets the last group when writing a decision policy for node.set_decision_policy(...) and meets the reason codes in the logs and in the reasons of the Session events (see Networking). Everything else is used by the session layer and the transport only.

Wire format

Every Session message is one frame on a one-shot stream of its protocol. The first byte of the frame is a kind tag that names the message. The rest is the payload in one of two encodings.

  • The handshake messages and the goodbye (tags 0x01 to 0x0A) use the binary message format of the SDK. Its generated classes are imported only inside to_bytes and from_bytes. Importing this module therefore loads nothing heavy and works in the browser runtime.
  • The liveness and control messages added later (tags 0x0B to 0x10) use a small JSON object in UTF-8 with every bytes field written as a hexadecimal string.

Because the tag names the message, the receiver does not need to infer the message from the direction or the fields. The native networking library never parses these bytes and only carries them.

>>> m = SessMsg(SessMsg.KIND_PING, {"session_id": bytes.fromhex("9f2c6a0b4d1e7f3a8c5b2e6d0a4f1c7e"),
...                                  "nonce": bytes.fromhex("0011223344556677")})
>>> m.to_bytes()
b'\x0b{"session_id": "9f2c6a0b4d1e7f3a8c5b2e6d0a4f1c7e", "nonce": "0011223344556677"}'
>>> SessMsg.from_bytes(m.to_bytes()).fields
{'session_id': b'\x9f,j\x0bM\x1e\x7f:\x8c[.m\nO\x1c~', 'nonce': b'\x00\x11"3DUfw'}

Protocols

SESSION_HELLO_PROTOCOL module-attribute

SESSION_HELLO_PROTOCOL = '/unaiverse/session/hello/1.0.0'

"/unaiverse/session/hello/1.0.0". The protocol of HELLO and HELLO_ACK. A manager also answers a simultaneous open on it with a HELLO_ACK that carries SIMULTANEOUS_OPEN_LOSS.

SESSION_PROFILE_PROTOCOL module-attribute

SESSION_PROFILE_PROTOCOL = '/unaiverse/session/profile/1.0.0'

"/unaiverse/session/profile/1.0.0". The protocol of PROFILE_OFFER and PROFILE_DECISION.

SESSION_WORLD_PROTOCOL module-attribute

SESSION_WORLD_PROTOCOL = '/unaiverse/session/world/1.0.0'

"/unaiverse/session/world/1.0.0". The protocol of WORLD_GRANT. A world node sends the grant on it right after its decision. The decision and the grant travel on different protocols with no ordering guarantee and the joiner may therefore receive the grant first.

SESSION_CONTROL_PROTOCOL module-attribute

SESSION_CONTROL_PROTOCOL = '/unaiverse/session/control/1.0.0'

"/unaiverse/session/control/1.0.0". The protocol of everything that follows the handshake (GOAWAY, GOAWAY_ACK, PING, PONG, RESUME, RESUME_ACK, TOKEN_UPDATE and STOP_SENDING).

SESSION_PROTOCOL_IDS module-attribute

The frozenset of the four protocols above. P2P.get_messages uses it to split the inbound frames into Session messages and chat messages. SessionManager.deliver drops a message whose protocol is not in it.

Capability bits

Each side writes an int that combines these bits into the capabilities field of its HELLO or HELLO_ACK. They describe what the transport of that side can do and not what the code knows. The browser transport runs the same Session code and announces 0. A peer that sends 0 (any node older than the bits) gets the old behavior: messages of up to 50 MB in one frame, files inside the message and no stop. The node passes the bits of the peer to its transport when the Session reaches ESTABLISHED or RESUMED (see Large messages and files).

CAP_CHUNKED_FRAMES module-attribute

CAP_CHUNKED_FRAMES = 1 << 0

1 (bit 0). The side accepts chat messages larger than one chunk (5 MB) as a sequence of chunk frames on the same stream. One such message can reach 1 GB.

CAP_FILE_STREAM module-attribute

CAP_FILE_STREAM = 1 << 1

2 (bit 1). The side accepts file messages. The sender of a file message streams its files from disk in chunks next to the message. A node announces it only when its transport can stream files and Custom.ACCEPT_FILES is true.

CAP_STOP_SENDING module-attribute

CAP_STOP_SENDING = 1 << 2

4 (bit 2). The side stops sending a large message when its receiver asks with STOP_SENDING. A receiver sends STOP_SENDING only to a peer with this bit.

Inbound messages

SessionInbound module-attribute

SessionInbound = namedtuple('SessionInbound', ['peer_id', 'protocol_id', 'sess_msg'])

A namedtuple with three fields: peer_id (the sender as the transport verified it), protocol_id (one of SESSION_PROTOCOL_IDS) and sess_msg (the decoded SessMsg). The payload of a Session message carries neither the sender nor the protocol and the manager needs both to route it. P2P.get_messages builds one per inbound Session frame. NodeConn.pump_sessions hands each one to SessionManager.deliver of its network.

SessionInbound(peer_id="12D3KooW...", protocol_id="/unaiverse/session/control/1.0.0",
               sess_msg=SessMsg(kind="pong", fields={"session_id": b"...", "nonce": b"...", "ok": True}))

Reason codes

A reason code is an int that tells why a handshake was refused or why a Session ended. It travels in the reason_code field of HELLO_ACK, PROFILE_DECISION and RESUME_ACK and in the reason field of GOAWAY. The Sessions put its name into the reasons of their events (profile_rejected:NOT_IN_ALLOW_LIST, remote_goaway:WORLD_DISENGAGEMENT and so on). The values match the enumeration of the binary message format. The current SDK never sends some of the codes of the format and the text of each such code says so.

OK module-attribute

OK = 0

0. No error. A positive HELLO_ACK, PROFILE_DECISION or RESUME_ACK carries it.

VERSION_UNSUPPORTED module-attribute

VERSION_UNSUPPORTED = 1

1. The HELLO offered no protocol version that the responder speaks (the only version is "1.0"). The responder answers with it in HELLO_ACK and fails its Session.

OVERLOADED module-attribute

OVERLOADED = 2

2. Reserved for a responder that has no room for the peer. No code of the current SDK sends it.

NOT_AUTHORIZED module-attribute

NOT_AUTHORIZED = 3

3. The peer did not prove who it is. A responder sends it in PROFILE_DECISION when the signature sig_a or the token of the offer does not verify. The decision hook of a world node also returns it when the token of a joiner attests no world peer id or no world address.

NOT_IN_ALLOW_LIST module-attribute

NOT_IN_ALLOW_LIST = 4

4. The node id of the peer is not among the nodes that the owner of the responder allows. The decision hook of the node returns it.

CV_HASH_MISMATCH module-attribute

CV_HASH_MISMATCH = 5

5. The CV in the profile offered by the peer does not hash to the value that its token attests. The CV is therefore forged or stale. The decision hook of the node returns it.

ROLE_INCOMPATIBLE module-attribute

ROLE_INCOMPATIBLE = 6

6. A world found no role for the joiner. The decision hook of a world node returns it when World.assign_role returns None.

WORLD_BUSY module-attribute

WORLD_BUSY = 7

7. Reserved for a world that admits nobody at the moment. No code of the current SDK sends it.

HOSTED_REJECTED module-attribute

HOSTED_REJECTED = 8

8. The hosted agent or world refused the peer. The decision hook returns it for a profile that cannot be parsed. A world node also closes with it the world Session of a joiner whose role lacks the world bit or whose profile has no world address.

GRACEFUL_SHUTDOWN module-attribute

GRACEFUL_SHUTDOWN = 9

9. An ordinary goodbye and the default of Session.close, SessionManager.close_session and SessionManager.close_all. An agent also closes with it the Session of a peer it removes on purpose.

WORLD_DISENGAGEMENT module-attribute

WORLD_DISENGAGEMENT = 10

10. The node leaves a world or stops working with a peer of that world. NodeConn.remove_all_world_agents and the agent close the Sessions of the former companions with it. The companions then see CLOSED and do not try to reconnect.

WORLD_HANDOFF_COMPLETE module-attribute

WORLD_HANDOFF_COMPLETE = 11

11. The joiner closes with it the public Session that brought its grant once the world Session is established (NodeConn.complete_world_handoff). The node recognizes this name in the reason of CLOSED and does not purge the world.

ROLE_REVOKED module-attribute

ROLE_REVOKED = 12

12. Reserved for a world that takes a role back. No code of the current SDK sends it.

TOKEN_REVOKED module-attribute

TOKEN_REVOKED = 13

13. Reserved for a peer whose token the UNaIVERSE server revoked. No code of the current SDK sends it.

KICKED_BY_HOST module-attribute

KICKED_BY_HOST = 14

14. Reserved for a host that removes a peer. No code of the current SDK sends it.

LOCAL_ERROR module-attribute

LOCAL_ERROR = 15

15. Something failed on the side that sends it. A responder refuses with it an offer whose profile is not valid JSON or whose decision hook raised. An agent or a world closes with it the Session of a peer to which a send failed.

GRANT_EXPIRED module-attribute

GRANT_EXPIRED = 16

16. Reserved for a grant redeemed too late. No code of the current SDK sends it because a joiner checks the expiry itself and fails with world_grant_expired.

SIMULTANEOUS_OPEN_LOSS module-attribute

SIMULTANEOUS_OPEN_LOSS = 17

17. Two nodes dialed each other at the same time. The manager of the node with the smaller peer id keeps its initiator and sends this code in a HELLO_ACK to the other node. The initiator of the other node fails with this code if it is still waiting (see SessionManager).

SESSION_UNKNOWN module-attribute

SESSION_UNKNOWN = 18

18. The receiver holds no Session with that session_id (typically because it restarted). A RESUME_ACK with accepted=false carries it and the initiator then runs a new handshake or reports LOST.

TOKEN_EXPIRED module-attribute

TOKEN_EXPIRED = 19

19. The token of the peer expired more than 3600 s ago with no TOKEN_UPDATE in between. The Session sends GOAWAY with it from tick_keepalive.

PERIMETER_CUT module-attribute

PERIMETER_CUT = 20

20. Reserved for the perimeter of a world. No code of the current SDK sends it because the perimeter cuts a non-member without any goodbye.

REASON_NAME module-attribute

REASON_NAME: dict[int, str] = {OK: 'OK', VERSION_UNSUPPORTED: 'VERSION_UNSUPPORTED', OVERLOADED: 'OVERLOADED', NOT_AUTHORIZED: 'NOT_AUTHORIZED', NOT_IN_ALLOW_LIST: 'NOT_IN_ALLOW_LIST', CV_HASH_MISMATCH: 'CV_HASH_MISMATCH', ROLE_INCOMPATIBLE: 'ROLE_INCOMPATIBLE', WORLD_BUSY: 'WORLD_BUSY', HOSTED_REJECTED: 'HOSTED_REJECTED', GRACEFUL_SHUTDOWN: 'GRACEFUL_SHUTDOWN', WORLD_DISENGAGEMENT: 'WORLD_DISENGAGEMENT', WORLD_HANDOFF_COMPLETE: 'WORLD_HANDOFF_COMPLETE', ROLE_REVOKED: 'ROLE_REVOKED', TOKEN_REVOKED: 'TOKEN_REVOKED', KICKED_BY_HOST: 'KICKED_BY_HOST', LOCAL_ERROR: 'LOCAL_ERROR', GRANT_EXPIRED: 'GRANT_EXPIRED', SIMULTANEOUS_OPEN_LOSS: 'SIMULTANEOUS_OPEN_LOSS', SESSION_UNKNOWN: 'SESSION_UNKNOWN', TOKEN_EXPIRED: 'TOKEN_EXPIRED', PERIMETER_CUT: 'PERIMETER_CUT'}

The dict[int, str] that maps every reason code above to its name ({0: "OK", 1: "VERSION_UNSUPPORTED", ...}).

reason_name

reason_name(code: int) -> str
Source code in unaiverse/networking/session/sess_msg.py
def reason_name(code: int) -> str:
    """Gets the name of a reason code (replacement of ``spb.ReasonCode.Name``).

    Args:
        code: The reason code.

    Returns:
        The name of the reason code, or the code itself as a string when it is unknown.
    """
    return REASON_NAME.get(int(code), str(code))

Returns the name of a reason code as REASON_NAME gives it. The argument goes through int() first and an unknown code returns its decimal string (reason_name(99) == "99"). It never raises for an int. The Session and the manager call it to build the reasons of their events and their logs.

The message

SessMsg dataclass

SessMsg(kind: str, fields: dict[str, Any] = dict())

A Session message holds a kind and a dict of fields whose names follow the definition of the binary message format. bytes fields stay bytes and integers stay int. The class is a dataclass without validation and a missing field stays absent until the message is encoded. The Session builds messages with the kind constants below and reads their fields with get or msg["name"].

from unaiverse.networking.session import SessMsg

msg = SessMsg(SessMsg.KIND_GOAWAY, {"reason": 9, "drain_window_ms": 0, "session_id": sid})
msg.get("reason")           # 9
msg.get("missing", "n/a")   # "n/a"
msg["session_id"]           # the bytes of sid

The table lists every kind with its tag, its protocol and its fields in the order in which the codec writes them. The Session never writes the fields marked unused.

Constant kind Tag Protocol Fields
KIND_HELLO_REQ "hello_request" 0x01 hello session_id (16 bytes), nonce_a (32 bytes), protocol_versions (list of str), capabilities (int), client_id (str)
KIND_HELLO_RESP "hello_response" 0x02 hello chosen_version (str), capabilities, nonce_b (32 bytes), sig_b (bytes), reason_code (int)
KIND_PROFILE_OFFER "profile_offer" 0x03 profile profile (JSON bytes), sig_a (bytes), session_id, token (str)
KIND_PROFILE_DECISION "profile_decision" 0x04 profile accepted (bool), profile_b (JSON bytes), reason_code, hint_addrs (list, unused), retry_after_ms (unused), session_id, token
KIND_WORLD_GRANT "world_grant" 0x05 world grant_id (32 bytes), expiry_unix_ms (int), world_profile (bytes), role (int), code_bundle (bytes), initial_stats (bytes), rendezvous_tag (int)
KIND_WORLD_GRANT_ACK "world_grant_ack" 0x06 world received (bool). It is never sent and stays decodable for old joiners.
KIND_GOAWAY "goaway" 0x09 control reason (int), drain_window_ms (always 0), session_id
KIND_GOAWAY_ACK "goaway_ack" 0x0A control received (bool)
KIND_PING "ping" 0x0B control session_id, nonce (8 bytes)
KIND_PONG "pong" 0x0C control session_id, nonce, ok (bool)
KIND_RESUME "resume" 0x0D control session_id, nonce (8 bytes)
KIND_RESUME_ACK "resume_ack" 0x0E control session_id, nonce, accepted (bool), reason_code (int)
KIND_TOKEN_UPDATE "token_update" 0x0F control session_id, token (str)
KIND_STOP_SENDING "stop_sending" 0x10 control session_id, seq (int)

kind instance-attribute

kind: str

The kind of the message as one of the KIND_* strings.

fields class-attribute instance-attribute

fields: dict[str, Any] = field(default_factory=dict)

The fields of the message as a dict keyed by field name. It is empty by default.

KIND_HELLO_REQ class-attribute instance-attribute

KIND_HELLO_REQ = 'hello_request'

"hello_request". The HELLO that an initiator sends first. It opens the Session with its session_id and the nonce that the responder signs.

KIND_HELLO_RESP class-attribute instance-attribute

KIND_HELLO_RESP = 'hello_response'

"hello_response". The HELLO_ACK of the responder with its signature over nonce_a || session_id. A refusal carries a non-zero reason_code and empty fields.

KIND_PROFILE_OFFER class-attribute instance-attribute

KIND_PROFILE_OFFER = 'profile_offer'

"profile_offer". The profile and the token of the initiator with its signature over nonce_b || session_id.

KIND_PROFILE_DECISION class-attribute instance-attribute

KIND_PROFILE_DECISION = 'profile_decision'

"profile_decision". The answer of the responder. An acceptance carries its profile and its token. A refusal carries only accepted=False, the reason code and the session_id.

KIND_WORLD_GRANT class-attribute instance-attribute

KIND_WORLD_GRANT = 'world_grant'

"world_grant". The admission that a world node grants to a joiner. It is not signed and the joiner trusts it because both tokens of the public Session were verified.

KIND_WORLD_GRANT_ACK class-attribute instance-attribute

KIND_WORLD_GRANT_ACK = 'world_grant_ack'

"world_grant_ack". An acknowledgement of the grant that the current SDK never sends.

KIND_GOAWAY class-attribute instance-attribute

KIND_GOAWAY = 'goaway'

"goaway". The goodbye with its reason code. The session_id lets the receiver ignore a goodbye meant for an older Session.

KIND_GOAWAY_ACK class-attribute instance-attribute

KIND_GOAWAY_ACK = 'goaway_ack'

"goaway_ack". The acknowledgement of a GOAWAY. It has no session_id and the receiver matches it by its sender.

KIND_PING class-attribute instance-attribute

KIND_PING = 'ping'

"ping". The keep-alive of an established Session and the probe of a reconnecting responder.

KIND_PONG class-attribute instance-attribute

KIND_PONG = 'pong'

"pong". The answer to a PING with the same nonce. ok is true only when the receiver holds that Session in a usable state.

KIND_RESUME class-attribute instance-attribute

KIND_RESUME = 'resume'

"resume". The request of a reconnecting initiator to continue the Session with the same session_id.

KIND_RESUME_ACK class-attribute instance-attribute

KIND_RESUME_ACK = 'resume_ack'

"resume_ack". The answer to a RESUME with the same nonce. A refusal carries SESSION_UNKNOWN.

KIND_TOKEN_UPDATE class-attribute instance-attribute

KIND_TOKEN_UPDATE = 'token_update'

"token_update". The refreshed node token of the sender.

KIND_STOP_SENDING class-attribute instance-attribute

KIND_STOP_SENDING = 'stop_sending'

"stop_sending". The request of a receiver to stop the large message whose sequence number in the send queue of the peer is seq.

get

get(key: str, default: Any = None) -> Any
Source code in unaiverse/networking/session/sess_msg.py
def get(self, key: str, default: Any = None) -> Any:
    """Gets a field of the message, with a default for a missing one.

    Args:
        key: The field name (as in session.proto).
        default: The value to return when the field is missing (default: None).

    Returns:
        The value of the field, or the default.
    """
    return self.fields.get(key, default)

Returns the field key or default (None unless given) when the message lacks it. It never raises. The Session reads every field through it.

to_bytes

to_bytes() -> bytes
Source code in unaiverse/networking/session/sess_msg.py
def to_bytes(self) -> bytes:
    """Serializes the message to ``[1-byte kind tag] || payload`` wire bytes.

    The payload is protobuf for the handshake messages and a small JSON envelope for the
    liveness/resume control messages (which carry no protobuf at all).

    Returns:
        The wire bytes of the message.

    Raises:
        ValueError: If the kind of the message is unknown.
    """
    json_tag = _JSON_KIND_TO_TAG.get(self.kind)
    if json_tag is not None:
        spec = _JSON_KIND_FIELDS[self.kind]
        obj = {}
        for fn, is_bytes in spec.items():
            val = self.fields.get(fn)
            if val is None:
                continue
            obj[fn] = bytes(val).hex() if is_bytes else val
        return bytes([json_tag]) + json.dumps(obj).encode("utf-8")

    spec = _KIND_SPEC.get(self.kind)
    if spec is None:
        raise ValueError(f"SessMsg.to_bytes: unknown SessMsg kind '{self.kind}'")
    from . import session_pb2 as _spb  # Lazy: CPython conn layer only, never under Pyodide
    tag, cls_name, field_names = spec
    msg = getattr(_spb, cls_name)()
    for fn in field_names:
        if fn not in self.fields or self.fields[fn] is None:
            continue
        val = self.fields[fn]
        if fn in _REPEATED_FIELDS:
            getattr(msg, fn).extend(list(val))
        else:
            setattr(msg, fn, val)
    return bytes([tag]) + msg.SerializeToString()

Encodes the message as the kind tag followed by the payload and returns the bytes. A JSON kind writes every field that is present and not None with bytes turned into hexadecimal. Any other kind fills the generated class of the binary message format with the fields that are present and not None. An unknown kind raises ValueError and a field of the wrong type raises the error of the binary format. P2P.send_session calls it right before writing the frame and returns False when it raises.

from_bytes classmethod

from_bytes(payload: bytes, protocol_id: str | None = None) -> SessMsg
Source code in unaiverse/networking/session/sess_msg.py
@classmethod
def from_bytes(cls, payload: bytes, protocol_id: str | None = None) -> 'SessMsg':
    """Decodes ``[1-byte kind tag] || payload`` wire bytes into a SessMsg (inverse of :meth:`to_bytes`).

    Args:
        payload: The wire bytes.
        protocol_id: The protocol the bytes arrived on, only used in error messages (default: None).

    Returns:
        The decoded message.

    Raises:
        ValueError: If the payload is empty or its kind tag is unknown.
    """
    if not payload:
        raise ValueError("SessMsg.from_bytes: empty payload")
    json_kind = _JSON_TAG_TO_KIND.get(payload[0])
    if json_kind is not None:
        spec = _JSON_KIND_FIELDS[json_kind]
        obj = json.loads(payload[1:].decode("utf-8")) if len(payload) > 1 else {}
        fields = {}
        for fn, is_bytes in spec.items():
            if fn not in obj:
                fields[fn] = b"" if is_bytes else _JSON_FIELD_DEFAULTS.get(fn, 0)
                continue
            fields[fn] = bytes.fromhex(obj[fn]) if is_bytes else obj[fn]
        return cls(kind=json_kind, fields=fields)

    kind = _TAG_TO_KIND.get(payload[0])
    if kind is None:
        raise ValueError(f"SessMsg.from_bytes: unknown kind tag {payload[0]} on {protocol_id}")
    from . import session_pb2 as _spb  # Lazy: CPython conn layer only, never under Pyodide
    _tag, cls_name, field_names = _KIND_SPEC[kind]
    msg = getattr(_spb, cls_name)()
    msg.ParseFromString(payload[1:])
    fields = {}
    for fn in field_names:
        val = getattr(msg, fn)
        fields[fn] = list(val) if fn in _REPEATED_FIELDS else val
    return cls(kind=kind, fields=fields)

Decodes the bytes of one frame into a new SessMsg. protocol_id is used only in the error message. A JSON kind restores the bytes fields from hexadecimal and fills missing fields with defaults: b"" for bytes, False for ok and accepted, "" for token and 0 for the rest. A kind of the binary format gets every field of its kind with the defaults of that format and its list fields as list. An empty payload or an unknown tag raises ValueError and malformed content raises the error of the decoder. P2P.get_messages calls it for every inbound Session frame and drops a frame that fails to decode.

Decision values

VerifiedTokenClaims dataclass

VerifiedTokenClaims(node_id: str, cv_hash: str, p2p_peers: tuple = (), exp: int = 0, code_hash: str | None = None)

The claims of a node token that the UNaIVERSE server signed and the responder verified against the peer id of the transport. A frozen dataclass. The Session builds it after the verification and passes it to the decision hook. The hook trusts these claims more than the profile offered by the peer. The hook receives None instead when no token verifier is configured.

Field Type Default Meaning
node_id str required The node id of the peer. The allow list of the owner is checked against it.
cv_hash str required The hash of the CV of the peer. The CV in the offered profile must hash to it.
p2p_peers tuple () The peer ids of the node on the public and the world network. A world node uses them to admit the world peer id of a joiner.
exp int 0 The expiry of the token in Unix seconds.
code_hash str \| None None The hash of the stored code of a world, present only in the token of a world node. The joiner checks the code bundle of its grant against it.

node_id instance-attribute

node_id: str

The node id attested by the token.

cv_hash instance-attribute

cv_hash: str

The hash of the CV attested by the token.

p2p_peers class-attribute instance-attribute

p2p_peers: tuple = ()

The public and world peer ids attested by the token.

exp class-attribute instance-attribute

exp: int = 0

The expiry of the token in Unix seconds.

code_hash class-attribute instance-attribute

code_hash: str | None = None

The hash of the code of a world or None.

ProfileDecisionResult dataclass

ProfileDecisionResult(accepted: bool, reason_code: int = OK, world_grant: WorldGrantSpec | None = None)

What a decision hook returns for one offer. With accepted=False the responder sends a negative PROFILE_DECISION with reason_code and fails its Session. With accepted=True and no world_grant the responder accepts and enters ESTABLISHED. With accepted=True and a world_grant the responder is a world node on the public network that sends a grant and waits for the handoff.

Field Type Default Meaning
accepted bool required Whether the offer is accepted.
reason_code int OK The reason of a refusal. An acceptance ignores it.
world_grant WorldGrantSpec \| None None The grant to send. Only a world node on its public network returns one.
from unaiverse.networking.session import ProfileDecisionResult
from unaiverse.networking.session.sess_msg import NOT_IN_ALLOW_LIST

async def only_known(peer_id, node_id, profile, p2p_name, claims):
    if claims is None or claims.node_id not in {"node-lab-arm-01", "node-lab-cam-02"}:
        return ProfileDecisionResult(accepted=False, reason_code=NOT_IN_ALLOW_LIST)
    return ProfileDecisionResult(accepted=True)

accepted instance-attribute

accepted: bool

True to accept the offer.

reason_code class-attribute instance-attribute

reason_code: int = OK

The reason code sent with a refusal.

world_grant class-attribute instance-attribute

world_grant: WorldGrantSpec | None = None

The specification of the grant or None.

WorldGrantSpec dataclass

WorldGrantSpec(role: int, world_profile_bytes: bytes, rendezvous_tag: int, code_bundle: bytes = b'', initial_stats: bytes = b'', grant_ttl_ms: int = 30000)

The grant that a world node puts in the ProfileDecisionResult for a joiner on its public network. The Session turns it into a WORLD_GRANT and adds a random 32-byte grant_id and the expiry. The fields of type bytes are already serialized and the joiner decodes them.

Field Type Default Meaning
role int required The role bits assigned to the joiner.
world_profile_bytes bytes required The profile of the world serialized for the joiner. It travels as world_profile.
rendezvous_tag int required The tag of the roster of the world at the time of the grant. The joiner holds its dials toward the other members until a newer roster lists it.
code_bundle bytes b"" The code of the role, its behavior and the code of the statistics packed as one blob.
initial_stats bytes b"" The initial statistics of the world.
grant_ttl_ms int 30000 The validity of the grant in milliseconds from the time it is sent.

role instance-attribute

role: int

The role bits of the joiner.

world_profile_bytes instance-attribute

world_profile_bytes: bytes

The serialized profile of the world.

rendezvous_tag instance-attribute

rendezvous_tag: int

The roster tag at the time of the grant.

code_bundle class-attribute instance-attribute

code_bundle: bytes = b''

The packed code of the role.

initial_stats class-attribute instance-attribute

initial_stats: bytes = b''

The serialized initial statistics.

grant_ttl_ms class-attribute instance-attribute

grant_ttl_ms: int = 30000

The validity of the grant in milliseconds.