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/client.py ADDED
@@ -0,0 +1,413 @@
1
+ """
2
+ driverkit — the client for the relay's agent-facing HTTP surface.
3
+
4
+ Five calls, exactly the five in PROTOCOL.md's "The HTTP surface the agent
5
+ uses". There is deliberately nothing else: the two remaining endpoints
6
+ (``/dk/events``, ``/dk/result``) belong to the tab, and a client that reached
7
+ for them would be impersonating the browser rather than driving it.
8
+
9
+ Synchronous on purpose. A human-driven session makes a handful of calls a
10
+ minute and every call is a round trip the agent is waiting on anyway, so an
11
+ event loop would buy nothing and cost every caller a colour.
12
+
13
+ The error policy is the one decision worth reading before using this:
14
+
15
+ A refusal is a value. A transport failure is an exception.
16
+
17
+ ``call()`` returns ``Result(ok=False, refused=...)`` for every answer the tab
18
+ actually gave — stale, bad-argument, unknown-verb, a business rule saying no.
19
+ Those are outcomes an agent is expected to handle, and the TS core already
20
+ refuses to raise for them (see ``Result`` in types.ts and the test named "a
21
+ refusal is an ordinary result, not an exception"). Raising here would re-break
22
+ that at the language boundary and push every caller into a try/except around
23
+ the app's own business rules. What does raise is the relay being unreachable or
24
+ answering with something that is not a Result — because there is then no
25
+ outcome to report, only a broken pipe.
26
+
27
+ A relay refusal sits between the two and is a third thing: ``no-such-tab``,
28
+ ``tab-went-away`` and ``timeout`` arrive as ordinary ``WireResult`` bodies, so
29
+ they are returned rather than raised, but their ``snapshot`` is absent because
30
+ nothing ran and nobody looked. ``Result.relay_refusal`` names them and
31
+ ``Result.landed`` / ``Result.outcome_unknown`` say what a caller may conclude.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import urllib.error
38
+ import urllib.parse
39
+ import urllib.request
40
+ from typing import Any, Iterator, Mapping
41
+
42
+ from .types import Manifest, Result, Scalar, Snapshot, Tab
43
+
44
+ __all__ = ["Driverkit", "DriverkitError", "TransportError", "ProtocolError"]
45
+
46
+ #: The socket deadline for one request, in seconds.
47
+ #:
48
+ #: **Deliberately above the relay's own 60s call deadline, and that ordering is
49
+ #: the whole point of the number.** The relay answers a tab that went quiet
50
+ #: with a structured ``timeout`` ``WireResult`` — a slug, a hint, and the
51
+ #: PROTOCOL.md rule that the outcome is unknown rather than failed. If this
52
+ #: client gives up first, the caller gets a ``TransportError`` instead: an
53
+ #: unknown outcome with none of that shape, about a call that may well have
54
+ #: committed. The two deadlines were both 15.0, so whichever fired first was a
55
+ #: race, and the bad side of that race is the side with no slug on it.
56
+ #:
57
+ #: 75 is 60 plus fifteen seconds of slack for the relay to notice its own
58
+ #: deadline, build the body and write it.
59
+ DEFAULT_TIMEOUT = 75.0
60
+
61
+
62
+ class DriverkitError(Exception):
63
+ """Base class, so a caller can catch everything this module raises."""
64
+
65
+
66
+ class TransportError(DriverkitError):
67
+ """The relay could not be reached, or answered with an HTTP error that
68
+ carried no Result."""
69
+
70
+
71
+ class ProtocolError(DriverkitError):
72
+ """The relay answered, but not with something this client can read:
73
+ malformed JSON, or JSON of the wrong shape."""
74
+
75
+
76
+ class Driverkit:
77
+ """A client for one relay.
78
+
79
+ ``relay_url`` is the relay's base URL (``http://127.0.0.1:7777``). The
80
+ ``/dk`` prefix belongs to the protocol, not the deployment, so it is added
81
+ here and a caller never writes it.
82
+
83
+ ``token`` is a tab token, minted by the app's backend, naming the person
84
+ whose tabs this client may see. It is sent as ``Authorization: Bearer`` and
85
+ it is what makes ``tabs()`` list that person's tabs and nobody else's. A
86
+ relay with no auth configured — the unconfigured loopback one — needs none,
87
+ which is why this is optional and why omitting it is the dev-loop path.
88
+
89
+ A token minted with a ``tab`` claim narrows this client to that one tab:
90
+ ``tabs()`` then lists only it and every other call refuses anything else as
91
+ ``no-such-tab``. That is the right credential for an MCP server configured
92
+ to drive one known tab, and it is free there, because the tab id is already
93
+ in its configuration.
94
+
95
+ A token expires. This client does not refresh one — it has no way to mint —
96
+ so a long-lived process should pass a fresh ``Driverkit`` or set
97
+ ``client.token`` when its own session management says to. A lapsed token
98
+ arrives as :class:`TransportError` on an HTTP 401, which is a transport
99
+ failure and not a refusal: nothing was asked of any tab.
100
+
101
+ ``headers`` is anything else the app in front of the relay requires.
102
+ """
103
+
104
+ def __init__(
105
+ self,
106
+ relay_url: str,
107
+ *,
108
+ timeout: float = DEFAULT_TIMEOUT,
109
+ token: str | None = None,
110
+ headers: Mapping[str, str] | None = None,
111
+ ) -> None:
112
+ self.relay_url = relay_url.rstrip("/")
113
+ self.timeout = timeout
114
+ self.token = token
115
+ self.headers = dict(headers or {})
116
+
117
+ # ---- the four endpoints ------------------------------------------------
118
+
119
+ def tabs(self) -> list[Tab]:
120
+ """``GET /dk/tabs`` — the connected tabs.
121
+
122
+ The specified shape is the ``{"tabs": [...]}`` envelope, so that a
123
+ later field can be added beside ``tabs`` without breaking a parser. A
124
+ bare list is also accepted, for relays written against the earlier
125
+ prose, which named this endpoint's columns but not its envelope.
126
+ """
127
+ body = self._get("/dk/tabs")
128
+ if isinstance(body, Mapping):
129
+ body = body.get("tabs", [])
130
+ if not isinstance(body, list):
131
+ raise ProtocolError(f"GET /dk/tabs: expected a list of tabs, got {type(body).__name__}")
132
+ return [Tab.from_dict(t) for t in body if isinstance(t, Mapping)]
133
+
134
+ def manifest(self, tab: str) -> Manifest:
135
+ """``GET /dk/tabs/:tab/manifest`` — the static half. Cache it; the
136
+ ``version`` field is how you find out you may not any more."""
137
+ body = self._get(f"/dk/tabs/{urllib.parse.quote(tab, safe='')}/manifest")
138
+ if not isinstance(body, Mapping) or "verbs" not in body:
139
+ raise ProtocolError("manifest response is not a Manifest")
140
+ return Manifest.from_dict(body)
141
+
142
+ def snapshot(self, tab: str) -> Snapshot:
143
+ """``GET /dk/tabs/:tab/snapshot`` — the dynamic half. Never cache it:
144
+ a person at the keyboard can move the screen between any two calls."""
145
+ body = self._get(f"/dk/tabs/{urllib.parse.quote(tab, safe='')}/snapshot")
146
+ if not isinstance(body, Mapping) or "rev" not in body:
147
+ raise ProtocolError("snapshot response is not a Snapshot")
148
+ return Snapshot.from_dict(body)
149
+
150
+ def watch(self, tab: str, *, timeout: float | None = None) -> Iterator[Snapshot]:
151
+ """``GET /dk/tabs/:tab/watch`` — snapshots as they happen, as an
152
+ iterator that blocks between them.
153
+
154
+ This is the agent's end of the ``snapshot`` push frame. Without it that
155
+ frame reaches the relay and stops there, and the shared-presence case
156
+ it exists for — a human and an agent watching one screen — is
157
+ unreachable through a request/response surface. Polling ``snapshot()``
158
+ is the lower-effort alternative and is right for a script that acts and
159
+ stops; it is wrong for an agent sitting beside a person, which would
160
+ have to poll fast to feel live and pay for every poll.
161
+
162
+ ::
163
+
164
+ for screen in dk.watch(tab):
165
+ print(screen.where, screen.rev) # the person just moved
166
+
167
+ ``timeout`` is the socket read timeout and defaults to **None**, not to
168
+ the client's usual one. A live stream is idle most of the time by
169
+ design, so the ordinary timeout would tear it down between two of the
170
+ person's clicks. The relay's 20s ping comments are what prove it is
171
+ still there; pass a timeout comfortably above that interval if you want
172
+ a dead-connection deadline, and expect ``TransportError``.
173
+
174
+ The iterator ends when the relay closes the stream. It does not
175
+ reconnect: an agent that reconnects silently can be watching a screen
176
+ for minutes after the tab it cared about went away, and "the stream
177
+ ended" is information its caller needs.
178
+ """
179
+ request = urllib.request.Request(
180
+ self.relay_url + f"/dk/tabs/{urllib.parse.quote(tab, safe='')}/watch",
181
+ method="GET",
182
+ )
183
+ request.add_header("Accept", "text/event-stream")
184
+ # No caching proxy should ever hold a frame of this back.
185
+ request.add_header("Cache-Control", "no-cache")
186
+ self._authorize(request)
187
+ for key, value in self.headers.items():
188
+ request.add_header(key, value)
189
+
190
+ try:
191
+ response = urllib.request.urlopen(request, timeout=timeout)
192
+ except urllib.error.HTTPError as err:
193
+ with err:
194
+ err.read()
195
+ raise TransportError(
196
+ f"GET {request.full_url}: HTTP {err.code} {err.reason}"
197
+ ) from err
198
+ except (urllib.error.URLError, TimeoutError, OSError) as err:
199
+ raise TransportError(f"{request.full_url}: {err}") from err
200
+
201
+ with response:
202
+ try:
203
+ for frame in _sse_frames(response):
204
+ snapshot = _snapshot_frame(frame)
205
+ if snapshot is not None:
206
+ yield snapshot
207
+ except (TimeoutError, OSError) as err:
208
+ raise TransportError(f"{request.full_url}: the stream broke: {err}") from err
209
+
210
+ def call(
211
+ self,
212
+ tab: str,
213
+ name: str,
214
+ args: Mapping[str, Scalar] | None = None,
215
+ rev: int | None = None,
216
+ screen: str | None = None,
217
+ plan: str | None = None,
218
+ ) -> Result:
219
+ """``POST /dk/tabs/:tab/call`` — run a verb, get the screen back.
220
+
221
+ ``rev`` is your claim about what you were looking at. Pass the ``rev``
222
+ from the snapshot you read and a call made against a screen that has
223
+ since moved comes back refused as ``stale`` instead of landing on a row
224
+ you never saw. Omitting it opts out of that check, which is right for a
225
+ verb whose effect does not depend on what is on screen (``scroll``) and
226
+ wrong for one that names a row.
227
+
228
+ ``screen`` is the other half of that claim and is checked first: the
229
+ ``Snapshot.screen`` you believed you were on. A paging call sent with
230
+ no ``rev`` once landed on a screen the agent had never seen, paged a
231
+ different company's contact list and answered ``ok`` — "you are
232
+ somewhere else" is a better answer than "the number moved", and the two
233
+ have different fixes. Comes back refused as ``wrong-screen``, naming
234
+ both screens. Omitting it opts out, like ``rev``.
235
+
236
+ ``plan`` is the third claim and the one that is NOT optional where it
237
+ applies: the token a ``describe`` returned in ``Result.plan``, passed
238
+ back to a commit whose manifest entry says ``consumes: "plan"``. The
239
+ other two may be omitted to skip their checks, because an agent that
240
+ makes no claim about what it was looking at has at least made no false
241
+ one. A commit that could be called without a plan would be a commit
242
+ whose count guarantee is advisory, so the core refuses the bare call as
243
+ ``stale-plan`` — and refuses a token taken before the selection moved,
244
+ naming both counts.
245
+
246
+ Returns a Result either way. Only the relay being unreachable, or
247
+ answering with something that is not a Result, raises.
248
+
249
+ The Result may carry :attr:`driverkit.types.Result.took_ms`: how long
250
+ the TAB's own work took, with any person's time already taken out of
251
+ it. It is the only honest duration this side has — the one figure this
252
+ client could measure for itself is the whole round trip, which is the
253
+ network plus the tab's work plus any question the page put to
254
+ somebody — and it is ``None`` whenever the tab did not say, which means
255
+ UNKNOWN and never zero.
256
+ """
257
+ payload: dict[str, Any] = {"name": name, "args": dict(args or {})}
258
+ if rev is not None:
259
+ # Sent only when asked for. An explicit `"rev": null` would be a
260
+ # claim about the screen, and the claim we want to make is none.
261
+ payload["rev"] = rev
262
+ if screen:
263
+ # Same rule, and an empty string is not a claim either: it is not
264
+ # the id of any screen, so sending it would ask the app to refuse a
265
+ # call over a field the caller left blank.
266
+ payload["screen"] = screen
267
+ if plan:
268
+ # Forwarded as the opaque string it is. This client does not parse
269
+ # it, does not check it and could not: the core that minted it is
270
+ # the only thing that knows what it binds, and a second opinion
271
+ # about staleness on this side would be a second set of rules.
272
+ payload["plan"] = plan
273
+
274
+ body = self._post(f"/dk/tabs/{urllib.parse.quote(tab, safe='')}/call", payload)
275
+ if not isinstance(body, Mapping) or "ok" not in body:
276
+ raise ProtocolError(f"call response is not a Result: {body!r}")
277
+ return Result.from_dict(body)
278
+
279
+ # ---- transport --------------------------------------------------------
280
+
281
+ def _authorize(self, request: urllib.request.Request) -> None:
282
+ """Attach the bearer token, if there is one.
283
+
284
+ Added before ``headers`` so an explicit ``Authorization`` in
285
+ ``headers=`` wins: a caller spelling the header out by hand has a
286
+ reason, and silently overriding it would be the library disagreeing
287
+ with the person who configured it. Never logged, never put in a URL —
288
+ ``urllib`` does not log, and the query string is where a token goes to
289
+ be written into somebody's access log.
290
+ """
291
+ if self.token:
292
+ request.add_header("Authorization", f"Bearer {self.token}")
293
+
294
+ def _get(self, path: str) -> Any:
295
+ return self._request(urllib.request.Request(self.relay_url + path, method="GET"))
296
+
297
+ def _post(self, path: str, payload: Mapping[str, Any]) -> Any:
298
+ request = urllib.request.Request(
299
+ self.relay_url + path,
300
+ data=json.dumps(payload).encode("utf-8"),
301
+ method="POST",
302
+ )
303
+ request.add_header("Content-Type", "application/json")
304
+ return self._request(request)
305
+
306
+ def _request(self, request: urllib.request.Request) -> Any:
307
+ request.add_header("Accept", "application/json")
308
+ self._authorize(request)
309
+ for key, value in self.headers.items():
310
+ request.add_header(key, value)
311
+ try:
312
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
313
+ raw = response.read()
314
+ except urllib.error.HTTPError as err:
315
+ # A non-2xx status means the request never produced a WireResult at
316
+ # all — malformed JSON, an unroutable path, a broken relay. The
317
+ # status contract is explicit that a refusal arrives as 200 with
318
+ # `ok: false`, and that a relay must not use 4xx to mean "the app
319
+ # said no". So this is a transport failure even when the body looks
320
+ # like a Result: honouring such a body would quietly bless the
321
+ # conflation the contract forbids, and the two want opposite
322
+ # handling — retry elsewhere versus rephrase and retry.
323
+ with err:
324
+ detail = _first_line(err.read())
325
+ raise TransportError(
326
+ f"{request.get_method()} {request.full_url}: HTTP {err.code} {err.reason}"
327
+ + (f": {detail}" if detail else "")
328
+ ) from err
329
+ except urllib.error.URLError as err:
330
+ raise TransportError(f"{request.full_url} is unreachable: {err.reason}") from err
331
+ except TimeoutError as err:
332
+ raise TransportError(f"{request.full_url} timed out after {self.timeout}s") from err
333
+ except OSError as err: # a connection dropped mid-read
334
+ raise TransportError(f"{request.full_url}: {err}") from err
335
+
336
+ try:
337
+ return json.loads(raw)
338
+ except (ValueError, UnicodeDecodeError) as err:
339
+ raise ProtocolError(
340
+ f"{request.full_url} returned {len(raw)} bytes that are not JSON"
341
+ ) from err
342
+
343
+
344
+ def _sse_frames(stream: Any) -> Iterator[dict[str, str]]:
345
+ """Parse an SSE body into one dict of fields per frame.
346
+
347
+ Small enough to hand-roll, and hand-rolled for the same reason the relay
348
+ chose SSE over WebSocket: this is plain chunked HTTP with ``field: value``
349
+ lines and a blank line between frames, so the whole parser is this
350
+ function. Three details are the ones that bite:
351
+
352
+ * A line beginning with ``:`` is a comment. That is what the relay's 20s
353
+ keepalive is, and treating it as data would deliver a junk frame every
354
+ twenty seconds.
355
+ * ``data:`` may appear more than once in a frame and the values join with
356
+ newlines. JSON payloads rarely need it, but a parser that keeps only the
357
+ last line silently truncates the day one does.
358
+ * An unterminated final frame is dropped rather than delivered. A
359
+ half-written snapshot is not a screen.
360
+ """
361
+ fields: dict[str, str] = {}
362
+ data: list[str] = []
363
+ for raw_line in stream:
364
+ line = raw_line.decode("utf-8", "replace").rstrip("\r\n")
365
+ if line.startswith(":"):
366
+ continue
367
+ if line == "":
368
+ if data or fields:
369
+ fields["data"] = "\n".join(data)
370
+ yield fields
371
+ fields, data = {}, []
372
+ continue
373
+ name, _, value = line.partition(":")
374
+ value = value[1:] if value.startswith(" ") else value
375
+ if name == "data":
376
+ data.append(value)
377
+ else:
378
+ fields[name] = value
379
+
380
+
381
+ def _snapshot_frame(frame: Mapping[str, str]) -> Snapshot | None:
382
+ """A ``snapshot`` frame as a Snapshot, or None for anything else.
383
+
384
+ Both the wrapped shape from the frames section, ``{"t": "snapshot",
385
+ "snapshot": {...}}``, and a bare snapshot object are accepted. A frame that
386
+ is not JSON, or is some other ``t``, is skipped rather than raised on:
387
+ PROTOCOL.md says unknown frames are ignored so a new one can be added
388
+ without a version bump, and a watcher that dies on an unrecognised frame
389
+ turns that additive promise into an outage.
390
+ """
391
+ payload = _loads_or_none(frame.get("data", ""))
392
+ if not isinstance(payload, Mapping):
393
+ return None
394
+ if payload.get("t") == "snapshot" or "snapshot" in payload:
395
+ inner = payload.get("snapshot")
396
+ return Snapshot.from_dict(inner) if isinstance(inner, Mapping) else None
397
+ if "rev" in payload and "where" in payload:
398
+ return Snapshot.from_dict(payload)
399
+ return None
400
+
401
+
402
+ def _loads_or_none(raw: str) -> Any:
403
+ try:
404
+ return json.loads(raw)
405
+ except (ValueError, UnicodeDecodeError):
406
+ return None
407
+
408
+
409
+ def _first_line(raw: bytes, limit: int = 200) -> str:
410
+ """A scrap of an error body, for the exception message. Truncated, because
411
+ a relay that fell over may answer with a whole HTML error page."""
412
+ text = raw.decode("utf-8", "replace").strip().splitlines()
413
+ return text[0][:limit] if text else ""