feat(#20): admin (bifrost inspection + admin-events stream) onto the wt adapter (slice-6)
Slice-6 of the worldtree-sdk cutover: migrate the two admin routes off the
hand-rolled paths onto the `ratatoskr.wt` adapter over `client.admin.*`, and delete
the retired code. Both are web-only (the coverage-map's `tui.py` rows were stale —
corrected to `web/server.py`).
Adapter (`wt.py`): `get_session_bifrost` → `client.admin.sessions.bifrost` (open-world
dict verbatim, any error → SessionApiFailed default); `stream_admin_events` →
`client.admin.stream_events`, re-wrapping the SDK's `AdminEvent` → ratatoskr's at the
boundary.
Decisions (contract § slice-6 notes):
- Admin auth moves from a per-call `Authorization` header override to the client's
`admin_auth` (`_wt_client(admin_key=…)`, extended this slice) — the SDK's admin.*
routes use the provider, not a header.
- `AdminEvent` re-wrap (chosen over yield-through): the SDK's `admin_id`(nan)/None-able
`type`/`data` diverge from ratatoskr's `id`/`type`/`data` that the web filter reads;
re-wrapping (nan→0, None→""/{}) degrades the open-world None/nan ONCE at the adapter
and keeps the web endpoint + `_admin_event_matches_web` + the `AdminEvent` domain type
unchanged (preserves the web surface). Rejected: yield SDK events + rewire the web
filter (heavier churn, scattered hardening).
- Admin-stream error map: a NON-200 open raises `ApiError("admin_stream_failed")`
(NOT `ConnectFailed`) → SseConnectFailed; `ConnectionDropped` (connect-time OR
mid-stream/resumable-EOF) → SseConnectionDropped. The web integration test caught the
ApiError-not-ConnectFailed gotcha the unit fake couldn't.
Web (`web/server.py`): both admin endpoints build the wt client with admin_key and call
`wt.*`; the bifrost endpoint gains ConnectFailed→502 handling (cutover foot-gun); the
admin-events endpoint closes the injected transport (INV-CUT-1), never the wt client.
Deleted the hand-rolled `sessions.get_session_bifrost` + `sse_client.stream_admin_events`
(+ orphaned httpx/httpx_sse/json/AsyncIterator imports); the ratatoskr `AdminEvent`
dataclass stays in `sse_client.py` (re-wrap target, imported by wt + web) until slice-7.
Retired `test_sse_client.py` entirely (its last test was the admin stream) and the
`test_sessions.py` `TestGetSessionBifrost`; added the slice-6 adapter tests.
LIVE SMOKE (:8081, readonly-admin key) — INV-CUT-5 / DEC-4 cleared: the web bifrost
endpoint returned an admin-authed clean 404 envelope (auth + route + mapping proven);
a real `session.created` admin event (id=32) re-wrapped cleanly on live wire (driven by
a session-create, throwaway session cleaned up).
Suite 490 green; ruff clean; mypy net-improved on web/server.py (16→12 pre-existing, no
new). Patch bump 0.21.18 → 0.21.19 (the cutover MINOR is deferred to slice-7, DEC-6).
This commit is contained in:
@@ -38,6 +38,7 @@ from ratatoskr.sessions import (
|
||||
Tier3UserIdUnsupported,
|
||||
)
|
||||
from ratatoskr.sse_client import (
|
||||
AdminEvent,
|
||||
AgentNotAvailable,
|
||||
CancelAlreadyCompleted,
|
||||
CancelFailed,
|
||||
@@ -62,6 +63,7 @@ from ratatoskr.wt import (
|
||||
get_character_state,
|
||||
get_me,
|
||||
get_persona_state,
|
||||
get_session_bifrost,
|
||||
get_session_messages,
|
||||
get_session_tools,
|
||||
list_agents,
|
||||
@@ -69,6 +71,7 @@ from ratatoskr.wt import (
|
||||
list_sessions,
|
||||
patch_agent,
|
||||
set_persona_state,
|
||||
stream_admin_events,
|
||||
stream_turn,
|
||||
translate_error,
|
||||
write_authored_history,
|
||||
@@ -1066,3 +1069,153 @@ class TestDeleteCharacter:
|
||||
with pytest.raises(SessionApiFailed) as ei:
|
||||
await delete_character(_wtm(fake), "char_x")
|
||||
assert ei.value.status == 500
|
||||
|
||||
|
||||
# ── slice-6: admin (bifrost inspection + admin-events stream) adapter routes ──
|
||||
|
||||
|
||||
class _SdkAdminEvent:
|
||||
"""Minimal stand-in for the SDK's `AdminEvent` — the adapter reads
|
||||
`admin_id`/`type`/`timestamp`/`data`. `admin_id` may be `nan` (id-less);
|
||||
`type`/`data` may be None (open-world)."""
|
||||
|
||||
def __init__(self, admin_id: Any, type: Any, timestamp: Any = None, data: Any = None) -> None:
|
||||
self.admin_id = admin_id
|
||||
self.type = type
|
||||
self.timestamp = timestamp
|
||||
self.data = data
|
||||
|
||||
|
||||
class _FakeAdminSessions:
|
||||
def __init__(self, admin: _FakeAdmin) -> None:
|
||||
self._admin = admin
|
||||
|
||||
async def bifrost(self, *a: Any, **k: Any) -> Any:
|
||||
return await self._admin._bifrost(*a, **k)
|
||||
|
||||
|
||||
class _FakeAdmin:
|
||||
"""Stand-in for `client.admin` — `.sessions.bifrost(id)` (canned result/error) +
|
||||
`.stream_events(...)` (canned events / terminal error). Same shape as `_FakeSessions`."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
result: Any = None,
|
||||
error: BaseException | None = None,
|
||||
events: list[Any] | None = None,
|
||||
stream_error: BaseException | None = None,
|
||||
) -> None:
|
||||
self._result = result
|
||||
self._error = error
|
||||
self._events = events or []
|
||||
self._stream_error = stream_error
|
||||
self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = []
|
||||
self.sessions = _FakeAdminSessions(self)
|
||||
|
||||
async def _bifrost(self, *a: Any, **k: Any) -> Any:
|
||||
self.calls.append(("bifrost", a, k))
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._result
|
||||
|
||||
def stream_events(self, *a: Any, **k: Any) -> Any:
|
||||
self.calls.append(("stream_events", a, k))
|
||||
return self._astream()
|
||||
|
||||
async def _astream(self) -> Any:
|
||||
for ev in self._events:
|
||||
yield ev
|
||||
if self._stream_error is not None:
|
||||
raise self._stream_error
|
||||
|
||||
|
||||
class _FakeAdminClient:
|
||||
def __init__(self, admin: _FakeAdmin) -> None:
|
||||
self.admin = admin
|
||||
|
||||
|
||||
def _wtad(admin: _FakeAdmin) -> WorldtreeClient:
|
||||
"""Cast the admin-surface fake (`.admin.sessions.bifrost` + `.admin.stream_events`)
|
||||
to the nominal client type the slice-6 route functions are typed against."""
|
||||
return cast(WorldtreeClient, _FakeAdminClient(admin))
|
||||
|
||||
|
||||
class TestGetSessionBifrostWt:
|
||||
"""slice-6: get_session_bifrost → SDK admin.sessions.bifrost(id); open-world verbatim."""
|
||||
|
||||
async def test_happy_returns_dict_verbatim(self) -> None:
|
||||
binding = {"endpoint_url": "https://b/mcp", "connected": True, "tools": []}
|
||||
fake = _FakeAdmin(result=binding)
|
||||
out = await get_session_bifrost(_wtad(fake), "s1")
|
||||
assert out is binding
|
||||
assert fake.calls[-1] == ("bifrost", ("s1",), {})
|
||||
|
||||
async def test_empty_id_asserts_no_call(self) -> None:
|
||||
fake = _FakeAdmin(result={})
|
||||
with pytest.raises(AssertionError):
|
||||
await get_session_bifrost(_wtad(fake), "")
|
||||
assert fake.calls == []
|
||||
|
||||
async def test_403_maps_to_session_api_failed(self) -> None:
|
||||
fake = _FakeAdmin(error=ApiError("auth_scope_denied", "no", status=403))
|
||||
with pytest.raises(SessionApiFailed) as ei:
|
||||
await get_session_bifrost(_wtad(fake), "s1")
|
||||
assert ei.value.status == 403
|
||||
|
||||
async def test_404_not_bound_maps_to_session_api_failed(self) -> None:
|
||||
fake = _FakeAdmin(error=ApiError("session_not_bifrost_bound", "no", status=404))
|
||||
with pytest.raises(SessionApiFailed) as ei:
|
||||
await get_session_bifrost(_wtad(fake), "s1")
|
||||
assert ei.value.status == 404
|
||||
|
||||
|
||||
class TestStreamAdminEventsWt:
|
||||
"""slice-6: stream_admin_events → SDK admin.stream_events; re-wrap SDK AdminEvent →
|
||||
ratatoskr AdminEvent (nan/None degraded), terminal errors → Sse* types."""
|
||||
|
||||
async def test_rewraps_events_to_ratatoskr_shape(self) -> None:
|
||||
sdk_evs = [
|
||||
_SdkAdminEvent(5, "session.created", "t0", {"session_id": "s1"}),
|
||||
_SdkAdminEvent(6, "turn.completed", "t1", {"session_id": "s1", "turn_id": 2}),
|
||||
]
|
||||
fake = _FakeAdmin(events=sdk_evs)
|
||||
out = await _drain(stream_admin_events(_wtad(fake)))
|
||||
assert all(isinstance(e, AdminEvent) for e in out)
|
||||
assert (out[0].id, out[0].type, out[0].timestamp) == (5, "session.created", "t0")
|
||||
assert out[0].data == {"session_id": "s1"}
|
||||
assert out[1].id == 6
|
||||
|
||||
async def test_nan_admin_id_degrades_to_zero(self) -> None:
|
||||
fake = _FakeAdmin(events=[_SdkAdminEvent(float("nan"), "system.heartbeat", None, None)])
|
||||
out = await _drain(stream_admin_events(_wtad(fake)))
|
||||
assert out[0].id == 0 # id-less envelope → 0, not nan
|
||||
|
||||
async def test_none_type_and_data_degrade(self) -> None:
|
||||
# A partial wire: type=None (would crash `.startswith` in the web filter) and
|
||||
# data=None (would crash `.get`) → "" and {} at the adapter boundary.
|
||||
fake = _FakeAdmin(events=[_SdkAdminEvent(1, None, None, None)])
|
||||
out = await _drain(stream_admin_events(_wtad(fake)))
|
||||
assert out[0].type == ""
|
||||
assert out[0].data == {}
|
||||
|
||||
async def test_passes_last_event_id(self) -> None:
|
||||
fake = _FakeAdmin(events=[])
|
||||
await _drain(stream_admin_events(_wtad(fake), last_event_id=42))
|
||||
assert fake.calls[-1] == ("stream_events", (), {"last_event_id": 42})
|
||||
|
||||
async def test_non_200_apierror_maps_to_sse_connect_failed(self) -> None:
|
||||
# The SDK admin stream raises ApiError("admin_stream_failed", status=…) on a
|
||||
# non-200 open (NOT ConnectFailed) — mapped → SseConnectFailed for the web.
|
||||
fake = _FakeAdmin(stream_error=ApiError("admin_stream_failed", "no", status=502))
|
||||
with pytest.raises(SseConnectFailed) as ei:
|
||||
await _drain(stream_admin_events(_wtad(fake)))
|
||||
assert ei.value.status == 502
|
||||
|
||||
async def test_connection_dropped_maps_and_carries_cursor(self) -> None:
|
||||
# Both a connect-time failure (cursor None) and a mid-stream drop / resumable
|
||||
# EOF (cursor set) surface as ConnectionDropped → SseConnectionDropped.
|
||||
fake = _FakeAdmin(stream_error=wtsdk.ConnectionDropped("42"))
|
||||
with pytest.raises(SseConnectionDropped) as ei:
|
||||
await _drain(stream_admin_events(_wtad(fake)))
|
||||
assert ei.value.last_seen_sse_id == "42"
|
||||
|
||||
Reference in New Issue
Block a user