nodus-protocol 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ """nodus-protocol — typed control-plane message contracts.
2
+
3
+ Envelopes:
4
+ RequestEnvelope — inbound request (id, method, params)
5
+ ResponseEnvelope — response (id, ok, result/error)
6
+ EventEnvelope — server-pushed event (event_type, payload, timestamp)
7
+
8
+ Codec:
9
+ encode(envelope) → str — JSON serialisation with _type discriminator
10
+ decode(raw) → envelope — JSON deserialisation
11
+
12
+ Versioning:
13
+ PROTOCOL_VERSION — current version string ("1.0")
14
+ is_compatible(v) — True if *v* is interoperable with this implementation
15
+ """
16
+ from .codec import decode, encode
17
+ from .messages import EventEnvelope, RequestEnvelope, ResponseEnvelope
18
+ from .versions import PROTOCOL_VERSION, is_compatible
19
+
20
+ __all__ = [
21
+ "RequestEnvelope",
22
+ "ResponseEnvelope",
23
+ "EventEnvelope",
24
+ "encode",
25
+ "decode",
26
+ "PROTOCOL_VERSION",
27
+ "is_compatible",
28
+ ]
@@ -0,0 +1,78 @@
1
+ """JSON encode/decode for protocol envelopes."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from datetime import datetime
6
+ from typing import Any, Union
7
+
8
+ from .messages import EventEnvelope, RequestEnvelope, ResponseEnvelope
9
+
10
+ _ENVELOPE_TYPES = {
11
+ "request": RequestEnvelope,
12
+ "response": ResponseEnvelope,
13
+ "event": EventEnvelope,
14
+ }
15
+
16
+
17
+ def _default_serialiser(obj: Any) -> Any:
18
+ if isinstance(obj, datetime):
19
+ return obj.isoformat()
20
+ raise TypeError(f"Object of type {type(obj).__name__} is not JSON serialisable")
21
+
22
+
23
+ def encode(
24
+ envelope: Union[RequestEnvelope, ResponseEnvelope, EventEnvelope]
25
+ ) -> str:
26
+ """Serialise an envelope to a compact JSON string.
27
+
28
+ The JSON object includes a ``"_type"`` discriminator so :func:`decode`
29
+ can reconstruct the correct class.
30
+ """
31
+ if isinstance(envelope, RequestEnvelope):
32
+ type_key = "request"
33
+ elif isinstance(envelope, ResponseEnvelope):
34
+ type_key = "response"
35
+ elif isinstance(envelope, EventEnvelope):
36
+ type_key = "event"
37
+ else:
38
+ raise TypeError(f"Cannot encode {type(envelope).__name__}")
39
+
40
+ data = {"_type": type_key, **_to_dict(envelope)}
41
+ return json.dumps(data, default=_default_serialiser)
42
+
43
+
44
+ def decode(
45
+ raw: str,
46
+ ) -> Union[RequestEnvelope, ResponseEnvelope, EventEnvelope]:
47
+ """Deserialise a JSON string into the appropriate envelope type.
48
+
49
+ Raises:
50
+ ValueError: If the JSON is malformed or the ``_type`` field is missing/unknown.
51
+ """
52
+ try:
53
+ data = json.loads(raw)
54
+ except json.JSONDecodeError as exc:
55
+ raise ValueError(f"Cannot decode protocol message: {exc}") from exc
56
+
57
+ type_key = data.pop("_type", None)
58
+ if type_key not in _ENVELOPE_TYPES:
59
+ raise ValueError(
60
+ f"Unknown envelope _type: {type_key!r}. Expected one of {sorted(_ENVELOPE_TYPES)}"
61
+ )
62
+
63
+ cls = _ENVELOPE_TYPES[type_key]
64
+ # Parse datetime fields
65
+ if type_key == "event" and "timestamp" in data and isinstance(data["timestamp"], str):
66
+ from datetime import timezone # noqa: PLC0415
67
+ data["timestamp"] = datetime.fromisoformat(data["timestamp"])
68
+
69
+ import inspect # noqa: PLC0415
70
+ valid_fields = {p for p in inspect.signature(cls.__init__).parameters if p != "self"}
71
+ filtered = {k: v for k, v in data.items() if k in valid_fields}
72
+ return cls(**filtered)
73
+
74
+
75
+ def _to_dict(obj: Any) -> dict[str, Any]:
76
+ """Shallow convert a dataclass to a dict."""
77
+ from dataclasses import asdict # noqa: PLC0415
78
+ return asdict(obj)
@@ -0,0 +1,80 @@
1
+ """Typed control-plane message envelopes."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, field
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Optional
7
+
8
+
9
+ @dataclass
10
+ class RequestEnvelope:
11
+ """An inbound control-plane request.
12
+
13
+ Attributes
14
+ ----------
15
+ id: Unique request ID (used to correlate responses).
16
+ method: Method name (e.g. ``"agent.run"``, ``"session.get"``).
17
+ params: Method-specific parameters.
18
+ idempotency_key: Optional deduplication key; defaults to *id*.
19
+ trace_id: Distributed trace ID for observability.
20
+ protocol_version: Sender's protocol version string.
21
+ """
22
+
23
+ id: str
24
+ method: str
25
+ params: dict[str, Any]
26
+ idempotency_key: Optional[str] = None
27
+ trace_id: Optional[str] = None
28
+ protocol_version: str = "1.0"
29
+
30
+ def __post_init__(self) -> None:
31
+ if self.idempotency_key is None:
32
+ self.idempotency_key = self.id
33
+
34
+
35
+ @dataclass
36
+ class ResponseEnvelope:
37
+ """The outcome of a control-plane request.
38
+
39
+ Attributes
40
+ ----------
41
+ id: Matches the ``RequestEnvelope.id`` this responds to.
42
+ ok: True on success, False on error.
43
+ result: Success payload (when ok=True).
44
+ error: Human-readable error message (when ok=False).
45
+ error_code: Machine-readable error code (when ok=False).
46
+ trace_id: Propagated trace ID.
47
+ duration_ms: Server-side processing time in milliseconds.
48
+ """
49
+
50
+ id: str
51
+ ok: bool
52
+ result: Optional[dict[str, Any]] = None
53
+ error: Optional[str] = None
54
+ error_code: Optional[str] = None
55
+ trace_id: Optional[str] = None
56
+ duration_ms: Optional[int] = None
57
+
58
+
59
+ @dataclass
60
+ class EventEnvelope:
61
+ """A server-pushed event, not a response to a specific request.
62
+
63
+ Attributes
64
+ ----------
65
+ event_type: Dot-separated type string (e.g. ``"agent.block"``, ``"session.ended"``).
66
+ payload: Event-specific data.
67
+ source: Component that emitted the event.
68
+ correlation_id: Links related events in an execution chain.
69
+ trace_id: Distributed trace ID.
70
+ timestamp: UTC timestamp when the event was emitted.
71
+ """
72
+
73
+ event_type: str
74
+ payload: dict[str, Any]
75
+ source: Optional[str] = None
76
+ correlation_id: Optional[str] = None
77
+ trace_id: Optional[str] = None
78
+ timestamp: datetime = field(
79
+ default_factory=lambda: datetime.now(timezone.utc)
80
+ )
@@ -0,0 +1,12 @@
1
+ """Protocol version constants and compatibility checks."""
2
+ from __future__ import annotations
3
+
4
+ PROTOCOL_VERSION = "1.0"
5
+
6
+ # Versions this implementation can interoperate with
7
+ _COMPATIBLE_VERSIONS: frozenset[str] = frozenset({"1.0"})
8
+
9
+
10
+ def is_compatible(version: str) -> bool:
11
+ """Return True if *version* is compatible with this implementation."""
12
+ return version in _COMPATIBLE_VERSIONS
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: nodus-protocol
3
+ Version: 0.1.0
4
+ Summary: Typed control-plane message contracts: RequestEnvelope, ResponseEnvelope, EventEnvelope
5
+ Author: Shawn Knight
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Masterplanner25/nodus-protocol
8
+ Project-URL: Repository, https://github.com/Masterplanner25/nodus-protocol
9
+ Requires-Python: >=3.11
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8.0; extra == "dev"
14
+ Dynamic: license-file
15
+
16
+ # nodus-protocol
17
+
18
+ **Typed control-plane message contracts for Nodus AI systems.**
19
+
20
+ Defines the wire format for request/response/event envelopes exchanged
21
+ between Nodus components (gateway, agents, channels). JSON codec with a
22
+ `_type` discriminator for safe deserialization. No required external
23
+ dependencies — pure stdlib.
24
+
25
+ > **Status:** v0.1.0 — prepared, not yet published.
26
+
27
+ ---
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ pip install nodus-protocol
33
+ ```
34
+
35
+ ---
36
+
37
+ ## What it provides
38
+
39
+ | Component | Purpose |
40
+ |---|---|
41
+ | `RequestEnvelope` | Inbound request: `id`, `method`, `params` |
42
+ | `ResponseEnvelope` | Response: `id`, `ok`, `result` or `error` |
43
+ | `EventEnvelope` | Server-pushed event: `event_type`, `payload`, `timestamp` |
44
+ | `encode(envelope)` | Serialize to JSON string with `_type` discriminator |
45
+ | `decode(raw)` | Deserialize JSON string to typed envelope |
46
+ | `PROTOCOL_VERSION` | Current version string (`"1.0"`) |
47
+ | `is_compatible(v)` | Check interoperability with another version |
48
+
49
+ ---
50
+
51
+ ## Quick start
52
+
53
+ ```python
54
+ from nodus_protocol import RequestEnvelope, ResponseEnvelope, encode, decode
55
+
56
+ req = RequestEnvelope(id="req-001", method="agent.run", params={"objective": "hello"})
57
+ wire = encode(req)
58
+ # '{"_type": "request", "id": "req-001", "method": "agent.run", ...}'
59
+
60
+ decoded = decode(wire)
61
+ assert isinstance(decoded, RequestEnvelope)
62
+ assert decoded.method == "agent.run"
63
+
64
+ resp = ResponseEnvelope(id="req-001", ok=True, result={"run_id": "run-abc"})
65
+ ```
66
+
67
+ ---
68
+
69
+ ## Envelopes
70
+
71
+ **RequestEnvelope** — `id` (str), `method` (str), `params` (dict | None)
72
+
73
+ **ResponseEnvelope** — `id` (str), `ok` (bool), `result` (any | None), `error` (str | None)
74
+
75
+ **EventEnvelope** — `event_type` (str), `payload` (dict | None), `timestamp` (float, auto-set UTC epoch)
76
+
77
+ ---
78
+
79
+ ## Codec
80
+
81
+ ```python
82
+ from nodus_protocol import encode, decode
83
+
84
+ wire = encode(envelope) # JSON str with "_type" discriminator
85
+ envelope = decode(wire) # RequestEnvelope | ResponseEnvelope | EventEnvelope
86
+ ```
87
+
88
+ `decode` routes on `_type`. Raises `ValueError` on unknown type or malformed JSON.
89
+
90
+ ---
91
+
92
+ ## Versioning
93
+
94
+ ```python
95
+ from nodus_protocol import PROTOCOL_VERSION, is_compatible
96
+
97
+ print(PROTOCOL_VERSION) # "1.0"
98
+ is_compatible("1.0") # True
99
+ is_compatible("1.1") # True (minor compatible)
100
+ is_compatible("2.0") # False (major mismatch)
101
+ ```
102
+
103
+ ---
104
+
105
+ ## Design
106
+
107
+ - **No required dependencies.** Pure stdlib (`json`, `dataclasses`, `datetime`).
108
+ - **`_type` discriminator.** Every encoded envelope includes `_type` so
109
+ `decode` can reconstruct the correct class without out-of-band schema info.
110
+
111
+ ---
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ pip install -e ".[dev]"
117
+ pytest tests/ -q
118
+ ```
119
+
120
+ ---
121
+
122
+ ## License
123
+
124
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ nodus_protocol/__init__.py,sha256=0l-E5thHTdwT1ln9OzovtZqe29O_KzAriXuYZ0icYp4,886
2
+ nodus_protocol/codec.py,sha256=dags0Brx2wbHlsMfJSIq1Xy2c42S0uCgXgVxUJnc5xo,2534
3
+ nodus_protocol/messages.py,sha256=T5Y-6S21BEO9m1HpJ8TB3QOI8yIuShnkLRZMNIE3z_o,2466
4
+ nodus_protocol/versions.py,sha256=4g6-_qvTOy__vnTaZ8f_SCOXwmKiv014P_CSiUD5-uw,393
5
+ nodus_protocol-0.1.0.dist-info/licenses/LICENSE,sha256=fPXtVFKk3GVjyErjlaH2F56cuzEfzln8OP_ElB7cXTI,1069
6
+ nodus_protocol-0.1.0.dist-info/METADATA,sha256=io-2g5q5T61Xq8z599Y2pE27Oos7vVDXkzqPWlCwQUk,3322
7
+ nodus_protocol-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ nodus_protocol-0.1.0.dist-info/top_level.txt,sha256=c2P8vnCsWPl0sBfHXoSSi3B3SI-lkikEok0WvFtqUiE,15
9
+ nodus_protocol-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shawn Knight
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ nodus_protocol