ki-protocol 1.0.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,16 @@
1
+ """ki-protocol — KubeIntellect SSE wire protocol, shared by server and clients.
2
+
3
+ Import the view you need:
4
+
5
+ from ki_protocol import wire # server emission models (flat wire shape)
6
+ from ki_protocol import events # client typed envelope + parse_event()
7
+
8
+ Both views describe protocol version `PROTOCOL_VERSION`; the wire module is
9
+ canonical for what the server sends, the events module is canonical for how
10
+ clients parse it. Class names overlap between the two views deliberately
11
+ (StatusEvent, TokenEvent, ...) — always import via the submodule.
12
+ """
13
+
14
+ from ki_protocol.wire import PROTOCOL_VERSION
15
+
16
+ __all__ = ["PROTOCOL_VERSION"]
ki_protocol/events.py ADDED
@@ -0,0 +1,177 @@
1
+ """
2
+ events.py — Typed client view of the KubeIntellect wire protocol.
3
+
4
+ Moved here from `kube_q/core/events.py` in the V4 monorepo merge (ADR-004);
5
+ the server emission models (the flat wire shape this module normalises) live
6
+ in `ki_protocol.wire`. Wire-format changes must update both modules together.
7
+
8
+ All backend → client messages use the envelope defined here.
9
+ The discriminated union ``Event`` covers every event type emitted by
10
+ KubeIntellect. New types must be added by extending the union — never
11
+ overload ``data`` shapes between types.
12
+
13
+ Wire format (SSE):
14
+ data: {"type": "status", "event_id": "...", "session_id": "...", ...}
15
+
16
+ Example usage:
17
+ event = parse_event(raw_dict)
18
+ match event:
19
+ case StatusEvent(data=d): print(d.message)
20
+ case TokenEvent(data=d): buffer += d.content
21
+ ...
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from typing import Annotated, Any, Literal
27
+
28
+ from pydantic import BaseModel, Field, TypeAdapter
29
+
30
+ # ── Per-type data payloads ────────────────────────────────────────────────────
31
+
32
+ class StatusData(BaseModel):
33
+ phase: str = ""
34
+ message: str = ""
35
+
36
+
37
+ class TokenData(BaseModel):
38
+ content: str
39
+ role: str = "assistant"
40
+
41
+
42
+ class ToolCallData(BaseModel):
43
+ tool_name: str = ""
44
+ args: dict[str, Any] = Field(default_factory=dict)
45
+ call_id: str = ""
46
+ dry_run: bool = False
47
+ # Legacy field emitted by some backends
48
+ tool: str = ""
49
+ message: str = ""
50
+
51
+
52
+ class ToolResultData(BaseModel):
53
+ call_id: str = ""
54
+ ok: bool = True
55
+ summary: str = ""
56
+ truncated: bool = False
57
+
58
+
59
+ class HitlRequestData(BaseModel):
60
+ action: str = ""
61
+ risk: str = ""
62
+ diff: str = ""
63
+ approval_id: str = ""
64
+
65
+
66
+ class UsageData(BaseModel):
67
+ prompt_tokens: int = 0
68
+ completion_tokens: int = 0
69
+ total_tokens: int = 0
70
+ model: str = ""
71
+
72
+
73
+ class FinalData(BaseModel):
74
+ content: str = ""
75
+ usage: UsageData | None = None
76
+ elapsed_ms: int = 0
77
+
78
+
79
+ class ErrorData(BaseModel):
80
+ code: str = ""
81
+ message: str = ""
82
+ retryable: bool = False
83
+
84
+
85
+ # ── Envelope base ─────────────────────────────────────────────────────────────
86
+
87
+ class _EventBase(BaseModel):
88
+ event_id: str = ""
89
+ session_id: str = ""
90
+ conversation_id: str = ""
91
+ timestamp: str = ""
92
+
93
+
94
+ # ── Typed event models ────────────────────────────────────────────────────────
95
+
96
+ class StatusEvent(_EventBase):
97
+ type: Literal["status"]
98
+ data: StatusData = Field(default_factory=StatusData)
99
+
100
+
101
+ class TokenEvent(_EventBase):
102
+ type: Literal["token"]
103
+ data: TokenData
104
+
105
+
106
+ class ToolCallEvent(_EventBase):
107
+ type: Literal["tool_call"]
108
+ data: ToolCallData = Field(default_factory=ToolCallData)
109
+
110
+
111
+ class ToolResultEvent(_EventBase):
112
+ type: Literal["tool_result"]
113
+ data: ToolResultData = Field(default_factory=ToolResultData)
114
+
115
+
116
+ class HitlRequestEvent(_EventBase):
117
+ type: Literal["hitl_request"]
118
+ data: HitlRequestData = Field(default_factory=HitlRequestData)
119
+
120
+
121
+ class UsageEvent(_EventBase):
122
+ type: Literal["usage"]
123
+ data: UsageData = Field(default_factory=UsageData)
124
+
125
+
126
+ class FinalEvent(_EventBase):
127
+ type: Literal["final"]
128
+ data: FinalData = Field(default_factory=FinalData)
129
+
130
+
131
+ class ErrorEvent(_EventBase):
132
+ type: Literal["error"]
133
+ data: ErrorData = Field(default_factory=ErrorData)
134
+
135
+
136
+ # ── Discriminated union ───────────────────────────────────────────────────────
137
+
138
+ Event = Annotated[
139
+ StatusEvent
140
+ | TokenEvent
141
+ | ToolCallEvent
142
+ | ToolResultEvent
143
+ | HitlRequestEvent
144
+ | UsageEvent
145
+ | FinalEvent
146
+ | ErrorEvent,
147
+ Field(discriminator="type"),
148
+ ]
149
+
150
+ # Module-level adapter — built once at import time, not per parse_event() call.
151
+ _event_adapter: TypeAdapter[Event] = TypeAdapter(Event)
152
+
153
+
154
+ # ── Parser ────────────────────────────────────────────────────────────────────
155
+
156
+ def parse_event(raw: dict[str, Any]) -> Event | None:
157
+ """Parse a raw SSE data dict into a typed Event.
158
+
159
+ Also handles the legacy KubeIntellect ``ki_event`` side-channel format
160
+ where data fields are at the top level of the event dict rather than
161
+ nested under a ``data`` key.
162
+
163
+ Returns None for unknown/malformed events.
164
+ """
165
+ from pydantic import ValidationError
166
+
167
+ # Normalise legacy ki_event format: type is at top level, data fields also
168
+ # at top level (no nested "data" key).
169
+ event_type = raw.get("type")
170
+ if event_type and "data" not in raw:
171
+ raw = dict(raw)
172
+ raw["data"] = {k: v for k, v in raw.items() if k != "type"}
173
+
174
+ try:
175
+ return _event_adapter.validate_python(raw)
176
+ except (ValidationError, Exception):
177
+ return None
ki_protocol/wire.py ADDED
@@ -0,0 +1,96 @@
1
+ """
2
+ Server emission models — the canonical flat wire shape (protocol 1.0).
3
+
4
+ These models define exactly what the KubeIntellect server serialises onto the
5
+ SSE `ki_event` side-channel:
6
+
7
+ {"type": "status", "phase": "...", "message": "...", "session_id": "...", "ts": ...}
8
+
9
+ Moved verbatim from `app/streaming/emitter.py` in the V4 monorepo merge
10
+ (ADR-004) so server and clients share one protocol definition. The client-side
11
+ typed view (envelope + `data`, with normalisation of this flat shape) lives in
12
+ `ki_protocol.events`. Wire-format changes must update both modules together.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from typing import Literal
18
+ from uuid import uuid4
19
+
20
+ from pydantic import BaseModel, Field
21
+
22
+ PROTOCOL_VERSION = "1.0"
23
+
24
+
25
+ class StatusEvent(BaseModel):
26
+ type: Literal["status"] = "status"
27
+ phase: str # loading | analyzing | investigating | dispatching | synthesizing
28
+ message: str
29
+ session_id: str
30
+ ts: float = Field(default_factory=time.time)
31
+
32
+
33
+ class ToolCallEvent(BaseModel):
34
+ type: Literal["tool_call"] = "tool_call"
35
+ tool: str
36
+ command: str | None = None # populated for run_kubectl
37
+ session_id: str
38
+ ts: float = Field(default_factory=time.time)
39
+
40
+
41
+ class ToolResultEvent(BaseModel):
42
+ type: Literal["tool_result"] = "tool_result"
43
+ tool: str
44
+ output: str # first 500 chars of tool output
45
+ session_id: str
46
+ ts: float = Field(default_factory=time.time)
47
+
48
+
49
+ class TokenEvent(BaseModel):
50
+ type: Literal["token"] = "token"
51
+ content: str
52
+ session_id: str
53
+ ts: float = Field(default_factory=time.time)
54
+
55
+
56
+ class FinalEvent(BaseModel):
57
+ type: Literal["final"] = "final"
58
+ session_id: str
59
+ ts: float = Field(default_factory=time.time)
60
+
61
+
62
+ class HitlRequestEvent(BaseModel):
63
+ type: Literal["hitl_request"] = "hitl_request"
64
+ action_id: str = Field(default_factory=lambda: str(uuid4()))
65
+ risk_level: str
66
+ command: str
67
+ stdin_yaml: str | None = None
68
+ session_id: str
69
+ ts: float = Field(default_factory=time.time)
70
+
71
+
72
+ class PlanEvent(BaseModel):
73
+ """Emitted by the coordinator when an investigation plan is produced."""
74
+ type: Literal["plan"] = "plan"
75
+ steps: list[dict] # list of {description, status}
76
+ session_id: str
77
+ ts: float = Field(default_factory=time.time)
78
+
79
+
80
+ class ErrorEvent(BaseModel):
81
+ type: Literal["error"] = "error"
82
+ error: str
83
+ session_id: str
84
+ ts: float = Field(default_factory=time.time)
85
+
86
+
87
+ Event = (
88
+ StatusEvent
89
+ | ToolCallEvent
90
+ | ToolResultEvent
91
+ | TokenEvent
92
+ | FinalEvent
93
+ | HitlRequestEvent
94
+ | PlanEvent
95
+ | ErrorEvent
96
+ )
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: ki-protocol
3
+ Version: 1.0.0
4
+ Summary: KubeIntellect wire protocol — single source of truth for the typed SSE event format shared by server and clients.
5
+ License: AGPL-3.0-or-later
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: pydantic>=2.10
8
+ Description-Content-Type: text/markdown
9
+
10
+ # ki-protocol
11
+
12
+ Single source of truth for the KubeIntellect SSE wire protocol (version 1.0).
13
+
14
+ Two views of the same protocol:
15
+
16
+ - `ki_protocol.wire` — the **emission models** used by the server. Flat shape:
17
+ `{"type": "...", <fields>, "session_id": "...", "ts": ...}`. This is exactly
18
+ what goes over the wire inside the `ki_event` side-channel.
19
+ - `ki_protocol.events` — the **typed client view**: an envelope/`data`
20
+ discriminated union plus `parse_event()`, which normalizes the flat wire
21
+ shape into the nested form. Used by kube-q and any SDK consumer.
22
+
23
+ Wire-format changes must update both views in the same commit — that is the
24
+ point of this package (before V4, the two definitions lived in separate repos
25
+ and drifted).
@@ -0,0 +1,6 @@
1
+ ki_protocol/__init__.py,sha256=FEV0NaMrf_CfttOVNM5Iz-rIF1BwcqqFpzw8k_9p80I,646
2
+ ki_protocol/events.py,sha256=957lmJdbBbCpeBkaj3RdJ8rKBJEeveGPWH38kQOWNNA,5179
3
+ ki_protocol/wire.py,sha256=DB7w49EWmbZcm3Y8dKRTe8ozBBy66cZIOYcP8FoqD_g,2605
4
+ ki_protocol-1.0.0.dist-info/METADATA,sha256=_F1Rs_VRT4QHXUG8FvYf2IF3KVOIx5E7TspjoOyUQAM,1037
5
+ ki_protocol-1.0.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ ki_protocol-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any