nini-protocol 0.4.1__tar.gz → 0.4.2__tar.gz
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.
- {nini_protocol-0.4.1 → nini_protocol-0.4.2}/PKG-INFO +1 -1
- nini_protocol-0.4.2/nini_protocol/__init__.py +164 -0
- nini_protocol-0.4.2/nini_protocol/models.py +939 -0
- {nini_protocol-0.4.1 → nini_protocol-0.4.2}/pyproject.toml +1 -1
- {nini_protocol-0.4.1 → nini_protocol-0.4.2}/LICENSE +0 -0
- {nini_protocol-0.4.1 → nini_protocol-0.4.2}/README.md +0 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Nini wire protocol: the single source of truth for service, clients and UIs.
|
|
2
|
+
|
|
3
|
+
Contract: ``docs/nini/protocol/20261202-nini-contract-v1.md`` (v1, FROZEN).
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from nini_protocol.models import (
|
|
7
|
+
ALL_TOOLS_SCOPE,
|
|
8
|
+
CORE_MODELS,
|
|
9
|
+
DEFAULT_PERMISSION_SCOPE,
|
|
10
|
+
EVENT_DATA_MODELS,
|
|
11
|
+
KNOWN_EVENT_TYPES,
|
|
12
|
+
PARAMETERIZED_MODELS,
|
|
13
|
+
PERMISSION_SCOPES,
|
|
14
|
+
PROTOCOL_VERSION,
|
|
15
|
+
Attachment,
|
|
16
|
+
ClientKind,
|
|
17
|
+
CreateSessionInput,
|
|
18
|
+
DecidedBy,
|
|
19
|
+
ErrorData,
|
|
20
|
+
Event,
|
|
21
|
+
EventType,
|
|
22
|
+
FileChangedData,
|
|
23
|
+
FileChangeKind,
|
|
24
|
+
FileContent,
|
|
25
|
+
FileDiff,
|
|
26
|
+
FileNode,
|
|
27
|
+
FileNodeItems,
|
|
28
|
+
FileNodeType,
|
|
29
|
+
FileTree,
|
|
30
|
+
HealthResponse,
|
|
31
|
+
Items,
|
|
32
|
+
Message,
|
|
33
|
+
MessageCompletedData,
|
|
34
|
+
MessageCreatedData,
|
|
35
|
+
MessageItems,
|
|
36
|
+
MessageRole,
|
|
37
|
+
MessageUpdatedData,
|
|
38
|
+
NiniModel,
|
|
39
|
+
Part,
|
|
40
|
+
PartDeltaData,
|
|
41
|
+
PartType,
|
|
42
|
+
PartUpdatedData,
|
|
43
|
+
PermissionDecision,
|
|
44
|
+
PermissionReason,
|
|
45
|
+
PermissionRequest,
|
|
46
|
+
PermissionRequestedData,
|
|
47
|
+
PermissionResolvedData,
|
|
48
|
+
PermissionScope,
|
|
49
|
+
PromptInput,
|
|
50
|
+
PromptResult,
|
|
51
|
+
PtyCreateInput,
|
|
52
|
+
PtyCreateResult,
|
|
53
|
+
PtyDataData,
|
|
54
|
+
PtyExitData,
|
|
55
|
+
ResolvePermissionInput,
|
|
56
|
+
ResyncRequiredData,
|
|
57
|
+
ServerHeartbeatData,
|
|
58
|
+
ServerHelloData,
|
|
59
|
+
ServerInfo,
|
|
60
|
+
Session,
|
|
61
|
+
SessionCreatedData,
|
|
62
|
+
SessionDeletedData,
|
|
63
|
+
SessionItems,
|
|
64
|
+
SessionKind,
|
|
65
|
+
SessionPage,
|
|
66
|
+
SessionSnapshot,
|
|
67
|
+
SessionStatus,
|
|
68
|
+
SessionSubagentsData,
|
|
69
|
+
SessionUpdatedData,
|
|
70
|
+
SubagentInfo,
|
|
71
|
+
SubagentSummary,
|
|
72
|
+
Timestamp,
|
|
73
|
+
ToolCallData,
|
|
74
|
+
ToolResultData,
|
|
75
|
+
TurnCheckpointData,
|
|
76
|
+
TurnFinishedData,
|
|
77
|
+
TurnReason,
|
|
78
|
+
TurnStartedData,
|
|
79
|
+
Usage,
|
|
80
|
+
WriteFileInput,
|
|
81
|
+
WriteFileResult,
|
|
82
|
+
utcnow,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
__all__ = [
|
|
86
|
+
"ALL_TOOLS_SCOPE",
|
|
87
|
+
"CORE_MODELS",
|
|
88
|
+
"DEFAULT_PERMISSION_SCOPE",
|
|
89
|
+
"EVENT_DATA_MODELS",
|
|
90
|
+
"KNOWN_EVENT_TYPES",
|
|
91
|
+
"PARAMETERIZED_MODELS",
|
|
92
|
+
"PERMISSION_SCOPES",
|
|
93
|
+
"PROTOCOL_VERSION",
|
|
94
|
+
"Attachment",
|
|
95
|
+
"ClientKind",
|
|
96
|
+
"CreateSessionInput",
|
|
97
|
+
"DecidedBy",
|
|
98
|
+
"ErrorData",
|
|
99
|
+
"Event",
|
|
100
|
+
"EventType",
|
|
101
|
+
"FileChangeKind",
|
|
102
|
+
"FileChangedData",
|
|
103
|
+
"FileContent",
|
|
104
|
+
"FileDiff",
|
|
105
|
+
"FileNode",
|
|
106
|
+
"FileNodeType",
|
|
107
|
+
"FileTree",
|
|
108
|
+
"FileNodeItems",
|
|
109
|
+
"HealthResponse",
|
|
110
|
+
"Items",
|
|
111
|
+
"Message",
|
|
112
|
+
"MessageCompletedData",
|
|
113
|
+
"MessageCreatedData",
|
|
114
|
+
"MessageItems",
|
|
115
|
+
"MessageRole",
|
|
116
|
+
"MessageUpdatedData",
|
|
117
|
+
"NiniModel",
|
|
118
|
+
"PARAMETERIZED_MODELS",
|
|
119
|
+
"Part",
|
|
120
|
+
"PartDeltaData",
|
|
121
|
+
"PartType",
|
|
122
|
+
"PartUpdatedData",
|
|
123
|
+
"PermissionDecision",
|
|
124
|
+
"PermissionReason",
|
|
125
|
+
"PermissionRequest",
|
|
126
|
+
"PermissionRequestedData",
|
|
127
|
+
"PermissionResolvedData",
|
|
128
|
+
"PermissionScope",
|
|
129
|
+
"PromptInput",
|
|
130
|
+
"PromptResult",
|
|
131
|
+
"PtyCreateInput",
|
|
132
|
+
"PtyCreateResult",
|
|
133
|
+
"PtyDataData",
|
|
134
|
+
"PtyExitData",
|
|
135
|
+
"ResolvePermissionInput",
|
|
136
|
+
"ResyncRequiredData",
|
|
137
|
+
"ServerHeartbeatData",
|
|
138
|
+
"ServerHelloData",
|
|
139
|
+
"ServerInfo",
|
|
140
|
+
"Session",
|
|
141
|
+
"SessionItems",
|
|
142
|
+
"SessionKind",
|
|
143
|
+
"SessionSubagentsData",
|
|
144
|
+
"SessionPage",
|
|
145
|
+
"SessionSnapshot",
|
|
146
|
+
"SessionCreatedData",
|
|
147
|
+
"SessionDeletedData",
|
|
148
|
+
"SessionStatus",
|
|
149
|
+
"SessionUpdatedData",
|
|
150
|
+
"SubagentInfo",
|
|
151
|
+
"SubagentSummary",
|
|
152
|
+
"Timestamp",
|
|
153
|
+
"ToolCallData",
|
|
154
|
+
"ToolResultData",
|
|
155
|
+
"TurnCheckpointData",
|
|
156
|
+
"TurnFinishedData",
|
|
157
|
+
"TurnReason",
|
|
158
|
+
"TurnStartedData",
|
|
159
|
+
"Usage",
|
|
160
|
+
"WriteFileInput",
|
|
161
|
+
"WriteFileResult",
|
|
162
|
+
"utcnow",
|
|
163
|
+
]
|
|
164
|
+
__version__ = "0.4.2"
|
|
@@ -0,0 +1,939 @@
|
|
|
1
|
+
"""Nini wire protocol models — the single source of truth (contract v1).
|
|
2
|
+
|
|
3
|
+
Every field here is taken from ``docs/nini/protocol/20261202-nini-contract-v1.md``
|
|
4
|
+
(sections 1, 2, 7 and the REST shapes in section 3). TypeScript types in
|
|
5
|
+
``packages/nini-sdk-ts/src/types.ts`` mirror this file; the generated JSON Schemas
|
|
6
|
+
in ``packages/nini-protocol/schema/`` are produced from these models by
|
|
7
|
+
``scripts/export_schema.py``.
|
|
8
|
+
|
|
9
|
+
Design rules
|
|
10
|
+
------------
|
|
11
|
+
* Parsing is tolerant: an unknown ``Event.type`` never raises, ``data`` is kept
|
|
12
|
+
verbatim and :attr:`Event.known` is ``False`` (contract §7).
|
|
13
|
+
* Forward compatible: models use ``extra="allow"`` (not ``ignore``) so fields added by
|
|
14
|
+
a newer service survive a round-trip instead of being silently dropped (§7).
|
|
15
|
+
The exception is the envelope itself, where the internal ``id`` handle is
|
|
16
|
+
``exclude=True`` so the wire always carries exactly ``v, seq, ts, type, session,
|
|
17
|
+
data``.
|
|
18
|
+
* Timestamps are serialised as UTC ISO-8601 with milliseconds and a ``Z`` suffix,
|
|
19
|
+
matching the envelope example in contract §1.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from datetime import UTC, datetime
|
|
25
|
+
from enum import StrEnum
|
|
26
|
+
from typing import Annotated, Any, Literal
|
|
27
|
+
|
|
28
|
+
from pydantic import (
|
|
29
|
+
AfterValidator,
|
|
30
|
+
BaseModel,
|
|
31
|
+
BeforeValidator,
|
|
32
|
+
ConfigDict,
|
|
33
|
+
Field,
|
|
34
|
+
PlainSerializer,
|
|
35
|
+
field_validator,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
PROTOCOL_VERSION = 1
|
|
39
|
+
"""Contract §7: clients receiving ``v > 1`` must refuse writes and ask for upgrade."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def utcnow() -> datetime:
|
|
43
|
+
"""Timezone-aware UTC now (single clock entry point for the whole stack)."""
|
|
44
|
+
return datetime.now(UTC)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _ensure_utc(value: datetime) -> datetime:
|
|
48
|
+
"""Normalise naive datetimes to UTC and truncate to ms (the wire precision)."""
|
|
49
|
+
if value.tzinfo is None:
|
|
50
|
+
value = value.replace(tzinfo=UTC)
|
|
51
|
+
else:
|
|
52
|
+
value = value.astimezone(UTC)
|
|
53
|
+
return value.replace(microsecond=value.microsecond - value.microsecond % 1000)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _dump_timestamp(value: datetime) -> str:
|
|
57
|
+
"""Serialise as ``2026-12-02T04:33:00.123Z`` (contract §1 envelope example)."""
|
|
58
|
+
return _ensure_utc(value).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _coerce_timestamp(value: Any) -> Any:
|
|
62
|
+
"""Treat a missing/None timestamp as "now" instead of failing the whole object.
|
|
63
|
+
|
|
64
|
+
Producers that omit an informational timestamp should not lose a whole event
|
|
65
|
+
(nini-core would otherwise fall back to ``model_construct`` and drop validation).
|
|
66
|
+
"""
|
|
67
|
+
if value is None:
|
|
68
|
+
return utcnow()
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
Timestamp = Annotated[
|
|
73
|
+
datetime,
|
|
74
|
+
BeforeValidator(_coerce_timestamp),
|
|
75
|
+
AfterValidator(_ensure_utc),
|
|
76
|
+
PlainSerializer(_dump_timestamp, return_type=str, when_used="json"),
|
|
77
|
+
]
|
|
78
|
+
"""UTC timestamp; JSON form is ISO-8601 with ``Z`` suffix and ms precision."""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class NiniModel(BaseModel):
|
|
82
|
+
"""Base model for every wire object.
|
|
83
|
+
|
|
84
|
+
``extra="allow"`` keeps forward compatibility (contract §7: adding fields must
|
|
85
|
+
not break older clients, and newer clients must not silently drop them).
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
model_config = ConfigDict(
|
|
89
|
+
extra="allow",
|
|
90
|
+
validate_assignment=False,
|
|
91
|
+
populate_by_name=True,
|
|
92
|
+
# run validators on default_factory values too, so `created_at` defaults are
|
|
93
|
+
# ms-truncated exactly like parsed values (keeps JSON round-trips lossless)
|
|
94
|
+
validate_default=True,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------------------------------------------------------------------------
|
|
99
|
+
# Enumerations (contract §2 / §3)
|
|
100
|
+
# ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class EventType(StrEnum):
|
|
104
|
+
"""The contract §2 event types plus the §29 turn lifecycle pair."""
|
|
105
|
+
|
|
106
|
+
SERVER_HELLO = "server.hello"
|
|
107
|
+
SERVER_HEARTBEAT = "server.heartbeat"
|
|
108
|
+
SESSION_CREATED = "session.created"
|
|
109
|
+
SESSION_UPDATED = "session.updated"
|
|
110
|
+
SESSION_DELETED = "session.deleted"
|
|
111
|
+
SESSION_SUBAGENTS = "session.subagents"
|
|
112
|
+
MESSAGE_CREATED = "message.created"
|
|
113
|
+
MESSAGE_UPDATED = "message.updated"
|
|
114
|
+
MESSAGE_COMPLETED = "message.completed"
|
|
115
|
+
PART_UPDATED = "part.updated"
|
|
116
|
+
PART_DELTA = "part.delta"
|
|
117
|
+
TOOL_CALL = "tool.call"
|
|
118
|
+
TOOL_RESULT = "tool.result"
|
|
119
|
+
PERMISSION_REQUESTED = "permission.requested"
|
|
120
|
+
PERMISSION_RESOLVED = "permission.resolved"
|
|
121
|
+
PTY_DATA = "pty.data"
|
|
122
|
+
PTY_EXIT = "pty.exit"
|
|
123
|
+
FILE_CHANGED = "file.changed"
|
|
124
|
+
TURN_STARTED = "turn.started"
|
|
125
|
+
TURN_CHECKPOINT = "turn.checkpoint"
|
|
126
|
+
TURN_FINISHED = "turn.finished"
|
|
127
|
+
ERROR = "error"
|
|
128
|
+
RESYNC_REQUIRED = "resync.required"
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
KNOWN_EVENT_TYPES: frozenset[str] = frozenset(t.value for t in EventType)
|
|
132
|
+
"""Raw string set, used for tolerant ``Event.known`` checks."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class SessionStatus(StrEnum):
|
|
136
|
+
IDLE = "idle"
|
|
137
|
+
RUNNING = "running"
|
|
138
|
+
ERROR = "error"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class SessionKind(StrEnum):
|
|
142
|
+
"""Contract §33: a root session or a subagent session.
|
|
143
|
+
|
|
144
|
+
``kind`` is always derived from ``parent_id`` — a session with a parent is a
|
|
145
|
+
subagent, one without is a root. The wire field is informational; clients
|
|
146
|
+
must treat a missing ``kind`` as ``root`` (pre-§33 payloads).
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
ROOT = "root"
|
|
150
|
+
SUBAGENT = "subagent"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class MessageRole(StrEnum):
|
|
154
|
+
USER = "user"
|
|
155
|
+
ASSISTANT = "assistant"
|
|
156
|
+
SYSTEM = "system"
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class PartType(StrEnum):
|
|
160
|
+
TEXT = "text"
|
|
161
|
+
TOOL = "tool"
|
|
162
|
+
REASONING = "reasoning"
|
|
163
|
+
FILE = "file"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class FileChangeKind(StrEnum):
|
|
167
|
+
CREATED = "created"
|
|
168
|
+
MODIFIED = "modified"
|
|
169
|
+
DELETED = "deleted"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class FileNodeType(StrEnum):
|
|
173
|
+
FILE = "file"
|
|
174
|
+
DIR = "dir"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
PermissionDecision = Literal["allow", "deny"]
|
|
178
|
+
PermissionScope = Literal["once", "turn", "session"]
|
|
179
|
+
"""How long an approval lasts (contract §23)."""
|
|
180
|
+
PERMISSION_SCOPES: tuple[PermissionScope, ...] = ("once", "turn", "session")
|
|
181
|
+
"""The three legal scopes, in the order a UI should render them."""
|
|
182
|
+
DEFAULT_PERMISSION_SCOPE: PermissionScope = "once"
|
|
183
|
+
ALL_TOOLS_SCOPE = "*"
|
|
184
|
+
"""``tool="*"`` in a resolution: the scope covers *every* tool (§23)."""
|
|
185
|
+
ClientKind = Literal["cli", "web", "mobile"]
|
|
186
|
+
"""Who is *connected* (client hello / attribution of a user action)."""
|
|
187
|
+
DecidedBy = Literal["cli", "web", "mobile", "system", "policy"]
|
|
188
|
+
"""``permission.resolved.by`` (contract §21 + §23): the connected clients plus two
|
|
189
|
+
server-side deciders.
|
|
190
|
+
|
|
191
|
+
* ``system`` — timeouts / lost clients (§21);
|
|
192
|
+
* ``policy`` — an approval served from the scope table (§23), i.e. a decision the
|
|
193
|
+
user already made once in this turn/session; never attributed to a client.
|
|
194
|
+
"""
|
|
195
|
+
PermissionReason = Literal["timeout", "client_lost", "policy"]
|
|
196
|
+
"""Optional ``permission.resolved.reason`` (contract §21)."""
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# ---------------------------------------------------------------------------
|
|
200
|
+
# Core objects (contract §2 "核心对象")
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class SubagentInfo(NiniModel):
|
|
205
|
+
"""One row of ``subagent_summary.children`` (contract §33).
|
|
206
|
+
|
|
207
|
+
``status`` reuses :class:`SessionStatus`; ``started_at`` is the child's
|
|
208
|
+
creation instant and ``finished_at`` is its last update once it is no longer
|
|
209
|
+
``running`` (``null`` while it still runs). ``tool_calls`` / ``tokens`` are
|
|
210
|
+
aggregates over the child's own rows and events — the parent timeline never
|
|
211
|
+
loads the child transcript to draw the collapsed row. Both timestamps and
|
|
212
|
+
``cost`` are always serialised (``null`` when unknown) so this model and the
|
|
213
|
+
REST payload carry exactly the same keys.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
id: str
|
|
217
|
+
label: str | None = None
|
|
218
|
+
status: SessionStatus = SessionStatus.IDLE
|
|
219
|
+
started_at: Timestamp | None = None
|
|
220
|
+
finished_at: Timestamp | None = None
|
|
221
|
+
tool_calls: int = 0
|
|
222
|
+
tokens: int = 0
|
|
223
|
+
cost: float | None = None
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class SubagentSummary(NiniModel):
|
|
227
|
+
"""``subagent_summary`` on a parent session (contract §33).
|
|
228
|
+
|
|
229
|
+
``children`` lists **direct** children (what the expanded card shows);
|
|
230
|
+
``total`` is their count and ``descendants`` counts every level below this
|
|
231
|
+
parent (what the collapsed `↳ N 个子代理` row shows).
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
total: int = 0
|
|
235
|
+
running: int = 0
|
|
236
|
+
descendants: int = 0
|
|
237
|
+
children: list[SubagentInfo] = Field(default_factory=list)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class Session(NiniModel):
|
|
241
|
+
"""``Session { id, title, cwd, model, status, pinned_at?, created_at, updated_at }``.
|
|
242
|
+
|
|
243
|
+
``pinned_at`` (contract §32) is the pin instant; ``None``/absent means the
|
|
244
|
+
session is not pinned. It is *not* a status flag and does not affect
|
|
245
|
+
``updated_at`` — pinning never reorders history.
|
|
246
|
+
|
|
247
|
+
Contract §33 adds the subagent linkage. All three fields are optional and
|
|
248
|
+
only serialised when they carry information, so a root session keeps the
|
|
249
|
+
exact pre-§33 wire shape (a missing ``kind`` means ``root``)::
|
|
250
|
+
|
|
251
|
+
parent_id # parent session id, or absent for a root
|
|
252
|
+
kind # "root" | "subagent"; absent ⇒ root
|
|
253
|
+
label # short subagent name (e.g. "explorer"), or absent
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
id: str
|
|
257
|
+
title: str = "New session"
|
|
258
|
+
cwd: str | None = None
|
|
259
|
+
model: str | None = None
|
|
260
|
+
status: SessionStatus = SessionStatus.IDLE
|
|
261
|
+
pinned_at: Timestamp | None = None
|
|
262
|
+
created_at: Timestamp = Field(default_factory=utcnow)
|
|
263
|
+
updated_at: Timestamp = Field(default_factory=utcnow)
|
|
264
|
+
parent_id: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
265
|
+
kind: SessionKind = Field(
|
|
266
|
+
default=SessionKind.ROOT,
|
|
267
|
+
exclude_if=lambda value: value in (SessionKind.ROOT, "root"),
|
|
268
|
+
)
|
|
269
|
+
label: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
270
|
+
subagent_summary: SubagentSummary | None = Field(
|
|
271
|
+
default=None, exclude_if=lambda value: value is None
|
|
272
|
+
)
|
|
273
|
+
"""Aggregate of the direct children (contract §33.1), parents only.
|
|
274
|
+
|
|
275
|
+
Additive and optional: a session with no children never carries the key, so
|
|
276
|
+
a leaf keeps the pre-§33 wire shape byte-for-byte. Read-only for clients.
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Part(NiniModel):
|
|
281
|
+
"""``Part { id, message_id, type, text?, tool?, state? }``.
|
|
282
|
+
|
|
283
|
+
Contract leaves ``tool`` / ``state`` untyped. ``tool`` accepts either the tool
|
|
284
|
+
name (``"bash"``) or a full tool object — nini-core sends both spellings — and
|
|
285
|
+
``state`` is an open mapping (status/input/output/error) or a bare status string.
|
|
286
|
+
"""
|
|
287
|
+
|
|
288
|
+
id: str
|
|
289
|
+
message_id: str
|
|
290
|
+
type: PartType
|
|
291
|
+
text: str | None = None
|
|
292
|
+
tool: str | dict[str, Any] | None = None
|
|
293
|
+
state: dict[str, Any] | None = None
|
|
294
|
+
|
|
295
|
+
@field_validator("state", mode="before")
|
|
296
|
+
@classmethod
|
|
297
|
+
def _coerce_state(cls, value: Any) -> Any:
|
|
298
|
+
"""Accept a bare string state (e.g. ``"pending"``) from simple producers."""
|
|
299
|
+
if isinstance(value, str):
|
|
300
|
+
return {"status": value}
|
|
301
|
+
return value
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
class Message(NiniModel):
|
|
305
|
+
"""``Message { id, session, role, created_at, parts? }``.
|
|
306
|
+
|
|
307
|
+
Contract v1.1 §11.1:
|
|
308
|
+
|
|
309
|
+
* WS events carry a bare ``Message`` and stream content via ``part.updated``;
|
|
310
|
+
* REST responses carry ``parts`` in part order — the only reliable cold-start
|
|
311
|
+
source for web/mobile.
|
|
312
|
+
|
|
313
|
+
``parts`` is therefore omitted from the wire when unset (``exclude_if``), exactly
|
|
314
|
+
like :attr:`Event.id`, so an WS event never grows an empty ``"parts": null``.
|
|
315
|
+
"""
|
|
316
|
+
|
|
317
|
+
id: str
|
|
318
|
+
session: str
|
|
319
|
+
role: MessageRole
|
|
320
|
+
created_at: Timestamp = Field(default_factory=utcnow)
|
|
321
|
+
parts: list[Part] | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Attachment(NiniModel):
|
|
325
|
+
"""User attachment on ``POST /api/sessions/{id}/prompt``.
|
|
326
|
+
|
|
327
|
+
NOTE: the contract mentions ``attachments?[]`` but never defines the shape;
|
|
328
|
+
this is the minimal object the service/CLI/web/mobile agree on (reported as a
|
|
329
|
+
contract gap). ``path`` refers to a path inside the service workspace,
|
|
330
|
+
``data`` is optional inline base64 for remote clients.
|
|
331
|
+
"""
|
|
332
|
+
|
|
333
|
+
name: str
|
|
334
|
+
id: str | None = None
|
|
335
|
+
mime: str | None = None
|
|
336
|
+
size: int | None = None
|
|
337
|
+
path: str | None = None
|
|
338
|
+
data: str | None = None
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class Usage(NiniModel):
|
|
342
|
+
"""Token usage reported by ``message.completed``."""
|
|
343
|
+
|
|
344
|
+
input_tokens: int = 0
|
|
345
|
+
output_tokens: int = 0
|
|
346
|
+
reasoning_tokens: int = 0
|
|
347
|
+
cached_tokens: int = 0
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class SessionSnapshot(NiniModel):
|
|
351
|
+
"""``GET /api/sessions/{id}/snapshot`` (contract v1.1 §11.2).
|
|
352
|
+
|
|
353
|
+
Cold start calls this once, renders ``messages`` (each carrying ``parts``), then
|
|
354
|
+
subscribes with ``?since=last_seq``. ``resync.required`` is handled the same way:
|
|
355
|
+
rebuild from snapshot, reconnect from ``last_seq`` (§11.3).
|
|
356
|
+
"""
|
|
357
|
+
|
|
358
|
+
session: Session
|
|
359
|
+
messages: list[Message] = Field(default_factory=list)
|
|
360
|
+
last_seq: int = Field(default=0, ge=0)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
class Items[T](NiniModel):
|
|
364
|
+
"""Generic list envelope: ``{"items": [...]}`` (contract v1.1 §11.4).
|
|
365
|
+
|
|
366
|
+
Every list endpoint answers with this shape; v1 clients that expect a bare array
|
|
367
|
+
are still tolerated by the SDKs.
|
|
368
|
+
"""
|
|
369
|
+
|
|
370
|
+
items: list[T] = Field(default_factory=list)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class SessionPage(NiniModel):
|
|
374
|
+
"""One page of ``GET /api/sessions`` (contract §27 + §32).
|
|
375
|
+
|
|
376
|
+
``pinned`` is the §32 pin block: up to 50 pinned sessions ordered by
|
|
377
|
+
``pinned_at DESC, updated_at DESC``. It is **not** part of the pagination —
|
|
378
|
+
``items`` already excludes those rows, and ``has_more`` / ``next_before``
|
|
379
|
+
only describe ``items``. Pinned sessions beyond the 50-item window stay in
|
|
380
|
+
``items`` with their ``pinned_at`` intact.
|
|
381
|
+
|
|
382
|
+
``next_before`` is an **opaque** cursor: pass it back as the ``before`` query
|
|
383
|
+
parameter to load the next page, or stop when it is ``None`` (last page).
|
|
384
|
+
Clients must not rebuild it from ``Session.updated_at`` — the wire timestamp
|
|
385
|
+
is millisecond-truncated while the cursor carries the stored timestamp plus
|
|
386
|
+
the id, so a rebuilt cursor could skip a session written in the same
|
|
387
|
+
millisecond.
|
|
388
|
+
"""
|
|
389
|
+
|
|
390
|
+
items: list[Session] = Field(default_factory=list)
|
|
391
|
+
pinned: list[Session] = Field(default_factory=list)
|
|
392
|
+
has_more: bool = False
|
|
393
|
+
next_before: str | None = None
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
class PermissionRequest(NiniModel):
|
|
397
|
+
"""``PermissionRequest { id, session, message_id, tool, title, payload, ... }``.
|
|
398
|
+
|
|
399
|
+
``scope_options`` (contract §23) is the list of scopes the requester supports,
|
|
400
|
+
so a UI renders only choices the service understands. It defaults to the three
|
|
401
|
+
contract scopes and never contains anything else.
|
|
402
|
+
"""
|
|
403
|
+
|
|
404
|
+
id: str
|
|
405
|
+
session: str
|
|
406
|
+
message_id: str | None
|
|
407
|
+
tool: str
|
|
408
|
+
title: str = ""
|
|
409
|
+
payload: dict[str, Any] = Field(default_factory=dict)
|
|
410
|
+
created_at: Timestamp = Field(default_factory=utcnow)
|
|
411
|
+
expires_at: Timestamp | None = None
|
|
412
|
+
scope_options: list[PermissionScope] = Field(default_factory=lambda: list(PERMISSION_SCOPES))
|
|
413
|
+
|
|
414
|
+
@field_validator("scope_options")
|
|
415
|
+
@classmethod
|
|
416
|
+
def _check_scope_options(cls, value: list[PermissionScope]) -> list[PermissionScope]:
|
|
417
|
+
"""Reject unknown/duplicate scopes; keep the caller's order (UI order)."""
|
|
418
|
+
seen: list[PermissionScope] = []
|
|
419
|
+
for item in value:
|
|
420
|
+
if item not in PERMISSION_SCOPES:
|
|
421
|
+
raise ValueError(f"unknown permission scope: {item!r}")
|
|
422
|
+
if item not in seen:
|
|
423
|
+
seen.append(item)
|
|
424
|
+
return seen
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# ---------------------------------------------------------------------------
|
|
428
|
+
# REST payload objects (contract §3) — shared by service, CLI, SDK
|
|
429
|
+
# ---------------------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class HealthResponse(NiniModel):
|
|
433
|
+
"""``GET /health`` → ``{ok, name, version}`` (no auth)."""
|
|
434
|
+
|
|
435
|
+
ok: bool = True
|
|
436
|
+
name: str = "nini-service"
|
|
437
|
+
version: str = "0.1.0"
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
class ServerInfo(NiniModel):
|
|
441
|
+
"""``GET /api/info`` → ``{server_id, version, protocol, workspace, capabilities[]}``."""
|
|
442
|
+
|
|
443
|
+
server_id: str
|
|
444
|
+
version: str
|
|
445
|
+
protocol: int = PROTOCOL_VERSION
|
|
446
|
+
workspace: str
|
|
447
|
+
capabilities: list[str] = Field(default_factory=list)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
class CreateSessionInput(NiniModel):
|
|
451
|
+
"""``POST /api/sessions`` body — every field optional."""
|
|
452
|
+
|
|
453
|
+
title: str | None = None
|
|
454
|
+
cwd: str | None = None
|
|
455
|
+
model: str | None = None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
class PromptInput(NiniModel):
|
|
459
|
+
"""``POST /api/sessions/{id}/prompt`` body."""
|
|
460
|
+
|
|
461
|
+
text: str
|
|
462
|
+
attachments: list[Attachment] | None = None
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
class PromptResult(NiniModel):
|
|
466
|
+
"""``POST /api/sessions/{id}/prompt`` → ``{message_id}``."""
|
|
467
|
+
|
|
468
|
+
message_id: str
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
class ResolvePermissionInput(NiniModel):
|
|
472
|
+
"""``POST /api/permissions/{id}`` body (idempotent; contract §23).
|
|
473
|
+
|
|
474
|
+
``scope`` defaults to ``once``; ``tool="*"`` with ``scope="turn"`` means
|
|
475
|
+
"every tool for the rest of this turn".
|
|
476
|
+
"""
|
|
477
|
+
|
|
478
|
+
decision: PermissionDecision
|
|
479
|
+
scope: PermissionScope = DEFAULT_PERMISSION_SCOPE
|
|
480
|
+
tool: str | None = None
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class FileNode(NiniModel):
|
|
484
|
+
"""Entry of ``GET /api/files/tree``."""
|
|
485
|
+
|
|
486
|
+
name: str
|
|
487
|
+
path: str
|
|
488
|
+
type: FileNodeType
|
|
489
|
+
size: int | None = None
|
|
490
|
+
children: list[FileNode] | None = None
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
class FileTree(NiniModel):
|
|
494
|
+
"""``GET /api/files/tree`` result (root node + depth used)."""
|
|
495
|
+
|
|
496
|
+
path: str = "."
|
|
497
|
+
depth: int = 2
|
|
498
|
+
children: list[FileNode] = Field(default_factory=list)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class FileContent(NiniModel):
|
|
502
|
+
"""``GET /api/files/content`` → ``{path, content, hash}``."""
|
|
503
|
+
|
|
504
|
+
path: str
|
|
505
|
+
content: str
|
|
506
|
+
hash: str
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
class WriteFileInput(NiniModel):
|
|
510
|
+
"""``PUT /api/files/content`` body."""
|
|
511
|
+
|
|
512
|
+
path: str
|
|
513
|
+
content: str
|
|
514
|
+
expected_hash: str | None = None
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
class WriteFileResult(NiniModel):
|
|
518
|
+
"""``PUT /api/files/content`` → ``{hash}``; a stale hash yields HTTP 409."""
|
|
519
|
+
|
|
520
|
+
hash: str
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
class FileDiff(NiniModel):
|
|
524
|
+
"""``GET /api/files/diff`` result.
|
|
525
|
+
|
|
526
|
+
NOTE: the contract does not pin this shape; ``diff`` is the unified diff text
|
|
527
|
+
(empty when the file is clean or git is unavailable) — reported as a gap.
|
|
528
|
+
"""
|
|
529
|
+
|
|
530
|
+
path: str
|
|
531
|
+
diff: str = ""
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
class PtyCreateInput(NiniModel):
|
|
535
|
+
"""``POST /api/pty`` body."""
|
|
536
|
+
|
|
537
|
+
cwd: str | None = None
|
|
538
|
+
cols: int = 80
|
|
539
|
+
rows: int = 24
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
class PtyCreateResult(NiniModel):
|
|
543
|
+
"""``POST /api/pty`` → ``{pty_id}``."""
|
|
544
|
+
|
|
545
|
+
pty_id: str
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
# ---------------------------------------------------------------------------
|
|
549
|
+
# Event payloads (contract §2 table) — one model per event type
|
|
550
|
+
# ---------------------------------------------------------------------------
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
class ServerHelloData(NiniModel):
|
|
554
|
+
server_id: str
|
|
555
|
+
name: str
|
|
556
|
+
version: str
|
|
557
|
+
protocol: int = PROTOCOL_VERSION
|
|
558
|
+
workspace: str
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
class ServerHeartbeatData(NiniModel):
|
|
562
|
+
uptime_s: float
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
class SessionCreatedData(NiniModel):
|
|
566
|
+
session: Session
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
class SessionUpdatedData(NiniModel):
|
|
570
|
+
session: Session
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
class SessionDeletedData(NiniModel):
|
|
574
|
+
session_id: str
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
class SessionSubagentsData(NiniModel):
|
|
578
|
+
"""``session.subagents`` — pushed on the **parent** stream (contract §33).
|
|
579
|
+
|
|
580
|
+
Clients update the collapsed row (`↳ N 个子代理`) from this event without
|
|
581
|
+
loading any child session. Child messages/tools keep the child's
|
|
582
|
+
``session_id`` and never enter the parent stream.
|
|
583
|
+
"""
|
|
584
|
+
|
|
585
|
+
session_id: str
|
|
586
|
+
total: int = 0
|
|
587
|
+
running: int = 0
|
|
588
|
+
descendants: int = 0
|
|
589
|
+
children: list[SubagentInfo] = Field(default_factory=list)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
class MessageCreatedData(NiniModel):
|
|
593
|
+
message: Message
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
class MessageUpdatedData(NiniModel):
|
|
597
|
+
message: Message
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
class MessageCompletedData(NiniModel):
|
|
601
|
+
"""``message.completed`` — ``usage`` plus the §24 error surface.
|
|
602
|
+
|
|
603
|
+
``error="max_iterations"`` with ``iterations=N`` means the tool-round budget
|
|
604
|
+
ran out; the client should offer to continue instead of pretending the turn
|
|
605
|
+
finished cleanly.
|
|
606
|
+
"""
|
|
607
|
+
|
|
608
|
+
message_id: str
|
|
609
|
+
usage: Usage = Field(default_factory=Usage)
|
|
610
|
+
error: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
611
|
+
iterations: int | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
class PartUpdatedData(NiniModel):
|
|
615
|
+
message_id: str
|
|
616
|
+
part: Part
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
class TurnReason(StrEnum):
|
|
620
|
+
"""Contract §29: why a turn ended. Every turn ends with exactly one of these.
|
|
621
|
+
|
|
622
|
+
``MAX_ITERATIONS`` is legacy: since §34 the tool-round budget is a *checkpoint*
|
|
623
|
+
interval, so a turn that runs out of automatic continuations ends with
|
|
624
|
+
``CHECKPOINT_EXHAUSTED``. The old value stays because replayed event logs and
|
|
625
|
+
pre-§34 daemons still carry it.
|
|
626
|
+
"""
|
|
627
|
+
|
|
628
|
+
COMPLETED = "completed"
|
|
629
|
+
ABORTED = "aborted"
|
|
630
|
+
ERROR = "error"
|
|
631
|
+
MAX_ITERATIONS = "max_iterations"
|
|
632
|
+
EMPTY = "empty"
|
|
633
|
+
CHECKPOINT_EXHAUSTED = "checkpoint_exhausted"
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
class TurnStartedData(NiniModel):
|
|
637
|
+
"""``turn.started`` — a user message landed and the agent is about to run.
|
|
638
|
+
|
|
639
|
+
Published after ``message.created`` (the user message) and before the first
|
|
640
|
+
model call; ``message_id`` is that user message, i.e. the turn's identity.
|
|
641
|
+
"""
|
|
642
|
+
|
|
643
|
+
message_id: str
|
|
644
|
+
started_at: Timestamp = Field(default_factory=utcnow)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
class TurnFinishedData(NiniModel):
|
|
648
|
+
"""``turn.finished`` — the last event of a turn (contract §29).
|
|
649
|
+
|
|
650
|
+
``duration_ms`` covers the whole turn including tool execution; ``steps`` is
|
|
651
|
+
the number of model rounds (the "N 步" a TUI shows). ``error`` is a one-line
|
|
652
|
+
summary and only present for ``reason="error"``. ``iterations`` echoes the
|
|
653
|
+
``max_iterations`` limit when that budget was the reason. ``checkpoints`` is
|
|
654
|
+
the number of automatic continuations this turn performed (contract §34),
|
|
655
|
+
absent (not ``0``) for turns that never reached a checkpoint.
|
|
656
|
+
"""
|
|
657
|
+
|
|
658
|
+
message_id: str
|
|
659
|
+
reason: TurnReason
|
|
660
|
+
duration_ms: int = 0
|
|
661
|
+
steps: int = 0
|
|
662
|
+
error: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
663
|
+
iterations: int | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
664
|
+
checkpoints: int | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
class TurnCheckpointData(NiniModel):
|
|
668
|
+
"""``turn.checkpoint`` — the tool-round budget was reached (contract §34).
|
|
669
|
+
|
|
670
|
+
The turn does **not** end here: the engine keeps the same ``turn_id``, the
|
|
671
|
+
same transcript and the same user message, and simply continues. ``step`` is
|
|
672
|
+
the model round at which the checkpoint fired, ``attempt`` the 1-based
|
|
673
|
+
automatic continuation this event starts, and ``max_auto_continues`` the
|
|
674
|
+
configured ceiling. ``tokens_used`` / ``elapsed_ms`` are whole-turn totals
|
|
675
|
+
(both optional on the wire).
|
|
676
|
+
"""
|
|
677
|
+
|
|
678
|
+
message_id: str
|
|
679
|
+
step: int = 0
|
|
680
|
+
attempt: int = 1
|
|
681
|
+
max_auto_continues: int = 0
|
|
682
|
+
auto: bool = True
|
|
683
|
+
tokens_used: int | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
684
|
+
elapsed_ms: int | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
class PartDeltaData(NiniModel):
|
|
688
|
+
message_id: str
|
|
689
|
+
part_id: str
|
|
690
|
+
delta: str
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
class ToolCallData(NiniModel):
|
|
694
|
+
message_id: str
|
|
695
|
+
part_id: str
|
|
696
|
+
tool: str
|
|
697
|
+
input: dict[str, Any] = Field(default_factory=dict)
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
class ToolResultData(NiniModel):
|
|
701
|
+
message_id: str
|
|
702
|
+
part_id: str
|
|
703
|
+
status: str
|
|
704
|
+
output: Any = None
|
|
705
|
+
duration_ms: int | None = None
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
class PermissionRequestedData(NiniModel):
|
|
709
|
+
request: PermissionRequest
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class PermissionResolvedData(NiniModel):
|
|
713
|
+
"""``permission.resolved`` — contract §21 + §23.
|
|
714
|
+
|
|
715
|
+
A timeout is ``{"decision": "deny", "by": "system", "reason": "timeout"}``.
|
|
716
|
+
A policy approval is ``{"decision": "allow", "by": "policy", "scope": "turn"}``
|
|
717
|
+
(no ``reason``, no client attribution).
|
|
718
|
+
"""
|
|
719
|
+
|
|
720
|
+
request_id: str
|
|
721
|
+
decision: PermissionDecision
|
|
722
|
+
by: DecidedBy
|
|
723
|
+
# Omitted (not `null`) when the decision came from a client — a plain
|
|
724
|
+
# `{decision, by}` stays byte-identical to the v1.0 wire format.
|
|
725
|
+
reason: PermissionReason | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
726
|
+
# §23: echo of the granted scope / tool so every client can render
|
|
727
|
+
# "allowed for this session". Absent means `once` (the pre-§23 wire shape).
|
|
728
|
+
scope: PermissionScope | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
729
|
+
tool: str | None = Field(default=None, exclude_if=lambda value: value is None)
|
|
730
|
+
|
|
731
|
+
@property
|
|
732
|
+
def effective_scope(self) -> PermissionScope:
|
|
733
|
+
"""The granted scope; an absent field is ``once`` (§23)."""
|
|
734
|
+
return self.scope or DEFAULT_PERMISSION_SCOPE
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
class PtyDataData(NiniModel):
|
|
738
|
+
"""``pty.data`` — ``data`` is base64 of the raw terminal bytes."""
|
|
739
|
+
|
|
740
|
+
pty_id: str
|
|
741
|
+
data: str
|
|
742
|
+
|
|
743
|
+
|
|
744
|
+
class PtyExitData(NiniModel):
|
|
745
|
+
pty_id: str
|
|
746
|
+
code: int
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
class FileChangedData(NiniModel):
|
|
750
|
+
path: str
|
|
751
|
+
kind: FileChangeKind
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
class ErrorData(NiniModel):
|
|
755
|
+
code: str
|
|
756
|
+
message: str
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
class ResyncRequiredData(NiniModel):
|
|
760
|
+
since: int
|
|
761
|
+
latest: int
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
EVENT_DATA_MODELS: dict[EventType, type[NiniModel]] = {
|
|
765
|
+
EventType.SERVER_HELLO: ServerHelloData,
|
|
766
|
+
EventType.SERVER_HEARTBEAT: ServerHeartbeatData,
|
|
767
|
+
EventType.SESSION_CREATED: SessionCreatedData,
|
|
768
|
+
EventType.SESSION_UPDATED: SessionUpdatedData,
|
|
769
|
+
EventType.SESSION_DELETED: SessionDeletedData,
|
|
770
|
+
EventType.SESSION_SUBAGENTS: SessionSubagentsData,
|
|
771
|
+
EventType.MESSAGE_CREATED: MessageCreatedData,
|
|
772
|
+
EventType.MESSAGE_UPDATED: MessageUpdatedData,
|
|
773
|
+
EventType.MESSAGE_COMPLETED: MessageCompletedData,
|
|
774
|
+
EventType.PART_UPDATED: PartUpdatedData,
|
|
775
|
+
EventType.PART_DELTA: PartDeltaData,
|
|
776
|
+
EventType.TOOL_CALL: ToolCallData,
|
|
777
|
+
EventType.TOOL_RESULT: ToolResultData,
|
|
778
|
+
EventType.PERMISSION_REQUESTED: PermissionRequestedData,
|
|
779
|
+
EventType.PERMISSION_RESOLVED: PermissionResolvedData,
|
|
780
|
+
EventType.PTY_DATA: PtyDataData,
|
|
781
|
+
EventType.PTY_EXIT: PtyExitData,
|
|
782
|
+
EventType.FILE_CHANGED: FileChangedData,
|
|
783
|
+
EventType.TURN_STARTED: TurnStartedData,
|
|
784
|
+
EventType.TURN_CHECKPOINT: TurnCheckpointData,
|
|
785
|
+
EventType.TURN_FINISHED: TurnFinishedData,
|
|
786
|
+
EventType.ERROR: ErrorData,
|
|
787
|
+
EventType.RESYNC_REQUIRED: ResyncRequiredData,
|
|
788
|
+
}
|
|
789
|
+
"""Typed payload model per known event type (used by SDKs and tests)."""
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
# ---------------------------------------------------------------------------
|
|
793
|
+
# Event envelope (contract §1)
|
|
794
|
+
# ---------------------------------------------------------------------------
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
class Event(NiniModel):
|
|
798
|
+
"""``{v, seq, ts, type, session, data}``.
|
|
799
|
+
|
|
800
|
+
``seq`` starts at 1 in the service (contract §1) and resumes from the sqlite
|
|
801
|
+
max on restart; ``0`` means "not assigned yet" and is only ever produced by
|
|
802
|
+
:meth:`make` before the event bus stamps it.
|
|
803
|
+
"""
|
|
804
|
+
|
|
805
|
+
v: int = PROTOCOL_VERSION
|
|
806
|
+
seq: int = Field(default=0, ge=0)
|
|
807
|
+
ts: Timestamp = Field(default_factory=utcnow)
|
|
808
|
+
type: str
|
|
809
|
+
session: str | None = None
|
|
810
|
+
data: dict[str, Any] = Field(default_factory=dict)
|
|
811
|
+
# Internal handle for the store/bus (nini-core stamps it); never sent on the wire,
|
|
812
|
+
# so the envelope keeps exactly the six keys from contract §1.
|
|
813
|
+
id: str | None = Field(default=None, exclude=True)
|
|
814
|
+
|
|
815
|
+
@property
|
|
816
|
+
def known(self) -> bool:
|
|
817
|
+
"""``False`` for event types this protocol version does not know (§7)."""
|
|
818
|
+
return self.type in KNOWN_EVENT_TYPES
|
|
819
|
+
|
|
820
|
+
@property
|
|
821
|
+
def event_type(self) -> EventType | None:
|
|
822
|
+
"""Enum form of :attr:`type`, or ``None`` when unknown."""
|
|
823
|
+
if not self.known:
|
|
824
|
+
return None
|
|
825
|
+
return EventType(self.type)
|
|
826
|
+
|
|
827
|
+
@property
|
|
828
|
+
def is_server_event(self) -> bool:
|
|
829
|
+
"""Session-less events (``server.*``, ``resync.required``, …)."""
|
|
830
|
+
return self.session is None
|
|
831
|
+
|
|
832
|
+
def payload(self) -> NiniModel | None:
|
|
833
|
+
"""Parse :attr:`data` into its typed model, or ``None`` if unknown/invalid.
|
|
834
|
+
|
|
835
|
+
Never raises: a broken payload must not kill the client event loop.
|
|
836
|
+
"""
|
|
837
|
+
model = EVENT_DATA_MODELS.get(self.event_type) if self.event_type else None
|
|
838
|
+
if model is None:
|
|
839
|
+
return None
|
|
840
|
+
try:
|
|
841
|
+
return model.model_validate(self.data)
|
|
842
|
+
except Exception: # noqa: BLE001 — tolerant by design (contract §7)
|
|
843
|
+
return None
|
|
844
|
+
|
|
845
|
+
@classmethod
|
|
846
|
+
def make(
|
|
847
|
+
cls,
|
|
848
|
+
type: str | EventType,
|
|
849
|
+
data: dict[str, Any] | None = None,
|
|
850
|
+
session: str | None = None,
|
|
851
|
+
*,
|
|
852
|
+
seq: int = 0,
|
|
853
|
+
ts: datetime | None = None,
|
|
854
|
+
) -> Event:
|
|
855
|
+
"""Build an event with ``v`` / ``ts`` filled in automatically."""
|
|
856
|
+
return cls(
|
|
857
|
+
v=PROTOCOL_VERSION,
|
|
858
|
+
seq=seq,
|
|
859
|
+
ts=ts or utcnow(),
|
|
860
|
+
type=str(type.value if isinstance(type, EventType) else type),
|
|
861
|
+
session=session,
|
|
862
|
+
data=dict(data or {}),
|
|
863
|
+
)
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
# ---------------------------------------------------------------------------
|
|
867
|
+
# Schema export registry
|
|
868
|
+
# ---------------------------------------------------------------------------
|
|
869
|
+
|
|
870
|
+
CORE_MODELS: tuple[type[NiniModel], ...] = (
|
|
871
|
+
# core objects
|
|
872
|
+
Session,
|
|
873
|
+
SubagentInfo,
|
|
874
|
+
SubagentSummary,
|
|
875
|
+
Part,
|
|
876
|
+
Message,
|
|
877
|
+
Attachment,
|
|
878
|
+
Usage,
|
|
879
|
+
PermissionRequest,
|
|
880
|
+
SessionSnapshot,
|
|
881
|
+
# generic envelopes (contract v1.1 §11.4)
|
|
882
|
+
Items,
|
|
883
|
+
# cursor-paged list (contract §27)
|
|
884
|
+
SessionPage,
|
|
885
|
+
# event envelope + payloads
|
|
886
|
+
Event,
|
|
887
|
+
ServerHelloData,
|
|
888
|
+
ServerHeartbeatData,
|
|
889
|
+
SessionCreatedData,
|
|
890
|
+
SessionUpdatedData,
|
|
891
|
+
SessionDeletedData,
|
|
892
|
+
SessionSubagentsData,
|
|
893
|
+
MessageCreatedData,
|
|
894
|
+
MessageUpdatedData,
|
|
895
|
+
MessageCompletedData,
|
|
896
|
+
PartUpdatedData,
|
|
897
|
+
PartDeltaData,
|
|
898
|
+
ToolCallData,
|
|
899
|
+
ToolResultData,
|
|
900
|
+
PermissionRequestedData,
|
|
901
|
+
PermissionResolvedData,
|
|
902
|
+
PtyDataData,
|
|
903
|
+
PtyExitData,
|
|
904
|
+
FileChangedData,
|
|
905
|
+
TurnStartedData,
|
|
906
|
+
TurnCheckpointData,
|
|
907
|
+
TurnFinishedData,
|
|
908
|
+
ErrorData,
|
|
909
|
+
ResyncRequiredData,
|
|
910
|
+
# REST shapes
|
|
911
|
+
HealthResponse,
|
|
912
|
+
ServerInfo,
|
|
913
|
+
CreateSessionInput,
|
|
914
|
+
PromptInput,
|
|
915
|
+
PromptResult,
|
|
916
|
+
ResolvePermissionInput,
|
|
917
|
+
FileNode,
|
|
918
|
+
FileTree,
|
|
919
|
+
FileContent,
|
|
920
|
+
WriteFileInput,
|
|
921
|
+
WriteFileResult,
|
|
922
|
+
FileDiff,
|
|
923
|
+
PtyCreateInput,
|
|
924
|
+
PtyCreateResult,
|
|
925
|
+
)
|
|
926
|
+
"""Every model that gets a JSON Schema in ``packages/nini-protocol/schema/``."""
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
# Typed list envelopes the service returns (contract v1.1 §11.4).
|
|
930
|
+
SessionItems = Items[Session]
|
|
931
|
+
MessageItems = Items[Message]
|
|
932
|
+
FileNodeItems = Items[FileNode]
|
|
933
|
+
|
|
934
|
+
PARAMETERIZED_MODELS: dict[str, type[NiniModel]] = {
|
|
935
|
+
"items_session": SessionItems,
|
|
936
|
+
"items_message": MessageItems,
|
|
937
|
+
"items_file_node": FileNodeItems,
|
|
938
|
+
}
|
|
939
|
+
"""Concrete ``Items[T]`` instantiations exported as their own schemas."""
|
|
File without changes
|
|
File without changes
|