chuskybrowser 1.20.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.
chusky/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """chuskybrowser Python client. See client.py and the docs at docs/sdk/python.mdx."""
2
+
3
+ from .client import ChuskyClient, ChuskyError, DEFAULT_GATEWAY_URL
4
+
5
+ __all__ = ["ChuskyClient", "ChuskyError", "DEFAULT_GATEWAY_URL"]
6
+ __version__ = "1.20.0"
chusky/client.py ADDED
@@ -0,0 +1,156 @@
1
+ """chuskybrowser Python client. One instance per end user. Standard library only.
2
+
3
+ from chusky import ChuskyClient
4
+
5
+ browser = ChuskyClient(user_id=user_id_from_your_session) # never from user-typed text
6
+ tab = browser.open_tab(url="https://example.com", session_key="task-1")
7
+ page = browser.snapshot(tab["tabId"])
8
+ browser.close_tab(tab["tabId"])
9
+
10
+ Set CHUSKYBROWSER_API_KEY in the environment or in a .env file in the working folder.
11
+ Optional: CHUSKYBROWSER_BASE_URL (defaults to the hosted gateway).
12
+ The key is never printed, and error messages do not include it.
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+
21
+ DEFAULT_GATEWAY_URL = "https://chuskybrowser-production.up.railway.app/v1"
22
+
23
+
24
+ class ChuskyError(Exception):
25
+ """An API call failed. Carries status, code (for example 'human_in_control') and the body."""
26
+
27
+ def __init__(self, message, status=None, code=None, body=None):
28
+ super().__init__(message)
29
+ self.status = status
30
+ self.code = code
31
+ self.body = body
32
+
33
+
34
+ def _load_dotenv(path=".env"):
35
+ values = {}
36
+ if not os.path.exists(path):
37
+ return values
38
+ with open(path, encoding="utf-8") as f:
39
+ for line in f:
40
+ line = line.strip()
41
+ if not line or line.startswith("#") or "=" not in line:
42
+ continue
43
+ key, _, value = line.partition("=")
44
+ values[key.strip()] = value.strip().strip("'\"")
45
+ return values
46
+
47
+
48
+ _ENV = {**_load_dotenv(), **os.environ}
49
+
50
+
51
+ class ChuskyClient:
52
+ def __init__(self, user_id, api_key=None, base_url=None, timeout=120):
53
+ key = api_key or _ENV.get("CHUSKYBROWSER_API_KEY", "").strip()
54
+ if not key:
55
+ raise ChuskyError("CHUSKYBROWSER_API_KEY is not set. Put it in .env or your environment.")
56
+ if not isinstance(user_id, str) or not user_id.strip():
57
+ raise ChuskyError("user_id is required. Pass the end user's ID from your authenticated session.")
58
+ self._key = key
59
+ self._base = (base_url or _ENV.get("CHUSKYBROWSER_BASE_URL") or DEFAULT_GATEWAY_URL).rstrip("/")
60
+ self._timeout = timeout
61
+ self.user_id = user_id.strip()
62
+
63
+ # ----- transport -----
64
+
65
+ def _call(self, method, path, query=None, body=None, raw=False):
66
+ url = self._base + path
67
+ if method in ("GET", "DELETE"):
68
+ params = {"userId": self.user_id, **(query or {})}
69
+ params = {k: v for k, v in params.items() if v is not None}
70
+ url += "?" + urllib.parse.urlencode(params)
71
+ data = None
72
+ else:
73
+ payload = {"userId": self.user_id, **(body or {})}
74
+ data = json.dumps({k: v for k, v in payload.items() if v is not None}).encode("utf-8")
75
+ headers = {"Authorization": f"Bearer {self._key}"}
76
+ if data is not None:
77
+ headers["Content-Type"] = "application/json"
78
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
79
+ try:
80
+ with urllib.request.urlopen(req, timeout=self._timeout) as res:
81
+ payload = res.read()
82
+ if raw:
83
+ return payload
84
+ return json.loads(payload) if payload else None
85
+ except urllib.error.HTTPError as err:
86
+ text = err.read().decode("utf-8", errors="replace")
87
+ try:
88
+ body_json = json.loads(text)
89
+ except ValueError:
90
+ body_json = {"raw": text[:200]}
91
+ code = body_json.get("code") or body_json.get("error")
92
+ raise ChuskyError(
93
+ f"Chusky {method} {path} failed (HTTP {err.code})" + (f": {code}" if code else ""),
94
+ status=err.code, code=code, body=body_json,
95
+ ) from None
96
+
97
+ # ----- tabs -----
98
+
99
+ def open_tab(self, url=None, session_key=None, trace=False):
100
+ if not session_key:
101
+ raise ChuskyError("session_key is required (groups the tabs of one task).")
102
+ return self._call("POST", "/tabs", body={"sessionKey": session_key, "url": url, "trace": trace or None})
103
+
104
+ def navigate(self, tab_id, url=None, macro=None, query=None, session_key=None):
105
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/navigate",
106
+ body={"url": url, "macro": macro, "query": query, "sessionKey": session_key})
107
+
108
+ def state(self, tab_id):
109
+ return self._call("GET", f"/tabs/{_enc(tab_id)}/state")
110
+
111
+ def snapshot(self, tab_id, offset=None):
112
+ return self._call("GET", f"/tabs/{_enc(tab_id)}/snapshot", query={"offset": offset})
113
+
114
+ def screenshot(self, tab_id):
115
+ """Returns the PNG as bytes."""
116
+ return self._call("GET", f"/tabs/{_enc(tab_id)}/screenshot", raw=True)
117
+
118
+ def click(self, tab_id, ref=None, selector=None):
119
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/click", body={"ref": ref, "selector": selector})
120
+
121
+ def type(self, tab_id, text, ref=None, selector=None, press_enter=False):
122
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/type",
123
+ body={"text": text, "ref": ref, "selector": selector, "pressEnter": press_enter})
124
+
125
+ def press(self, tab_id, key):
126
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/press", body={"key": key})
127
+
128
+ def scroll(self, tab_id, direction="down", amount=None):
129
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/scroll", body={"direction": direction, "amount": amount})
130
+
131
+ def close_tab(self, tab_id):
132
+ return self._call("DELETE", f"/tabs/{_enc(tab_id)}")
133
+
134
+ def end_session(self):
135
+ """Close every tab for this user."""
136
+ return self._call("DELETE", f"/sessions/{_enc(self.user_id)}")
137
+
138
+ # ----- handoff to a person -----
139
+
140
+ def start_handoff(self, tab_id, reason, idle_ms=None):
141
+ if not reason:
142
+ raise ChuskyError("reason is required so the person knows what to do.")
143
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/handoff", body={"reason": reason, "idleMs": idle_ms})
144
+
145
+ def release(self, tab_id):
146
+ return self._call("POST", f"/tabs/{_enc(tab_id)}/handoff/release")
147
+
148
+ def viewer_link(self, tab_id, control=False, ttl_seconds=3600):
149
+ """A live view link for this user only. Returns the URL string."""
150
+ out = self._call("POST", "/live-viewer/links",
151
+ body={"tabId": tab_id, "control": control, "ttlSeconds": ttl_seconds})
152
+ return out.get("url")
153
+
154
+
155
+ def _enc(value):
156
+ return urllib.parse.quote(str(value), safe="")
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: chuskybrowser
3
+ Version: 1.20.0
4
+ Summary: Python client for chuskybrowser: open pages, read them, and hand them to a person for sign-in.
5
+ License: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+
9
+ # chuskybrowser (Python)
10
+
11
+ Standard library only. Requires Python 3.9 or newer.
12
+
13
+ ```bash
14
+ pip install chuskybrowser
15
+ ```
16
+
17
+ Set `CHUSKYBROWSER_API_KEY` in your environment or in a `.env` file.
18
+
19
+ ```python
20
+ from chusky import ChuskyClient
21
+
22
+ browser = ChuskyClient(user_id=user_id_from_your_session) # never from user-typed text
23
+ tab = browser.open_tab(url="https://example.com", session_key="task-1")
24
+ page = browser.snapshot(tab["tabId"])
25
+ browser.close_tab(tab["tabId"])
26
+ ```
27
+
28
+ Full guide: `docs/sdk/python.mdx`.
@@ -0,0 +1,6 @@
1
+ chusky/__init__.py,sha256=PH5uUrmvZ6L_FHvACsyjZMQc8CLYheoIuFvucg2ykAs,249
2
+ chusky/client.py,sha256=fhvrwB1ifdvD0Sj4vrPiIic8qDIUpUQA6t04gDlXO78,6651
3
+ chuskybrowser-1.20.0.dist-info/METADATA,sha256=Z9fOg8PGrAqWJy8knJSDeHn5ouT2IXRKIifpeFboGA4,769
4
+ chuskybrowser-1.20.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ chuskybrowser-1.20.0.dist-info/top_level.txt,sha256=mYFdjuyFa-CbrSGkIlxuQWgaR3yryLe1QtiwQY4HPC4,7
6
+ chuskybrowser-1.20.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ chusky