lustro-cli 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.
Files changed (60) hide show
  1. lustro_cli/__init__.py +29 -0
  2. lustro_cli/cli.py +2460 -0
  3. lustro_cli/client.py +434 -0
  4. lustro_cli/discovery.py +1033 -0
  5. lustro_cli/exitcodes.py +25 -0
  6. lustro_cli/mcp.py +867 -0
  7. lustro_cli/wire/__init__.py +62 -0
  8. lustro_cli/wire/_schema.json +97 -0
  9. lustro_cli/wire/cursor-envelope.schema.json +28 -0
  10. lustro_cli/wire/error-envelope.schema.json +46 -0
  11. lustro_cli/wire/golden/cursor-delta.json +91 -0
  12. lustro_cli/wire/golden/cursor-reset.json +65 -0
  13. lustro_cli/wire/golden/cursor-unchanged.json +15 -0
  14. lustro_cli/wire/golden/error-envelope.json +7 -0
  15. lustro_cli/wire/golden/export-har-websocket.json +148 -0
  16. lustro_cli/wire/golden/export-har.json +359 -0
  17. lustro_cli/wire/golden/logs-delta.json +44 -0
  18. lustro_cli/wire/golden/logs-reset.json +73 -0
  19. lustro_cli/wire/golden/logs-unchanged.json +9 -0
  20. lustro_cli/wire/golden/meta.json +12 -0
  21. lustro_cli/wire/golden/prefs-delta.json +58 -0
  22. lustro_cli/wire/golden/prefs-files.json +64 -0
  23. lustro_cli/wire/golden/prefs-reset.json +58 -0
  24. lustro_cli/wire/golden/prefs-unchanged.json +4 -0
  25. lustro_cli/wire/golden/rules-list.json +44 -0
  26. lustro_cli/wire/golden/screen-tree-views.json +596 -0
  27. lustro_cli/wire/golden/screen-tree.json +689 -0
  28. lustro_cli/wire/golden/send-result.json +7 -0
  29. lustro_cli/wire/golden/senders-list.json +6 -0
  30. lustro_cli/wire/golden/sqlite-databases.json +37 -0
  31. lustro_cli/wire/golden/sqlite-exec.json +4 -0
  32. lustro_cli/wire/golden/sqlite-query.json +109 -0
  33. lustro_cli/wire/golden/sqlite-rows.json +109 -0
  34. lustro_cli/wire/golden/sqlite-schema.json +98 -0
  35. lustro_cli/wire/golden/sqlite-tables.json +57 -0
  36. lustro_cli/wire/golden/stream-delta.json +48 -0
  37. lustro_cli/wire/golden/stream-reset.json +66 -0
  38. lustro_cli/wire/golden/stream-unchanged.json +4 -0
  39. lustro_cli/wire/golden/transaction-image.json +43 -0
  40. lustro_cli/wire/golden/transaction.json +41 -0
  41. lustro_cli/wire/golden/websocket.json +37 -0
  42. lustro_cli/wire/golden/websockets-reset.json +89 -0
  43. lustro_cli/wire/golden/work-events.json +152 -0
  44. lustro_cli/wire/golden/work-item.json +118 -0
  45. lustro_cli/wire/golden/work-items.json +129 -0
  46. lustro_cli/wire/golden/work-metrics.json +40 -0
  47. lustro_cli/wire/logs.openapi.json +622 -0
  48. lustro_cli/wire/meta.schema.json +47 -0
  49. lustro_cli/wire/network.openapi.json +2458 -0
  50. lustro_cli/wire/pagination.schema.json +20 -0
  51. lustro_cli/wire/prefs.openapi.json +699 -0
  52. lustro_cli/wire/screen.openapi.json +512 -0
  53. lustro_cli/wire/sqlite.openapi.json +1233 -0
  54. lustro_cli/wire/stream-envelope.schema.json +33 -0
  55. lustro_cli/wire/sync.py +80 -0
  56. lustro_cli/wire/work.openapi.json +1188 -0
  57. lustro_cli-0.1.0.dist-info/METADATA +585 -0
  58. lustro_cli-0.1.0.dist-info/RECORD +60 -0
  59. lustro_cli-0.1.0.dist-info/WHEEL +4 -0
  60. lustro_cli-0.1.0.dist-info/entry_points.txt +3 -0
