driverkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
driverkit/__init__.py ADDED
@@ -0,0 +1,93 @@
1
+ """
2
+ driverkit — the Python half.
3
+
4
+ Four things live here, and they are the whole backend side of PROTOCOL.md:
5
+
6
+ * :class:`driverkit.Driverkit`, a synchronous client for the relay's
7
+ agent-facing HTTP surface, returning the same four shapes the TypeScript core
8
+ defines.
9
+ * :mod:`driverkit.mcp_server`, which turns a tab's manifest into an MCP tool
10
+ list so any MCP client can drive the app without anybody hand-writing a tool
11
+ per feature.
12
+ * :class:`driverkit.TabAuth`, which is how a relay serving more than one
13
+ person learns which person a request is from — and, on the app backend's
14
+ side, the minter that says so. It grants nothing; see
15
+ :mod:`driverkit.auth`.
16
+ * :class:`driverkit.Relay`, the relay itself — the one place a browser tab and
17
+ an agent can both reach. A port of ``packages/driverkit/src/relay/relay.ts``, kept
18
+ behaviour-for-behaviour identical to it, because two relays that differ would
19
+ be worse than either.
20
+ * two ways to run that relay: :func:`driverkit.asgi.relay_asgi` mounts it into
21
+ a FastAPI, Starlette or Django app you already run, which is the deployment
22
+ PROTOCOL.md argues for, and :mod:`driverkit.serve_relay` (the
23
+ ``driverkit-relay`` command) runs it alone when there is no such app yet.
24
+
25
+ ``relay_asgi`` is reached through ``driverkit.asgi`` rather than from here, so
26
+ that importing the client or the MCP server does not drag in :mod:`asyncio` for
27
+ nothing.
28
+
29
+ The wire contract both sides implement is ``PROTOCOL.md`` at the repository
30
+ root. It, and not this code, is the thing to read first.
31
+ """
32
+
33
+ from .auth import AuthError, Principal, TabAuth, mint_anon_credential
34
+ from .client import Driverkit, DriverkitError, ProtocolError, TransportError
35
+ from .relay import Relay, Response, Stream
36
+ from .render import SLOW_MS, render_duration, render_result, render_snapshot
37
+ from .types import (
38
+ APPROVAL_REFUSALS,
39
+ RELAY_REFUSALS,
40
+ UNKNOWN_OUTCOME,
41
+ VERB_KINDS,
42
+ ArgSpec,
43
+ FlowSpec,
44
+ FlowStep,
45
+ Manifest,
46
+ Page,
47
+ Result,
48
+ Row,
49
+ Scalar,
50
+ ScreenSpec,
51
+ Snapshot,
52
+ Tab,
53
+ VerbKind,
54
+ VerbSpec,
55
+ )
56
+
57
+ __version__ = "0.0.0"
58
+
59
+ __all__ = [
60
+ "APPROVAL_REFUSALS",
61
+ "RELAY_REFUSALS",
62
+ "AuthError",
63
+ "Principal",
64
+ "TabAuth",
65
+ "mint_anon_credential",
66
+ "UNKNOWN_OUTCOME",
67
+ "VERB_KINDS",
68
+ "ArgSpec",
69
+ "Driverkit",
70
+ "DriverkitError",
71
+ "FlowSpec",
72
+ "FlowStep",
73
+ "Manifest",
74
+ "Page",
75
+ "ProtocolError",
76
+ "Relay",
77
+ "Response",
78
+ "Result",
79
+ "Row",
80
+ "Scalar",
81
+ "ScreenSpec",
82
+ "Snapshot",
83
+ "Stream",
84
+ "Tab",
85
+ "TransportError",
86
+ "VerbKind",
87
+ "VerbSpec",
88
+ "SLOW_MS",
89
+ "render_duration",
90
+ "render_result",
91
+ "render_snapshot",
92
+ "__version__",
93
+ ]
driverkit/asgi.py ADDED
@@ -0,0 +1,277 @@
1
+ """
2
+ Mount the relay into a server you already run.
3
+
4
+ This is the deployment PROTOCOL.md actually recommends, and it matters more
5
+ than :mod:`driverkit.serve_relay`. The argument for SSE over WebSocket was that
6
+ the relay belongs *inside* an existing server — "write a line, flush" works in
7
+ any HTTP library — and an embedded relay inherits that server's socket, its
8
+ TLS, its auth, its deploy and its supervision. A second process inherits none
9
+ of it and has to be given each one again.
10
+
11
+ from fastapi import FastAPI
12
+ from driverkit.relay import Relay
13
+ from driverkit.asgi import relay_asgi
14
+
15
+ relay = Relay()
16
+ app = FastAPI()
17
+ app.mount("/dk", relay_asgi(relay)) # or mount at "/" — both work
18
+
19
+ Written against the ASGI spec by hand, with no Starlette import, because
20
+ :mod:`driverkit` promises zero runtime dependencies and a relay that pulled in
21
+ a web framework to be embedded in a web framework would be a strange thing to
22
+ ship.
23
+
24
+ TWO THINGS THE SPEC MAKES YOU DO ON PURPOSE:
25
+
26
+ ``Relay.handle`` BLOCKS. A ``POST /dk/tabs/:tab/call`` returns when the tab's
27
+ ``result`` frame arrives, which is the whole design — the HTTP request does not
28
+ start the call, it *is* the call. Calling that from a coroutine directly would
29
+ stall the event loop for up to the relay's deadline and take the host app down
30
+ with it, so every call goes through :func:`asyncio.to_thread`. That is also why
31
+ the relay keeps its own lock rather than assuming one thread.
32
+
33
+ SSE IS STREAMED, not returned. The body goes out as a sequence of
34
+ ``http.response.body`` messages with ``more_body: True`` and no
35
+ ``Content-Length``; a single final message would buffer a stream that never
36
+ ends. The peer hanging up arrives as ``http.disconnect`` on ``receive``, which
37
+ is what closes the stream — and closing it is what evicts the tab from the
38
+ registry and fails its calls in flight as ``tab-went-away`` instead of letting
39
+ each sit out its own deadline.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import asyncio
45
+ from typing import Any, Awaitable, Callable, MutableMapping
46
+
47
+ from .relay import ABORT_BODY, MAX_BODY, Relay, Response, bad_request, too_large
48
+
49
+ __all__ = ["relay_asgi"]
50
+
51
+ Scope = MutableMapping[str, Any]
52
+ Receive = Callable[[], Awaitable[MutableMapping[str, Any]]]
53
+ Send = Callable[[MutableMapping[str, Any]], Awaitable[None]]
54
+ ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
55
+
56
+ _PREFIX = "/dk"
57
+
58
+
59
+ def relay_asgi(
60
+ relay: Relay,
61
+ *,
62
+ fallback: ASGIApp | None = None,
63
+ close_on_shutdown: bool = True,
64
+ ) -> ASGIApp:
65
+ """A plain ASGI 3 application serving the relay's ``/dk/*`` surface.
66
+
67
+ ``fallback`` is called for any request the relay does not own, which lets
68
+ this be mounted at ``/`` in front of an app rather than beside it. With no
69
+ fallback a non-``/dk`` path is a 404 — the same choice the standalone server
70
+ makes, and the reason :meth:`Relay.handle` returns ``None`` instead of
71
+ 404ing by itself: whether an unknown path is an error is the host's
72
+ business, not the relay's.
73
+
74
+ ``close_on_shutdown`` closes the relay on the ASGI ``lifespan.shutdown``
75
+ event, so tabs are hung up and calls in flight fail as ``tab-went-away``
76
+ rather than hanging until the process is killed. Note that most frameworks
77
+ do NOT forward lifespan events into a sub-application mounted with
78
+ ``app.mount(...)``; if you mounted this, call ``relay.close()`` from your
79
+ own shutdown hook.
80
+ """
81
+
82
+ async def app(scope: Scope, receive: Receive, send: Send) -> None:
83
+ kind = scope.get("type")
84
+
85
+ if kind == "lifespan":
86
+ while True:
87
+ message = await receive()
88
+ if message["type"] == "lifespan.startup":
89
+ await send({"type": "lifespan.startup.complete"})
90
+ elif message["type"] == "lifespan.shutdown":
91
+ if close_on_shutdown:
92
+ await asyncio.to_thread(relay.close)
93
+ await send({"type": "lifespan.shutdown.complete"})
94
+ return
95
+
96
+ if kind != "http":
97
+ # No WebSocket surface exists, by design: PROTOCOL.md carries these
98
+ # frames on plain chunked HTTP so that both ends need no library.
99
+ if fallback is not None:
100
+ await fallback(scope, receive, send)
101
+ return
102
+ if kind == "websocket":
103
+ await send({"type": "websocket.close", "code": 1000})
104
+ return
105
+
106
+ path = _path(scope)
107
+ # The trailing slash is required, exactly as in `Relay.handle`, so a
108
+ # host app that owns `/dk` itself keeps it.
109
+ if not path.startswith(_PREFIX + "/"):
110
+ if fallback is not None:
111
+ await fallback(scope, receive, send)
112
+ return
113
+ await _send_response(
114
+ send, bad_request(404, "this app serves /dk/* only", error="not-found")
115
+ )
116
+ return
117
+
118
+ body, over = await _read_body(receive)
119
+ if over:
120
+ # Never handed to the relay. A body this size is a bug or an
121
+ # attack, not a call. The reading of it happens anyway — see
122
+ # `_read_body` — so that the sender gets to read this answer.
123
+ await _send_response(send, too_large())
124
+ return
125
+
126
+ client = scope.get("client")
127
+ peer = client[0] if client else None
128
+ query = (scope.get("query_string") or b"").decode("latin-1")
129
+ # ASGI gives headers as a list of raw byte pairs, repeats included,
130
+ # which is exactly the shape `Relay.handle` wants: a repeated `Cookie`
131
+ # (HTTP/2 splits it) must be joined rather than have one copy win, or a
132
+ # jar with several entries silently loses the credential.
133
+ headers = scope.get("headers") or ()
134
+
135
+ response = await asyncio.to_thread(
136
+ relay.handle, scope.get("method", "GET"), path, query, body, peer, headers
137
+ )
138
+ if response is None:
139
+ # Unreachable in practice: the prefix test above is the same one
140
+ # `handle` applies. Left as a 404 rather than a fallback because the
141
+ # request body has already been consumed by now, and handing a
142
+ # half-read request to the host app is worse than answering it.
143
+ await _send_response(
144
+ send, bad_request(404, "this app serves /dk/* only", error="not-found")
145
+ )
146
+ return
147
+
148
+ if response.stream is None:
149
+ await _send_response(send, response)
150
+ return
151
+ await _send_stream(response, receive, send)
152
+
153
+ return app
154
+
155
+
156
+ def _path(scope: Scope) -> str:
157
+ """The path as the relay's router expects it, ``/dk/...``.
158
+
159
+ A mount rewrites the scope: the framework matches a prefix, moves it to
160
+ ``root_path`` and leaves the remainder in ``path``, so a request for
161
+ ``/dk/tabs`` arrives here as ``path="/tabs"`` with ``root_path="/dk"``.
162
+ Routing on ``path`` alone would then 404 every request when mounted and
163
+ work perfectly when not, which is the kind of bug that gets diagnosed as
164
+ "the relay is broken" for an afternoon. So the two are rejoined when the
165
+ path alone does not already carry the prefix, and both deployments route the
166
+ same way.
167
+ """
168
+ path = scope.get("path") or "/"
169
+ if path.startswith(_PREFIX):
170
+ return path
171
+ root = (scope.get("root_path") or "").rstrip("/")
172
+ if root:
173
+ joined = root + path
174
+ if joined.startswith(_PREFIX):
175
+ return joined
176
+ return path
177
+
178
+
179
+ async def _read_body(receive: Receive) -> tuple[bytes, bool]:
180
+ """The whole request body, or ``(b"", True)`` once it is over the limit.
181
+
182
+ Over the limit it stops BUFFERING but keeps READING, counting the overflow
183
+ instead of keeping it, so memory stays flat however big the upload is and
184
+ the 413 can still be sent once the sender has finished. Answering before
185
+ then is what resets the connection mid-upload, and a sender that takes
186
+ ECONNRESET never reads the status — so it cannot learn why it failed, and
187
+ retries identically.
188
+
189
+ Above :data:`ABORT_BODY` that courtesy is the attack succeeding, so the
190
+ draining stops and the response goes out regardless; the ASGI server owns
191
+ the socket from there.
192
+ """
193
+ chunks: list[bytes] = []
194
+ size = 0
195
+ over = False
196
+ while True:
197
+ message = await receive()
198
+ if message["type"] == "http.disconnect":
199
+ return b"", over
200
+ chunk = message.get("body") or b""
201
+ size += len(chunk)
202
+ if size > MAX_BODY:
203
+ over = True
204
+ chunks.clear()
205
+ elif not over:
206
+ chunks.append(chunk)
207
+ if not message.get("more_body") or size > ABORT_BODY:
208
+ break
209
+ return b"".join(chunks), over
210
+
211
+
212
+ async def _send_response(send: Send, response: Response) -> None:
213
+ headers = [(k.encode("latin-1"), v.encode("latin-1")) for k, v in response.headers]
214
+ headers.append((b"content-length", str(len(response.body)).encode("ascii")))
215
+ await send({"type": "http.response.start", "status": response.status, "headers": headers})
216
+ await send({"type": "http.response.body", "body": response.body, "more_body": False})
217
+
218
+
219
+ async def _send_stream(response: Response, receive: Receive, send: Send) -> None:
220
+ stream = response.stream
221
+ assert stream is not None
222
+ headers = [
223
+ (k.encode("latin-1"), v.encode("latin-1"))
224
+ for k, v in response.headers
225
+ # An ASGI server owns connection management; the spec says not to send
226
+ # hop-by-hop headers and `Connection` is one. The ping comments are what
227
+ # keep this stream alive, not a header.
228
+ if k.lower() != "connection"
229
+ ]
230
+ # No Content-Length on purpose: the length of a stream that never ends is
231
+ # not knowable, and a client that waited for one would hang forever.
232
+ await send({"type": "http.response.start", "status": response.status, "headers": headers})
233
+
234
+ hangup = asyncio.ensure_future(_watch_disconnect(receive, stream))
235
+ chunks = stream.chunks()
236
+ try:
237
+ while True:
238
+ # One blocking `next` per chunk, on a worker thread. The generator
239
+ # waits on a queue with a ping timeout, so this is a real block of
240
+ # up to `ping_s` and must not happen on the event loop.
241
+ chunk = await asyncio.to_thread(next, chunks, None)
242
+ if chunk is None:
243
+ break
244
+ await send({"type": "http.response.body", "body": chunk, "more_body": True})
245
+ except (asyncio.CancelledError, OSError):
246
+ raise
247
+ finally:
248
+ # Closing is what evicts the tab and fails its calls in flight at once,
249
+ # so it must happen on every exit path including a cancelled task.
250
+ stream.close()
251
+ hangup.cancel()
252
+ chunks.close()
253
+ await send({"type": "http.response.body", "body": b"", "more_body": False})
254
+
255
+
256
+ async def _watch_disconnect(receive: Receive, stream: Any) -> None:
257
+ """Close the stream when the peer hangs up.
258
+
259
+ This is the ASGI equivalent of a socket going readable-at-EOF. Without it
260
+ the writer would only learn of a dead peer when its next write failed,
261
+ which on an idle stream is a ping interval away — twenty seconds in which a
262
+ closed tab is still listed by ``/dk/tabs`` and a call to it waits out the
263
+ whole deadline instead of failing at once.
264
+ """
265
+ try:
266
+ while True:
267
+ message = await receive()
268
+ if message["type"] == "http.disconnect":
269
+ stream.close()
270
+ return
271
+ except asyncio.CancelledError:
272
+ raise
273
+ except Exception:
274
+ # A server that refuses further `receive` calls after the response
275
+ # started is within its rights; the write path will notice the peer
276
+ # soon enough.
277
+ stream.close()