seshi 0.11.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.
- seshi/__init__.py +119 -0
- seshi/_calls.py +482 -0
- seshi/_routes.py +84 -0
- seshi/_version.py +3 -0
- seshi/client.py +809 -0
- seshi/errors.py +74 -0
- seshi/models.py +1093 -0
- seshi/py.typed +0 -0
- seshi-0.11.0.dist-info/METADATA +75 -0
- seshi-0.11.0.dist-info/RECORD +12 -0
- seshi-0.11.0.dist-info/WHEEL +4 -0
- seshi-0.11.0.dist-info/licenses/LICENSE +21 -0
seshi/__init__.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""The typed Python client for a seshi server.
|
|
2
|
+
|
|
3
|
+
from seshi import SeshiClient, Upload
|
|
4
|
+
|
|
5
|
+
with SeshiClient("https://seshi.acme.internal", token) as db:
|
|
6
|
+
answer = db.ingest(Upload(agent="claude-code", session_id="8f1c…", transcript=log))
|
|
7
|
+
|
|
8
|
+
See docs/client.md in the seshi repository.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._calls import RETRACT_HEADER, rfc3339
|
|
12
|
+
from ._version import __version__
|
|
13
|
+
from .client import AsyncSeshiClient, SeshiClient, auth_config, exchange_id_token
|
|
14
|
+
from .errors import (
|
|
15
|
+
Forbidden,
|
|
16
|
+
OffsetMismatch,
|
|
17
|
+
ServerError,
|
|
18
|
+
SeshiError,
|
|
19
|
+
SessionConflict,
|
|
20
|
+
SessionRejected,
|
|
21
|
+
StoreError,
|
|
22
|
+
)
|
|
23
|
+
from .models import (
|
|
24
|
+
AllChangesPage,
|
|
25
|
+
AtifDocument,
|
|
26
|
+
AuthConfig,
|
|
27
|
+
Change,
|
|
28
|
+
ChangeEntry,
|
|
29
|
+
ChangesPage,
|
|
30
|
+
ConfigStatus,
|
|
31
|
+
CreatedToken,
|
|
32
|
+
ExchangeRequest,
|
|
33
|
+
ExchangeResult,
|
|
34
|
+
Health,
|
|
35
|
+
Identity,
|
|
36
|
+
IngestResult,
|
|
37
|
+
JobsStatus,
|
|
38
|
+
LettaTrace,
|
|
39
|
+
NotWritten,
|
|
40
|
+
OtlpTrace,
|
|
41
|
+
OwnedChange,
|
|
42
|
+
OwnersPage,
|
|
43
|
+
RecordsPage,
|
|
44
|
+
RedactionRules,
|
|
45
|
+
RedactionRulesAnswer,
|
|
46
|
+
ReloadReport,
|
|
47
|
+
ReloadResult,
|
|
48
|
+
Removed,
|
|
49
|
+
ReviewDecision,
|
|
50
|
+
SearchRequest,
|
|
51
|
+
SearchResult,
|
|
52
|
+
SearchResults,
|
|
53
|
+
SessionMetadata,
|
|
54
|
+
SessionsPage,
|
|
55
|
+
SourceStatus,
|
|
56
|
+
StaleSessionsPage,
|
|
57
|
+
Stored,
|
|
58
|
+
StoredTrace,
|
|
59
|
+
TokenInfo,
|
|
60
|
+
TokenRequest,
|
|
61
|
+
Trace,
|
|
62
|
+
Upload,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"RETRACT_HEADER",
|
|
67
|
+
"AllChangesPage",
|
|
68
|
+
"AsyncSeshiClient",
|
|
69
|
+
"AtifDocument",
|
|
70
|
+
"AuthConfig",
|
|
71
|
+
"Change",
|
|
72
|
+
"ChangeEntry",
|
|
73
|
+
"ChangesPage",
|
|
74
|
+
"ConfigStatus",
|
|
75
|
+
"CreatedToken",
|
|
76
|
+
"ExchangeRequest",
|
|
77
|
+
"ExchangeResult",
|
|
78
|
+
"Forbidden",
|
|
79
|
+
"Health",
|
|
80
|
+
"Identity",
|
|
81
|
+
"IngestResult",
|
|
82
|
+
"JobsStatus",
|
|
83
|
+
"LettaTrace",
|
|
84
|
+
"NotWritten",
|
|
85
|
+
"OffsetMismatch",
|
|
86
|
+
"OtlpTrace",
|
|
87
|
+
"OwnedChange",
|
|
88
|
+
"OwnersPage",
|
|
89
|
+
"RecordsPage",
|
|
90
|
+
"RedactionRules",
|
|
91
|
+
"RedactionRulesAnswer",
|
|
92
|
+
"ReloadReport",
|
|
93
|
+
"ReloadResult",
|
|
94
|
+
"Removed",
|
|
95
|
+
"ReviewDecision",
|
|
96
|
+
"SearchRequest",
|
|
97
|
+
"SearchResult",
|
|
98
|
+
"SearchResults",
|
|
99
|
+
"ServerError",
|
|
100
|
+
"SeshiClient",
|
|
101
|
+
"SeshiError",
|
|
102
|
+
"SessionConflict",
|
|
103
|
+
"SessionMetadata",
|
|
104
|
+
"SessionRejected",
|
|
105
|
+
"SessionsPage",
|
|
106
|
+
"SourceStatus",
|
|
107
|
+
"StaleSessionsPage",
|
|
108
|
+
"StoreError",
|
|
109
|
+
"Stored",
|
|
110
|
+
"StoredTrace",
|
|
111
|
+
"TokenInfo",
|
|
112
|
+
"TokenRequest",
|
|
113
|
+
"Trace",
|
|
114
|
+
"Upload",
|
|
115
|
+
"__version__",
|
|
116
|
+
"auth_config",
|
|
117
|
+
"exchange_id_token",
|
|
118
|
+
"rfc3339",
|
|
119
|
+
]
|
seshi/_calls.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Each API call as data: the request to send and how to read the answer. The sync and async
|
|
2
|
+
clients only move the bytes, so every rule about a route (its status codes, what is None, what
|
|
3
|
+
is refused) is written once, here."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import gzip
|
|
8
|
+
import json
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from typing import Any, Generic, TypeVar
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
from pydantic import BaseModel, TypeAdapter
|
|
17
|
+
|
|
18
|
+
from . import models as m
|
|
19
|
+
from ._routes import ROUTES, Route
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
from .errors import (
|
|
22
|
+
Forbidden,
|
|
23
|
+
OffsetMismatch,
|
|
24
|
+
ServerError,
|
|
25
|
+
SessionConflict,
|
|
26
|
+
SessionRejected,
|
|
27
|
+
StoreError,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
T = TypeVar("T")
|
|
31
|
+
M = TypeVar("M", bound=BaseModel)
|
|
32
|
+
|
|
33
|
+
DEFAULT_USER_AGENT = f"seshi-python/{__version__}"
|
|
34
|
+
DEFAULT_TIMEOUT = 120.0
|
|
35
|
+
"""Seconds per request: a large transcript can take the server a while to normalize and
|
|
36
|
+
verify. The server's own idle timeout."""
|
|
37
|
+
DEFAULT_GZIP_FROM = 8 * 1024
|
|
38
|
+
RETRACT_HEADER = "X-Seshi-Retract"
|
|
39
|
+
"""The header a retraction, or an org-key replace, carries the session's secret in (F9.7)."""
|
|
40
|
+
|
|
41
|
+
QueryValue = str | int | bool | datetime | None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Answer:
|
|
46
|
+
status: int
|
|
47
|
+
body: Any
|
|
48
|
+
headers: httpx.Headers
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Call(Generic[T]):
|
|
53
|
+
operation: str
|
|
54
|
+
read: Callable[[Answer], T]
|
|
55
|
+
path_params: Mapping[str, str] = field(default_factory=dict)
|
|
56
|
+
query: Mapping[str, QueryValue] = field(default_factory=dict)
|
|
57
|
+
body: Any = None
|
|
58
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def route(self) -> Route:
|
|
62
|
+
return ROUTES[self.operation]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Settings:
|
|
67
|
+
server: str
|
|
68
|
+
token: str | None
|
|
69
|
+
user: str | None
|
|
70
|
+
user_agent: str
|
|
71
|
+
gzip_from: int
|
|
72
|
+
timeout: float | None
|
|
73
|
+
"""Seconds per request; 0 or None disables. Set on each request, so it holds whatever
|
|
74
|
+
httpx client sends it."""
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _query_value(value: QueryValue) -> str:
|
|
78
|
+
if isinstance(value, bool):
|
|
79
|
+
return "true" if value else "false"
|
|
80
|
+
if isinstance(value, datetime):
|
|
81
|
+
return rfc3339(value)
|
|
82
|
+
return str(value)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def rfc3339(value: datetime) -> str:
|
|
86
|
+
"""A time as seshi writes it: UTC, milliseconds, `Z` (`2026-11-14T09:00:00.000Z`). A naive
|
|
87
|
+
time is taken as UTC."""
|
|
88
|
+
if value.tzinfo is None:
|
|
89
|
+
value = value.replace(tzinfo=timezone.utc)
|
|
90
|
+
utc = value.astimezone(timezone.utc)
|
|
91
|
+
return utc.strftime("%Y-%m-%dT%H:%M:%S.") + f"{utc.microsecond // 1000:03d}Z"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def prepare(call: Call[Any], settings: Settings) -> httpx.Request:
|
|
95
|
+
"""The request a call sends. Fails on a parameter the route table does not list, so the
|
|
96
|
+
table `tests/test_spec_drift.py` checks is the one the client uses."""
|
|
97
|
+
route = call.route
|
|
98
|
+
path = route.path
|
|
99
|
+
for name, value in call.path_params.items():
|
|
100
|
+
placeholder = "{" + name + "}"
|
|
101
|
+
if placeholder not in path:
|
|
102
|
+
raise AssertionError(f"{call.operation}: no path parameter {name}")
|
|
103
|
+
path = path.replace(placeholder, quote(value, safe=""))
|
|
104
|
+
unknown = set(call.query) - set(route.query)
|
|
105
|
+
if unknown:
|
|
106
|
+
raise AssertionError(f"{call.operation}: query parameters {sorted(unknown)} not in routes")
|
|
107
|
+
known_headers = {h.lower() for h in route.headers}
|
|
108
|
+
unknown_headers = {h for h in call.headers if h.lower() not in known_headers}
|
|
109
|
+
if unknown_headers:
|
|
110
|
+
raise AssertionError(f"{call.operation}: headers {sorted(unknown_headers)} not in routes")
|
|
111
|
+
|
|
112
|
+
headers = {"user-agent": settings.user_agent, **call.headers}
|
|
113
|
+
if route.auth and settings.token is not None:
|
|
114
|
+
headers["authorization"] = f"Bearer {settings.token}"
|
|
115
|
+
if settings.user is not None:
|
|
116
|
+
headers["x-seshi-user"] = settings.user
|
|
117
|
+
content: bytes | None = None
|
|
118
|
+
if call.body is not None:
|
|
119
|
+
headers["content-type"] = "application/json"
|
|
120
|
+
content = json.dumps(call.body, separators=(",", ":"), ensure_ascii=False).encode()
|
|
121
|
+
if len(content) >= settings.gzip_from:
|
|
122
|
+
headers["content-encoding"] = "gzip"
|
|
123
|
+
content = gzip.compress(content)
|
|
124
|
+
params = {k: _query_value(v) for k, v in call.query.items() if v is not None}
|
|
125
|
+
return httpx.Request(
|
|
126
|
+
route.method,
|
|
127
|
+
settings.server + path,
|
|
128
|
+
params=params,
|
|
129
|
+
headers=headers,
|
|
130
|
+
content=content,
|
|
131
|
+
extensions={"timeout": httpx.Timeout(settings.timeout or None).as_dict()},
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def read(response: httpx.Response) -> Answer:
|
|
136
|
+
text = response.text
|
|
137
|
+
body: Any = None
|
|
138
|
+
if text:
|
|
139
|
+
try:
|
|
140
|
+
body = json.loads(text)
|
|
141
|
+
except ValueError:
|
|
142
|
+
if response.is_success:
|
|
143
|
+
raise ServerError(
|
|
144
|
+
response.status_code, "bad_response", f"not JSON: {text[:200]}"
|
|
145
|
+
) from None
|
|
146
|
+
return Answer(response.status_code, body, response.headers)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def unreachable(server: str, err: Exception) -> StoreError:
|
|
150
|
+
error = StoreError(f"cannot reach {server}: {err}")
|
|
151
|
+
error.__cause__ = err
|
|
152
|
+
return error
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _error(body: Any) -> dict[str, Any]:
|
|
156
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
157
|
+
return error if isinstance(error, dict) else {}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def error_code(body: Any) -> str | None:
|
|
161
|
+
code = _error(body).get("code")
|
|
162
|
+
return code if isinstance(code, str) else None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def refuse(answer: Answer, offset: int = 0) -> Exception:
|
|
166
|
+
"""The error an answer that is not the call's success means."""
|
|
167
|
+
error = _error(answer.body)
|
|
168
|
+
code = str(error.get("code") or "unknown")
|
|
169
|
+
message = str(error.get("message") or f"HTTP {answer.status}")
|
|
170
|
+
status = answer.status
|
|
171
|
+
if status == 409 and code == "offset_mismatch":
|
|
172
|
+
expected = error.get("expected")
|
|
173
|
+
return OffsetMismatch(offset, expected if isinstance(expected, int) else 0)
|
|
174
|
+
if status == 409 and code == "conflict":
|
|
175
|
+
return SessionConflict(message)
|
|
176
|
+
if status == 403 and code == "forbidden":
|
|
177
|
+
return Forbidden(message)
|
|
178
|
+
if status == 422:
|
|
179
|
+
return SessionRejected(code, message)
|
|
180
|
+
if status == 502:
|
|
181
|
+
return StoreError(message)
|
|
182
|
+
return ServerError(status, code, message)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# --- Reading answers ------------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _expect(answer: Answer, *statuses: int, offset: int = 0) -> Any:
|
|
189
|
+
if answer.status not in statuses:
|
|
190
|
+
raise refuse(answer, offset)
|
|
191
|
+
return answer.body
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _model(model: type[M], *statuses: int) -> Callable[[Answer], M]:
|
|
195
|
+
return lambda answer: model.model_validate(_expect(answer, *(statuses or (200,))))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _or_none(model: type[M], *none_on: int) -> Callable[[Answer], M | None]:
|
|
199
|
+
def read_answer(answer: Answer) -> M | None:
|
|
200
|
+
if answer.status in none_on:
|
|
201
|
+
return None
|
|
202
|
+
return model.model_validate(_expect(answer, 200))
|
|
203
|
+
|
|
204
|
+
return read_answer
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _dump(value: BaseModel | Mapping[str, Any], model: type[BaseModel]) -> dict[str, Any]:
|
|
208
|
+
"""The body `model` sends: `value` checked as one, whatever it was given as (another model
|
|
209
|
+
is checked by its fields, so a stray field is refused here, not by the server)."""
|
|
210
|
+
if isinstance(value, model):
|
|
211
|
+
checked: BaseModel = value
|
|
212
|
+
elif isinstance(value, BaseModel):
|
|
213
|
+
checked = model.model_validate(value.model_dump(by_alias=True, exclude_none=True))
|
|
214
|
+
else:
|
|
215
|
+
checked = model.model_validate(value)
|
|
216
|
+
return checked.model_dump(mode="json", by_alias=True, exclude_none=True)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _session(agent: str, session_id: str) -> dict[str, str]:
|
|
220
|
+
return {"agent": agent, "session_id": session_id}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
_INGEST_RESULT: TypeAdapter[m.Stored | m.NotWritten] = TypeAdapter(m.IngestResult)
|
|
224
|
+
_TRACES: dict[str | None, type[BaseModel]] = {
|
|
225
|
+
None: m.Trace,
|
|
226
|
+
"seshi": m.Trace,
|
|
227
|
+
"letta": m.LettaTrace,
|
|
228
|
+
"otlp": m.OtlpTrace,
|
|
229
|
+
"atif": m.AtifDocument,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# --- The calls ------------------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def health() -> Call[m.Health]:
|
|
237
|
+
return Call("health", _model(m.Health))
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def auth_config() -> Call[m.AuthConfig]:
|
|
241
|
+
return Call("authConfig", _model(m.AuthConfig))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def exchange(request: m.ExchangeRequest | Mapping[str, Any]) -> Call[m.ExchangeResult]:
|
|
245
|
+
return Call("exchange", _model(m.ExchangeResult), body=_dump(request, m.ExchangeRequest))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def me() -> Call[m.Identity]:
|
|
249
|
+
return Call("me", _model(m.Identity))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def owners(after: str | None, limit: int | None) -> Call[m.OwnersPage]:
|
|
253
|
+
return Call("listOwners", _model(m.OwnersPage), query={"after": after, "limit": limit})
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def ingest(
|
|
257
|
+
upload: m.Upload | Mapping[str, Any],
|
|
258
|
+
retract_secret: str | None,
|
|
259
|
+
idempotency_key: str | None,
|
|
260
|
+
) -> Call[m.Stored | m.NotWritten]:
|
|
261
|
+
body = _dump(upload, m.Upload)
|
|
262
|
+
offset = int(body.get("offset", 0))
|
|
263
|
+
headers: dict[str, str] = {}
|
|
264
|
+
if retract_secret is not None:
|
|
265
|
+
headers[RETRACT_HEADER] = retract_secret
|
|
266
|
+
if idempotency_key is not None:
|
|
267
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
268
|
+
|
|
269
|
+
def read_answer(answer: Answer) -> m.Stored | m.NotWritten:
|
|
270
|
+
return _INGEST_RESULT.validate_python(_expect(answer, 200, 201, offset=offset))
|
|
271
|
+
|
|
272
|
+
return Call("ingest", read_answer, body=body, headers=headers)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def get_session(agent: str, session_id: str, owner: str | None) -> Call[m.SessionMetadata | None]:
|
|
276
|
+
return Call(
|
|
277
|
+
"getSession",
|
|
278
|
+
_or_none(m.SessionMetadata, 404),
|
|
279
|
+
path_params=_session(agent, session_id),
|
|
280
|
+
query={"owner": owner},
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def get_trace(
|
|
285
|
+
agent: str,
|
|
286
|
+
session_id: str,
|
|
287
|
+
hash: str | None,
|
|
288
|
+
format: m.RenderFormat | None,
|
|
289
|
+
owner: str | None,
|
|
290
|
+
) -> Call[Any]:
|
|
291
|
+
return Call(
|
|
292
|
+
"getTrace",
|
|
293
|
+
_or_none(_TRACES[format], 404, 410),
|
|
294
|
+
path_params=_session(agent, session_id),
|
|
295
|
+
query={"owner": owner, "hash": hash, "format": format},
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def list_sessions(owner: str | None, after: str | None, limit: int | None) -> Call[m.SessionsPage]:
|
|
300
|
+
return Call(
|
|
301
|
+
"listSessions",
|
|
302
|
+
_model(m.SessionsPage),
|
|
303
|
+
query={"owner": owner, "after": after, "limit": limit},
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def stale_sessions(after: str | None, limit: int | None) -> Call[m.StaleSessionsPage]:
|
|
308
|
+
return Call(
|
|
309
|
+
"staleSessions", _model(m.StaleSessionsPage), query={"after": after, "limit": limit}
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def tombstone(
|
|
314
|
+
agent: str, session_id: str, owner: str | None, retract_secret: str | None
|
|
315
|
+
) -> Call[m.Removed | None]:
|
|
316
|
+
return Call(
|
|
317
|
+
"tombstone",
|
|
318
|
+
_or_none(m.Removed, 404),
|
|
319
|
+
path_params=_session(agent, session_id),
|
|
320
|
+
query={"owner": owner},
|
|
321
|
+
headers={RETRACT_HEADER: retract_secret} if retract_secret is not None else {},
|
|
322
|
+
)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def set_visibility(
|
|
326
|
+
agent: str, session_id: str, visibility: m.Visibility, owner: str | None
|
|
327
|
+
) -> Call[m.SessionMetadata | None]:
|
|
328
|
+
return Call(
|
|
329
|
+
"setVisibility",
|
|
330
|
+
_or_none(m.SessionMetadata, 404),
|
|
331
|
+
path_params=_session(agent, session_id),
|
|
332
|
+
query={"owner": owner},
|
|
333
|
+
body=_dump({"visibility": visibility}, m.VisibilityChange),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def reviews(agent: str, session_id: str, owner: str | None) -> Call[list[m.ReviewDecision] | None]:
|
|
338
|
+
def read_answer(answer: Answer) -> list[m.ReviewDecision] | None:
|
|
339
|
+
if answer.status == 404:
|
|
340
|
+
return None
|
|
341
|
+
return m.ReviewsPage.model_validate(_expect(answer, 200)).reviews
|
|
342
|
+
|
|
343
|
+
return Call(
|
|
344
|
+
"sessionReviews",
|
|
345
|
+
read_answer,
|
|
346
|
+
path_params=_session(agent, session_id),
|
|
347
|
+
query={"owner": owner},
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def changes(
|
|
352
|
+
owner: str | None, after: str | None, since: str | datetime | None, limit: int | None
|
|
353
|
+
) -> Call[m.ChangesPage]:
|
|
354
|
+
return Call(
|
|
355
|
+
"changes",
|
|
356
|
+
_model(m.ChangesPage),
|
|
357
|
+
query={"owner": owner, "after": after, "since": since, "limit": limit},
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def all_changes(
|
|
362
|
+
after: str | None, since: str | datetime | None, limit: int | None
|
|
363
|
+
) -> Call[m.AllChangesPage]:
|
|
364
|
+
return Call(
|
|
365
|
+
"allChanges",
|
|
366
|
+
_model(m.AllChangesPage),
|
|
367
|
+
query={"after": after, "since": since, "limit": limit},
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def search(request: m.SearchRequest) -> Call[m.SearchResults]:
|
|
372
|
+
query: dict[str, QueryValue] = dict(request.model_dump(exclude_none=True))
|
|
373
|
+
return Call("search", _model(m.SearchResults), query=query)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def redaction_rules() -> Call[m.RedactionRules]:
|
|
377
|
+
return Call("redactionRules", _model(m.RedactionRules))
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def redaction_rules_since(etag: str | None) -> Call[m.RedactionRulesAnswer | None]:
|
|
381
|
+
def read_answer(answer: Answer) -> m.RedactionRulesAnswer | None:
|
|
382
|
+
if answer.status == 304 and etag:
|
|
383
|
+
return None
|
|
384
|
+
document = m.RedactionRules.model_validate(_expect(answer, 200))
|
|
385
|
+
return m.RedactionRulesAnswer(document=document, etag=answer.headers.get("etag"))
|
|
386
|
+
|
|
387
|
+
return Call("redactionRules", read_answer, headers={"If-None-Match": etag} if etag else {})
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def create_token(request: m.TokenRequest | Mapping[str, Any]) -> Call[m.CreatedToken]:
|
|
391
|
+
return Call("createToken", _model(m.CreatedToken, 201), body=_dump(request, m.TokenRequest))
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def list_tokens(owner: str | None, kind: m.TokenKind | None, all: bool) -> Call[list[m.TokenInfo]]:
|
|
395
|
+
return Call(
|
|
396
|
+
"listTokens",
|
|
397
|
+
lambda answer: m.TokenList.model_validate(_expect(answer, 200)).tokens,
|
|
398
|
+
query={"owner": owner, "kind": kind, "all": True if all else None},
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def revoke_token(id: str) -> Call[m.TokenInfo | None]:
|
|
403
|
+
def read_answer(answer: Answer) -> m.TokenInfo | None:
|
|
404
|
+
if answer.status == 404:
|
|
405
|
+
return None
|
|
406
|
+
return m.RevokedToken.model_validate(_expect(answer, 200)).token
|
|
407
|
+
|
|
408
|
+
return Call("revokeToken", read_answer, path_params={"id": id})
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def revoke_owner_tokens(owner: str, kind: m.TokenKind | None) -> Call[list[m.TokenInfo]]:
|
|
412
|
+
return Call(
|
|
413
|
+
"revokeOwnerTokens",
|
|
414
|
+
lambda answer: m.RevokedTokens.model_validate(_expect(answer, 200)).revoked,
|
|
415
|
+
body=_dump(m.OwnerRevocation(owner=owner, kind=kind), m.OwnerRevocation),
|
|
416
|
+
)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def jobs() -> Call[m.JobsStatus]:
|
|
420
|
+
return Call("adminJobs", _model(m.JobsStatus))
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def config_status() -> Call[m.ConfigStatus]:
|
|
424
|
+
return Call("adminReloadStatus", _model(m.ConfigStatus))
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def reload() -> Call[m.ReloadResult]:
|
|
428
|
+
def read_answer(answer: Answer) -> m.ReloadResult:
|
|
429
|
+
body = answer.body
|
|
430
|
+
if (
|
|
431
|
+
answer.status in (200, 422)
|
|
432
|
+
and isinstance(body, dict)
|
|
433
|
+
and "reload" in body
|
|
434
|
+
and "config" in body
|
|
435
|
+
):
|
|
436
|
+
return m.ReloadResult.model_validate(
|
|
437
|
+
{"reload": body["reload"], "config": body["config"]}
|
|
438
|
+
)
|
|
439
|
+
raise refuse(answer)
|
|
440
|
+
|
|
441
|
+
return Call("adminReload", read_answer)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def sources(days: int | None) -> Call[list[m.SourceStatus]]:
|
|
445
|
+
return Call(
|
|
446
|
+
"adminSources",
|
|
447
|
+
lambda answer: m.SourceList.model_validate(_expect(answer, 200)).sources,
|
|
448
|
+
query={"days": days},
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def _unknown_source_is_none(model: type[M]) -> Callable[[Answer], M | None]:
|
|
453
|
+
def read_answer(answer: Answer) -> M | None:
|
|
454
|
+
if answer.status == 404 and error_code(answer.body) == "unknown_source":
|
|
455
|
+
return None
|
|
456
|
+
return model.model_validate(_expect(answer, 200))
|
|
457
|
+
|
|
458
|
+
return read_answer
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def source(id: str, days: int | None) -> Call[m.SourceStatus | None]:
|
|
462
|
+
return Call(
|
|
463
|
+
"adminSource",
|
|
464
|
+
_unknown_source_is_none(m.SourceStatus),
|
|
465
|
+
path_params={"id": id},
|
|
466
|
+
query={"days": days},
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def records(
|
|
471
|
+
kind: m.RecordKind,
|
|
472
|
+
id: str,
|
|
473
|
+
since: str | datetime | None,
|
|
474
|
+
after: str | None,
|
|
475
|
+
limit: int | None,
|
|
476
|
+
) -> Call[m.RecordsPage | None]:
|
|
477
|
+
return Call(
|
|
478
|
+
"adminSourceRecords",
|
|
479
|
+
_unknown_source_is_none(m.RecordsPage),
|
|
480
|
+
path_params={"id": id, "kind": kind},
|
|
481
|
+
query={"since": since, "after": after, "limit": limit},
|
|
482
|
+
)
|
seshi/_routes.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Every route of `spec/openapi.yaml` this client calls, by operationId, with the query and
|
|
2
|
+
header parameters it handles.
|
|
3
|
+
|
|
4
|
+
The clients build every request from this table (`_calls.py` checks each call's parameters
|
|
5
|
+
against it), and `tests/test_spec_drift.py` checks the table against the spec: a route the spec
|
|
6
|
+
gains, drops or moves, or a parameter it adds or removes, fails the test until the client
|
|
7
|
+
covers it or `UNCOVERED` says why it does not.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
SESSION = "/v1/sessions/{agent}/{session_id}"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Route:
|
|
19
|
+
method: str
|
|
20
|
+
path: str
|
|
21
|
+
"""The OpenAPI path template; `{name}` segments are percent-encoded when filled in."""
|
|
22
|
+
query: tuple[str, ...] = ()
|
|
23
|
+
headers: tuple[str, ...] = ()
|
|
24
|
+
"""Header parameters the client handles, as the spec spells them."""
|
|
25
|
+
auth: bool = True
|
|
26
|
+
"""Sends the credential. The three routes made before there is one do not."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
ROUTES: dict[str, Route] = {
|
|
30
|
+
"health": Route("GET", "/healthz", auth=False),
|
|
31
|
+
"authConfig": Route("GET", "/v1/auth/config", auth=False),
|
|
32
|
+
"exchange": Route("POST", "/v1/auth/exchange", auth=False),
|
|
33
|
+
"me": Route("GET", "/v1/me"),
|
|
34
|
+
"listOwners": Route("GET", "/v1/owners", query=("after", "limit")),
|
|
35
|
+
"ingest": Route("POST", "/v1/sessions", headers=("Idempotency-Key", "X-Seshi-Retract")),
|
|
36
|
+
"listSessions": Route("GET", "/v1/sessions", query=("owner", "after", "limit")),
|
|
37
|
+
"staleSessions": Route("GET", "/v1/sessions/stale", query=("after", "limit")),
|
|
38
|
+
"getSession": Route("GET", SESSION, query=("owner",)),
|
|
39
|
+
"setVisibility": Route("PATCH", SESSION, query=("owner",)),
|
|
40
|
+
"tombstone": Route("DELETE", SESSION, query=("owner",), headers=("X-Seshi-Retract",)),
|
|
41
|
+
"getTrace": Route("GET", f"{SESSION}/trace", query=("owner", "hash", "format")),
|
|
42
|
+
"sessionReviews": Route("GET", f"{SESSION}/reviews", query=("owner",)),
|
|
43
|
+
"changes": Route("GET", "/v1/changes", query=("owner", "after", "since", "limit")),
|
|
44
|
+
"allChanges": Route("GET", "/v1/changes/all", query=("after", "since", "limit")),
|
|
45
|
+
"search": Route(
|
|
46
|
+
"GET",
|
|
47
|
+
"/v1/search",
|
|
48
|
+
query=(
|
|
49
|
+
"q",
|
|
50
|
+
"owner",
|
|
51
|
+
"agent",
|
|
52
|
+
"repo",
|
|
53
|
+
"branch",
|
|
54
|
+
"source",
|
|
55
|
+
"since",
|
|
56
|
+
"until",
|
|
57
|
+
"sort",
|
|
58
|
+
"limit",
|
|
59
|
+
"matches",
|
|
60
|
+
"cursor",
|
|
61
|
+
),
|
|
62
|
+
),
|
|
63
|
+
"redactionRules": Route("GET", "/v1/redaction/rules", headers=("If-None-Match",)),
|
|
64
|
+
"createToken": Route("POST", "/v1/tokens"),
|
|
65
|
+
"listTokens": Route("GET", "/v1/tokens", query=("owner", "kind", "all")),
|
|
66
|
+
"revokeOwnerTokens": Route("POST", "/v1/tokens/revoke"),
|
|
67
|
+
"revokeToken": Route("DELETE", "/v1/tokens/{id}"),
|
|
68
|
+
"adminJobs": Route("GET", "/v1/admin/jobs"),
|
|
69
|
+
"adminSources": Route("GET", "/v1/admin/sources", query=("days",)),
|
|
70
|
+
"adminSource": Route("GET", "/v1/admin/sources/{id}", query=("days",)),
|
|
71
|
+
"adminSourceRecords": Route(
|
|
72
|
+
"GET", "/v1/admin/sources/{id}/{kind}", query=("since", "after", "limit")
|
|
73
|
+
),
|
|
74
|
+
"adminReloadStatus": Route("GET", "/v1/admin/reload"),
|
|
75
|
+
"adminReload": Route("POST", "/v1/admin/reload"),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
UNCOVERED: dict[str, str] = {
|
|
79
|
+
"exportTrace": (
|
|
80
|
+
"the trace getTrace returns, with Content-Disposition for a browser download; use get_trace"
|
|
81
|
+
),
|
|
82
|
+
"otlpTraces": "where OTLP exporters (a Claude Console destination) push spans; not a client's",
|
|
83
|
+
}
|
|
84
|
+
"""Routes in the spec this client leaves out on purpose, and why."""
|
seshi/_version.py
ADDED