lustro_cli/client.py ADDED
@@ -0,0 +1,434 @@
1
+ """HTTP client for the Lustro wire protocol.
2
+
3
+ Stdlib only (``urllib.request``/``json``). The client adds the base URL and a
4
+ ``Authorization: Bearer <token>`` header, encodes/decodes JSON, and raises a
5
+ typed :class:`LustroError` parsed from the uniform error envelope
6
+ ``{error, message, code?, field?, hint?}``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import http.client
12
+ import json
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple, Union
18
+
19
+ # The shared error-envelope status -> machine "error" type map, mirrored from the
20
+ # wire protocol (docs/AGENTS.md "Failure modes" / error-envelope.schema.json). Used as
21
+ # a fallback when a non-JSON / non-enveloped HTTP error comes back.
22
+ _STATUS_ERROR_TYPES = {
23
+ 400: "bad_request",
24
+ 401: "unauthorized",
25
+ 403: "forbidden",
26
+ 404: "not_found",
27
+ 405: "method_not_allowed",
28
+ 409: "conflict",
29
+ 413: "payload_too_large",
30
+ 422: "unprocessable_entity",
31
+ 429: "too_many_requests",
32
+ 500: "internal_error",
33
+ 503: "unavailable",
34
+ 504: "timeout",
35
+ }
36
+
37
+
38
+ class LustroError(Exception):
39
+ """A typed error parsed from the Lustro error envelope (or a transport failure).
40
+
41
+ Attributes mirror the wire ``{error, message, code?, field?, hint?}`` shape,
42
+ plus the HTTP ``status`` when one is available.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ error: str,
48
+ message: str,
49
+ *,
50
+ status: Optional[int] = None,
51
+ code: Optional[str] = None,
52
+ field: Optional[str] = None,
53
+ hint: Optional[str] = None,
54
+ ) -> None:
55
+ super().__init__(message or error)
56
+ self.error = error
57
+ self.message = message
58
+ self.status = status
59
+ self.code = code
60
+ self.field = field
61
+ self.hint = hint
62
+
63
+ @classmethod
64
+ def from_envelope(cls, body: Mapping[str, Any], *, status: Optional[int] = None) -> "LustroError":
65
+ """Build from a decoded error envelope object."""
66
+ return cls(
67
+ error=str(body.get("error", "error")),
68
+ message=str(body.get("message", "")),
69
+ status=status,
70
+ code=_opt_str(body.get("code")),
71
+ field=_opt_str(body.get("field")),
72
+ hint=_opt_str(body.get("hint")),
73
+ )
74
+
75
+ def __str__(self) -> str:
76
+ parts = []
77
+ if self.status is not None:
78
+ parts.append(str(self.status))
79
+ parts.append(self.error)
80
+ line = " ".join(parts)
81
+ if self.message:
82
+ line += ": " + self.message
83
+ details = []
84
+ if self.code:
85
+ details.append("code: {}".format(self.code))
86
+ if self.field:
87
+ details.append("field: {}".format(self.field))
88
+ if details:
89
+ line += " ({})".format(", ".join(details))
90
+ if self.hint:
91
+ line += "\n hint: " + self.hint
92
+ return line
93
+
94
+
95
+ def _opt_str(value: Any) -> Optional[str]:
96
+ return None if value is None else str(value)
97
+
98
+
99
+ class RawBody(NamedTuple):
100
+ """A response body as the server sent it, for routes that don't answer JSON."""
101
+
102
+ data: bytes
103
+ content_type: Optional[str]
104
+
105
+
106
+ # Query parameters: a mapping, or a sequence of (key, value) pairs, which can
107
+ # repeat a key. A None value in a mapping leaves the key out.
108
+ Params = Union[Mapping[str, Any], Sequence[Tuple[str, Any]]]
109
+
110
+
111
+ # The server names each query parameter that the route does not declare in this
112
+ # header, as ``unknown query parameter "<name>"``, because the route ignores it.
113
+ # More than one is a comma-separated list.
114
+ WARNING_HEADER = "Lustro-Warning"
115
+
116
+
117
+ def split_warnings(value: str) -> List[str]:
118
+ """The warnings in one ``Lustro-Warning`` value: split at the commas that are
119
+ not in a quoted string, in which a backslash escapes the next character."""
120
+ warnings: List[str] = []
121
+ current: List[str] = []
122
+ quoted = escaped = False
123
+ for char in value:
124
+ if escaped:
125
+ escaped = False
126
+ elif quoted and char == "\\":
127
+ escaped = True
128
+ elif char == '"':
129
+ quoted = not quoted
130
+ elif char == "," and not quoted:
131
+ warnings.append("".join(current).strip())
132
+ current = []
133
+ continue
134
+ current.append(char)
135
+ warnings.append("".join(current).strip())
136
+ return [warning for warning in warnings if warning]
137
+
138
+
139
+ # How long the check of a ``guard`` holds. A command that sends more than one request
140
+ # checks again before a request after this time: the app's server closes when the app
141
+ # goes to the background, and another app can then bind the port.
142
+ GUARD_SECONDS = 1.0
143
+
144
+
145
+ # urllib honours http_proxy, HTTPS_PROXY, and the system's proxy settings. The
146
+ # server is an adb forward on this machine, which a proxy can't reach, and the
147
+ # token must not leave it, so requests never go through one.
148
+ _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
149
+
150
+
151
+ class LustroClient:
152
+ """Minimal JSON-over-HTTP client for ``/api/v1/*`` routes.
153
+
154
+ :param base_url: e.g. ``http://127.0.0.1:8080`` (no trailing ``/api/v1``).
155
+ :param token: bearer token; sent as ``Authorization: Bearer <token>``.
156
+ :param timeout: per-request socket timeout in seconds.
157
+ :param refresh_token: called once when the server answers 401; a token it
158
+ returns that differs from ``token`` replaces it, and the request is sent
159
+ again. For a token that discovery found, which can be stale.
160
+ :param on_warning: called with each warning in a ``Lustro-Warning`` response
161
+ header, such as ``unknown query parameter "uniqueName"``, also for an
162
+ error response.
163
+ :param guard: called before the first request, and again before a request when
164
+ its last check is older than ``GUARD_SECONDS`` or a connection failed since:
165
+ it raises a :class:`LustroError` when the server on the port must not get
166
+ the token, and can return the ``time.monotonic()`` of what it checked. For a
167
+ token that discovery found, which goes only to the server of the app that
168
+ owns it.
169
+ """
170
+
171
+ def __init__(
172
+ self,
173
+ base_url: str,
174
+ token: Optional[str] = None,
175
+ timeout: float = 30.0,
176
+ refresh_token: Optional[Callable[[], Optional[str]]] = None,
177
+ on_warning: Optional[Callable[[str], None]] = None,
178
+ guard: Optional[Callable[[], Optional[float]]] = None,
179
+ ) -> None:
180
+ self.base_url = base_url.rstrip("/")
181
+ self.token = token
182
+ self.timeout = timeout
183
+ self._refresh_token = refresh_token
184
+ self.on_warning = on_warning
185
+ self._guard = guard
186
+ self._guarded_at: Optional[float] = None
187
+
188
+ # ── request plumbing ──────────────────────────────────────────────────────
189
+
190
+ def _url(self, path: str, params: Optional[Params] = None) -> str:
191
+ if not path.startswith("/"):
192
+ path = "/" + path
193
+ url = self.base_url + path
194
+ if params:
195
+ if isinstance(params, Mapping):
196
+ # Drop None values so callers can pass optional params uniformly.
197
+ pairs: List[Tuple[str, Any]] = [(k, v) for k, v in params.items() if v is not None]
198
+ else:
199
+ pairs = list(params)
200
+ if pairs:
201
+ url += ("&" if "?" in path else "?") + urllib.parse.urlencode(pairs)
202
+ return url
203
+
204
+ def _headers(self, accept: str) -> Dict[str, str]:
205
+ headers = {"Accept": accept}
206
+ if self.token:
207
+ headers["Authorization"] = "Bearer " + self.token
208
+ return headers
209
+
210
+ def request(
211
+ self,
212
+ method: str,
213
+ path: str,
214
+ *,
215
+ params: Optional[Mapping[str, Any]] = None,
216
+ json_body: Any = None,
217
+ ) -> Any:
218
+ """Perform a request and return the decoded JSON body.
219
+
220
+ Raises :class:`LustroError` on any non-2xx response (parsing the error
221
+ envelope when present) or on a transport failure.
222
+ """
223
+ raw, _ = self._send(method, path, params=params, json_body=json_body, accept="application/json")
224
+ return _decode_json(raw)
225
+
226
+ def get_raw(self, path: str, params: Optional[Mapping[str, Any]] = None) -> RawBody:
227
+ """GET a route whose body isn't JSON, such as a captured body, and return
228
+ it undecoded with its ``Content-Type``. Errors raise :class:`LustroError`
229
+ as :meth:`request` does, since they still use the error envelope."""
230
+ return self.request_raw("GET", path, params=params)
231
+
232
+ def request_raw(
233
+ self,
234
+ method: str,
235
+ path: str,
236
+ *,
237
+ params: Optional[Params] = None,
238
+ json_body: Any = None,
239
+ ) -> RawBody:
240
+ """Perform any request and return the body undecoded, with its
241
+ ``Content-Type``. Errors raise :class:`LustroError` as :meth:`request` does."""
242
+ data, content_type = self._send(method, path, params=params, json_body=json_body, accept="*/*")
243
+ return RawBody(data, content_type)
244
+
245
+ def _send(
246
+ self,
247
+ method: str,
248
+ path: str,
249
+ *,
250
+ params: Optional[Params],
251
+ json_body: Any,
252
+ accept: str,
253
+ ) -> Tuple[bytes, Optional[str]]:
254
+ url = self._url(path, params)
255
+ data: Optional[bytes] = None
256
+ if json_body is not None:
257
+ data = json.dumps(json_body).encode("utf-8")
258
+ self._check_server()
259
+ try:
260
+ try:
261
+ return self._open(url, data, method, accept)
262
+ except urllib.error.HTTPError as exc:
263
+ if exc.code != 401 or not self._take_fresh_token():
264
+ raise
265
+ return self._open(url, data, method, accept)
266
+ except urllib.error.HTTPError as exc: # non-2xx
267
+ self._warn(exc.headers)
268
+ raise _error_from_http(exc) from None
269
+ except urllib.error.URLError as exc:
270
+ self._guarded_at = None
271
+ raise _connection_failed(url, getattr(exc, "reason", exc)) from None
272
+ except (http.client.HTTPException, OSError) as exc:
273
+ # A connection that closes before the response raises these, not
274
+ # URLError. adb forward does that while nothing listens on the device
275
+ # port, for example while the app is in the background.
276
+ self._guarded_at = None
277
+ raise _connection_failed(url, exc) from None
278
+
279
+ def _check_server(self) -> None:
280
+ if self._guard is None:
281
+ return
282
+ if self._guarded_at is not None and time.monotonic() - self._guarded_at < GUARD_SECONDS:
283
+ return
284
+ checked_at = self._guard()
285
+ self._guarded_at = time.monotonic() if checked_at is None else checked_at
286
+
287
+ def _open(self, url: str, data: Optional[bytes], method: str, accept: str) -> Tuple[bytes, Optional[str]]:
288
+ headers = self._headers(accept)
289
+ if data is not None:
290
+ headers["Content-Type"] = "application/json"
291
+ req = urllib.request.Request(url, data=data, headers=headers, method=method.upper())
292
+ with _OPENER.open(req, timeout=self.timeout) as resp:
293
+ self._warn(resp.headers)
294
+ return resp.read(), resp.headers.get("Content-Type")
295
+
296
+ def _warn(self, headers: Any) -> None:
297
+ if self.on_warning is None or headers is None:
298
+ return
299
+ for value in headers.get_all(WARNING_HEADER) or []:
300
+ for warning in split_warnings(value):
301
+ self.on_warning(warning)
302
+
303
+ def _take_fresh_token(self) -> bool:
304
+ """Asks ``refresh_token`` once for a token that differs from the one sent."""
305
+ refresh, self._refresh_token = self._refresh_token, None
306
+ fresh = refresh() if refresh is not None else None
307
+ if not fresh or fresh == self.token:
308
+ return False
309
+ self.token = fresh
310
+ return True
311
+
312
+ # ── convenience verbs ─────────────────────────────────────────────────────
313
+
314
+ def get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
315
+ return self.request("GET", path, params=params)
316
+
317
+ def post(self, path: str, json_body: Any = None, params: Optional[Mapping[str, Any]] = None) -> Any:
318
+ return self.request("POST", path, params=params, json_body=json_body)
319
+
320
+
321
+ class CursorState:
322
+ """Client-side state machine for the cursor-polling envelope.
323
+
324
+ Mirrors the wire contract (docs/AGENTS.md "Live polling cursor" /
325
+ cursor-envelope.schema.json) and the server's reference JS implementation:
326
+
327
+ - ``reset`` → replace the whole list with ``items`` (or empty).
328
+ - ``delta`` → ``items`` (when present) are the authoritative current
329
+ list; absent items means no list mutation.
330
+ - ``unchanged`` → no change; items are ignored even if present.
331
+ - any UNKNOWN/missing status → treated as ``reset``.
332
+
333
+ The returned ``cursor`` is persisted (when present) and echoed on the next
334
+ poll. ``state`` (paused/overwriteMode/throttleDelayMs) is captured verbatim.
335
+ """
336
+
337
+ def __init__(self) -> None:
338
+ self.cursor: Optional[str] = None
339
+ self.items: list = []
340
+ self.state: Dict[str, Any] = {}
341
+ self.last_status: Optional[str] = None
342
+
343
+ def apply(self, data: Optional[Mapping[str, Any]]) -> list:
344
+ """Apply one poll response; return the list of items considered *new*.
345
+
346
+ For ``reset``/``delta`` the "new" items are those not previously seen by
347
+ id (when items carry an ``id``), so a poll loop can print only fresh
348
+ rows. For ``unchanged`` the new list is empty.
349
+ """
350
+ if not data:
351
+ return []
352
+
353
+ status = data.get("status")
354
+ self.last_status = status
355
+
356
+ if "state" in data and isinstance(data["state"], dict):
357
+ self.state = dict(data["state"])
358
+
359
+ previous_ids = {
360
+ item.get("id")
361
+ for item in self.items
362
+ if isinstance(item, dict) and item.get("id") is not None
363
+ }
364
+
365
+ new_items: list = []
366
+ if status == "unchanged":
367
+ # No list mutation; ignore any items defensively.
368
+ pass
369
+ elif status == "delta":
370
+ if data.get("items") is not None:
371
+ self.items = list(data["items"])
372
+ new_items = self._diff(previous_ids)
373
+ else:
374
+ # 'reset' OR any unknown/missing status → replace the whole list.
375
+ self.items = list(data.get("items") or [])
376
+ new_items = self._diff(previous_ids)
377
+
378
+ if data.get("cursor") is not None:
379
+ self.cursor = data["cursor"]
380
+
381
+ return new_items
382
+
383
+ def _diff(self, previous_ids: set) -> list:
384
+ fresh = []
385
+ for item in self.items:
386
+ if isinstance(item, dict) and item.get("id") is not None:
387
+ if item.get("id") not in previous_ids:
388
+ fresh.append(item)
389
+ else:
390
+ fresh.append(item)
391
+ return fresh
392
+
393
+
394
+ def _connection_failed(url: str, reason: Any) -> LustroError:
395
+ return LustroError(
396
+ "connection_failed",
397
+ "could not reach {}: {}".format(url, reason),
398
+ hint=(
399
+ "Is the app running and foregrounded? Without --port, the CLI "
400
+ "connects through an adb forward to the app's port on the device. "
401
+ "With --port, it connects to that local port and makes no forward. "
402
+ "The `LustroToken` log line gives the live endpoint."
403
+ ),
404
+ )
405
+
406
+
407
+ def _decode_json(raw: bytes) -> Any:
408
+ if not raw:
409
+ return None
410
+ try:
411
+ return json.loads(raw.decode("utf-8"))
412
+ except (ValueError, UnicodeDecodeError) as exc:
413
+ raise LustroError("invalid_response", "server returned non-JSON body: {}".format(exc)) from None
414
+
415
+
416
+ def _error_from_http(exc: "urllib.error.HTTPError") -> LustroError:
417
+ status = exc.code
418
+ body_bytes = b""
419
+ try:
420
+ body_bytes = exc.read()
421
+ except Exception: # pragma: no cover - defensive
422
+ pass
423
+ # Prefer the structured error envelope when the server provides one.
424
+ if body_bytes:
425
+ try:
426
+ decoded = json.loads(body_bytes.decode("utf-8"))
427
+ except (ValueError, UnicodeDecodeError):
428
+ decoded = None
429
+ if isinstance(decoded, dict) and "error" in decoded:
430
+ return LustroError.from_envelope(decoded, status=status)
431
+ # Fallback: synthesize from the status code.
432
+ error_type = _STATUS_ERROR_TYPES.get(status, "http_error")
433
+ message = body_bytes.decode("utf-8", "replace").strip() if body_bytes else (exc.reason or "")
434
+ return LustroError(error_type, message or error_type, status=status)