muse-cli 0.3.13__tar.gz → 0.3.15__tar.gz

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 (45) hide show
  1. {muse_cli-0.3.13 → muse_cli-0.3.15}/.gitignore +1 -0
  2. {muse_cli-0.3.13 → muse_cli-0.3.15}/PKG-INFO +6 -6
  3. {muse_cli-0.3.13 → muse_cli-0.3.15}/README.md +4 -4
  4. {muse_cli-0.3.13 → muse_cli-0.3.15}/docs/PROTOCOL.md +3 -0
  5. {muse_cli-0.3.13 → muse_cli-0.3.15}/pyproject.toml +1 -1
  6. {muse_cli-0.3.13 → muse_cli-0.3.15}/skills/muse-cli/SKILL.md +2 -2
  7. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/__init__.py +1 -1
  8. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/cli.py +68 -10
  9. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/gateway.py +56 -30
  10. {muse_cli-0.3.13 → muse_cli-0.3.15}/LICENSE +0 -0
  11. {muse_cli-0.3.13 → muse_cli-0.3.15}/docs/TUI.md +0 -0
  12. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/__main__.py +0 -0
  13. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/bridge.py +0 -0
  14. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/browsers.py +0 -0
  15. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/chat.py +0 -0
  16. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/demo.py +0 -0
  17. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/desc0.bin +0 -0
  18. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/desc1.bin +0 -0
  19. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/routes.json +0 -0
  20. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/skill.py +0 -0
  21. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/bun.lock +0 -0
  22. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/package.json +0 -0
  23. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/app.tsx +0 -0
  24. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/bridge.ts +0 -0
  25. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Composer.tsx +0 -0
  26. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Header.tsx +0 -0
  27. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Overlays.tsx +0 -0
  28. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Panels.tsx +0 -0
  29. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Sidebar.tsx +0 -0
  30. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Splash.tsx +0 -0
  31. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/Transcript.tsx +0 -0
  32. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/components/common.tsx +0 -0
  33. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/context.tsx +0 -0
  34. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/controller.ts +0 -0
  35. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/format.ts +0 -0
  36. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/main.tsx +0 -0
  37. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/protocol.ts +0 -0
  38. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/store.ts +0 -0
  39. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/src/theme.ts +0 -0
  40. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/test/app.test.tsx +0 -0
  41. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/test/fake.ts +0 -0
  42. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/test/logic.test.ts +0 -0
  43. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui/tsconfig.json +0 -0
  44. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/tui.py +0 -0
  45. {muse_cli-0.3.13 → muse_cli-0.3.15}/src/muse_cli/update.py +0 -0
@@ -11,6 +11,7 @@ uv.lock
11
11
  cookies.txt
12
12
  agent-cookies.json
13
13
  config.json
14
+ tokens.json
14
15
  *.har
15
16
 
16
17
  # OS
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: muse-cli
3
- Version: 0.3.13
3
+ Version: 0.3.15
4
4
  Summary: Command-line client for your personal muse.ai AI agent: chat, automate, and manage side chats, feed, goals, ideas, and sessions from the terminal. No browser needed.
5
5
  Project-URL: Homepage, https://github.com/nikships/muse-cli
6
6
  Project-URL: Documentation, https://github.com/nikships/muse-cli#readme
@@ -30,7 +30,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
30
30
  Classifier: Topic :: Terminals
31
31
  Classifier: Topic :: Utilities
32
32
  Requires-Python: >=3.10
33
- Requires-Dist: curl-cffi>=0.11
33
+ Requires-Dist: curl-cffi>=0.17
34
34
  Requires-Dist: noiseprotocol>=0.3
35
35
  Requires-Dist: protobuf>=5.0
36
36
  Description-Content-Type: text/markdown
@@ -95,8 +95,8 @@ you have logged in at https://muse.ai/ in your browser. Follow
95
95
 
96
96
  muse-cli borrows the login you already have in your browser, saves those
97
97
  cookies to `~/.config/muse-cli/cookies.txt` (mode `600`, only your user can
98
- read it), and after that talks to muse.ai directly. Access tokens are fetched
99
- fresh on every command. When a command later says the cookies expired, repeat
98
+ read it), and after that talks to muse.ai directly. Access tokens are reused
99
+ for up to 15 minutes (`tokens.json`, mode `600`), so commands start fast. When a command later says the cookies expired, repeat
100
100
  this section.
101
101
 
102
102
  ### On a Mac (Chrome, Brave, Arc, Edge or Chromium)
@@ -209,7 +209,7 @@ Use this when you don't have Node, or you don't want remote debugging on.
209
209
 
210
210
  1. In Chrome, open https://muse.ai/ and log in.
211
211
  2. Open DevTools (F12, or Ctrl+Shift+I) → **Application** → **Cookies** → `https://muse.ai`.
212
- 3. Copy the cookies onto one line. `hatch_sess` has to be there. Separate cookies with `; ` (semicolon, space). A Netscape cookie jar (what curl writes) and a JSON object such as `{"hatch_sess": "..."}` also work.
212
+ 3. Copy the cookies onto one line. `hatch_sess` has to be there. Separate cookies with `; ` (semicolon, space). A Netscape cookie jar (what curl writes) and a JSON object such as `{"hatch_sess": "..."}` also work. From a cookie jar, muse-cli reads only the `muse.ai` rows.
213
213
 
214
214
  ```bash
215
215
  mkdir -p ~/.config/muse-cli
@@ -374,7 +374,7 @@ release flow and contributor notes. Merging to `main` publishes a release.
374
374
 
375
375
  - Login is the [Log in once](#log-in-once) section above. Cookies live at
376
376
  `~/.config/muse-cli/cookies.txt` (mode 600). Access and gateway tokens are
377
- fetched fresh on every run.
377
+ cached in `tokens.json` (mode 600) for 15 minutes and refetched when refused.
378
378
  - On macOS, `auth export` decrypts the muse.ai cookies from the browser's own
379
379
  cookie file, using the browser's Safe Storage key from your login keychain.
380
380
  Elsewhere it reads Google Chrome through
@@ -58,8 +58,8 @@ you have logged in at https://muse.ai/ in your browser. Follow
58
58
 
59
59
  muse-cli borrows the login you already have in your browser, saves those
60
60
  cookies to `~/.config/muse-cli/cookies.txt` (mode `600`, only your user can
61
- read it), and after that talks to muse.ai directly. Access tokens are fetched
62
- fresh on every command. When a command later says the cookies expired, repeat
61
+ read it), and after that talks to muse.ai directly. Access tokens are reused
62
+ for up to 15 minutes (`tokens.json`, mode `600`), so commands start fast. When a command later says the cookies expired, repeat
63
63
  this section.
64
64
 
65
65
  ### On a Mac (Chrome, Brave, Arc, Edge or Chromium)
@@ -172,7 +172,7 @@ Use this when you don't have Node, or you don't want remote debugging on.
172
172
 
173
173
  1. In Chrome, open https://muse.ai/ and log in.
174
174
  2. Open DevTools (F12, or Ctrl+Shift+I) → **Application** → **Cookies** → `https://muse.ai`.
175
- 3. Copy the cookies onto one line. `hatch_sess` has to be there. Separate cookies with `; ` (semicolon, space). A Netscape cookie jar (what curl writes) and a JSON object such as `{"hatch_sess": "..."}` also work.
175
+ 3. Copy the cookies onto one line. `hatch_sess` has to be there. Separate cookies with `; ` (semicolon, space). A Netscape cookie jar (what curl writes) and a JSON object such as `{"hatch_sess": "..."}` also work. From a cookie jar, muse-cli reads only the `muse.ai` rows.
176
176
 
177
177
  ```bash
178
178
  mkdir -p ~/.config/muse-cli
@@ -337,7 +337,7 @@ release flow and contributor notes. Merging to `main` publishes a release.
337
337
 
338
338
  - Login is the [Log in once](#log-in-once) section above. Cookies live at
339
339
  `~/.config/muse-cli/cookies.txt` (mode 600). Access and gateway tokens are
340
- fetched fresh on every run.
340
+ cached in `tokens.json` (mode 600) for 15 minutes and refetched when refused.
341
341
  - On macOS, `auth export` decrypts the muse.ai cookies from the browser's own
342
342
  cookie file, using the browser's Safe Storage key from your login keychain.
343
343
  Elsewhere it reads Google Chrome through
@@ -62,6 +62,9 @@ chat / feed / goals / ideas / sessions / ...
62
62
  - Genuine assistant replies have an **empty `reply_to_message_id`**; proactive
63
63
  pushes (Telegram drafts, background task updates) are self-referential
64
64
  there. That is how `send` tells a reply apart from background chatter.
65
+ - `send` reads the newest history `seq` before it sends, then counts only
66
+ later events as the reply. If that read fails, `send` exits without
67
+ sending. A baseline of 0 would return an old reply as the new answer.
65
68
  - Generated media arrives as a **separate** assistant event after the text
66
69
  reply, ~20 s later for an image. `send --download` therefore waits until
67
70
  the history seq has been quiet for `SETTLE` seconds before collecting files.
@@ -53,7 +53,7 @@ classifiers = [
53
53
  "Topic :: Utilities",
54
54
  ]
55
55
  dependencies = [
56
- "curl_cffi>=0.11",
56
+ "curl_cffi>=0.17",
57
57
  "noiseprotocol>=0.3",
58
58
  "protobuf>=5.0",
59
59
  ]
@@ -36,7 +36,7 @@ muse-cli --help >/dev/null && echo cli-ok # proves the install + deps resolve
36
36
 
37
37
  The CLI stores the user's muse.ai browser login at
38
38
  `~/.config/muse-cli/cookies.txt` (mode 0600). Access and gateway tokens are
39
- fetched fresh on every run; only cookies persist. When a later command fails
39
+ cached for 15 minutes in `tokens.json` (mode 0600) and refetched when refused. When a later command fails
40
40
  with `auth error`, the cookies expired: repeat this step.
41
41
 
42
42
  ### 2a. macOS: read the browser directly (try this first)
@@ -147,7 +147,7 @@ Use this when Node is unavailable, the browser is Safari, or the user does not w
147
147
  hatch_sess=VALUE; other_name=other_value
148
148
  ```
149
149
 
150
- A Netscape jar or `{"hatch_sess": "..."}` JSON also works.
150
+ A Netscape jar (only `muse.ai` rows are read) or `{"hatch_sess": "..."}` JSON also works.
151
151
 
152
152
  4. `chmod 600 ~/.config/muse-cli/cookies.txt`
153
153
  5. `test -s ~/.config/muse-cli/cookies.txt && echo auth-ok`, then `muse-cli status`.
@@ -1,3 +1,3 @@
1
1
  """muse-cli: talk to your personal muse.ai AI agent from the terminal."""
2
2
 
3
- __version__ = "0.3.13"
3
+ __version__ = "0.3.15"
@@ -9,6 +9,7 @@ instead; it prints those steps when something is missing.
9
9
  Then: muse-cli status | muse-cli threads | muse-cli history | muse-cli send "hello" | ...
10
10
  """
11
11
  import argparse
12
+ import hashlib
12
13
  import json
13
14
  import os
14
15
  import re
@@ -18,12 +19,15 @@ import time
18
19
  import urllib.parse
19
20
 
20
21
  from . import __version__, browsers
21
- from .gateway import Gateway, AuthError, GatewayError, load_cookies
22
+ from .gateway import (Gateway, AuthError, GatewayError, fetch_access_token, fetch_hatch_token,
23
+ fetch_session_info, load_cookies)
22
24
  from .update import cmd_update, finish_update_check, start_update_check
23
25
 
24
26
  CONFIG_DIR = os.path.expanduser("~/.config/muse-cli")
25
27
  CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")
26
28
  COOKIES_FILE = os.path.join(CONFIG_DIR, "cookies.txt")
29
+ TOKENS_FILE = os.path.join(CONFIG_DIR, "tokens.json")
30
+ TOKEN_TTL = 15 * 60 # seconds a cached gateway token is tried before refetching
27
31
 
28
32
 
29
33
  def load_config():
@@ -58,7 +62,67 @@ def connect(cfg):
58
62
  cookies = load_cookies(cfg["cookies_file"])
59
63
  if not cookies.strip():
60
64
  raise AuthError(f"cookies file {cfg['cookies_file']} is empty; run `muse-cli auth export`")
61
- return Gateway(cookies, vm_id=cfg.get("vm_id"))
65
+ # Three HTTPS round trips (session, auth/check, hatch/token) are most of a
66
+ # connect, about 2.3 s of 2.8 s, and their answers outlive one command.
67
+ # A stale cached token is refused fast (403 on the WebSocket upgrade), so
68
+ # anything but a timeout falls back to fetching fresh ones.
69
+ cached = _cached_tokens(cookies)
70
+ if cached and cfg.get("vm_id") in (None, cached["vm_id"]):
71
+ try:
72
+ return Gateway(cookies, **cached)
73
+ except TimeoutError:
74
+ raise
75
+ except Exception:
76
+ _drop_tokens()
77
+ vm_id = cfg.get("vm_id") or fetch_session_info(cookies)["vm_id"]
78
+ access_token = fetch_access_token(cookies)
79
+ hatch_token = fetch_hatch_token(cookies, access_token, vm_id)
80
+ gw = Gateway(cookies, vm_id=vm_id, access_token=access_token, hatch_token=hatch_token)
81
+ _save_tokens(cookies, {"vm_id": vm_id, "access_token": access_token, "hatch_token": hatch_token})
82
+ return gw
83
+
84
+
85
+ def _token_key(cookies):
86
+ return hashlib.sha256(cookies.encode()).hexdigest()
87
+
88
+
89
+ def _cached_tokens(cookies):
90
+ """Tokens from an earlier run with the same cookies, if young enough."""
91
+ try:
92
+ with open(TOKENS_FILE) as fh:
93
+ d = json.load(fh)
94
+ if d["key"] == _token_key(cookies) and 0 <= time.time() - d["at"] < TOKEN_TTL:
95
+ return {k: str(d[k]) for k in ("vm_id", "access_token", "hatch_token")}
96
+ except (OSError, ValueError, KeyError, TypeError):
97
+ pass
98
+ return None
99
+
100
+
101
+ def _save_tokens(cookies, tokens):
102
+ # Same protection as cookies.txt: the tokens are a short-lived login.
103
+ try:
104
+ os.makedirs(CONFIG_DIR, exist_ok=True)
105
+ tmp = TOKENS_FILE + ".tmp"
106
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
107
+ # The mode above only applies when the tmp file is created. A tmp
108
+ # file left behind by a crashed run keeps its old mode, so enforce
109
+ # it on the open descriptor too.
110
+ try:
111
+ os.fchmod(fd, 0o600)
112
+ except (AttributeError, OSError):
113
+ pass
114
+ with os.fdopen(fd, "w") as fh:
115
+ json.dump(dict(tokens, key=_token_key(cookies), at=time.time()), fh)
116
+ os.replace(tmp, TOKENS_FILE)
117
+ except OSError:
118
+ pass
119
+
120
+
121
+ def _drop_tokens():
122
+ try:
123
+ os.remove(TOKENS_FILE)
124
+ except OSError:
125
+ pass
62
126
 
63
127
 
64
128
  def out(obj):
@@ -578,14 +642,8 @@ def cmd_send(args):
578
642
  # chat.history without session_id reads the main chat; with it, the
579
643
  # thread. Either way the scope matches where the reply will land.
580
644
  scope = {"session_id": args.thread} if args.thread else {}
581
- baseline = 0
582
- try:
583
- h = gw.call_json("chat.history", body={"limit": 1, **scope})
584
- evs = h.get("chat_events", [])
585
- if evs:
586
- baseline = max(e.get("seq", 0) for e in evs)
587
- except (GatewayError, TimeoutError):
588
- pass
645
+ h = gw.call_json("chat.history", body={"limit": 1, **scope})
646
+ baseline = max((e.get("seq") or 0 for e in h.get("chat_events", [])), default=0)
589
647
  stream_sid = gw._open("chat.stream", body=params)
590
648
  if not args.wait:
591
649
  out({"sent": True, "stream": stream_sid,
@@ -15,6 +15,7 @@ import queue as queue_mod
15
15
 
16
16
  from curl_cffi import requests as rq
17
17
  from curl_cffi.requests import WebSocket
18
+ from curl_cffi.requests.websockets import WebSocketTimeout
18
19
  from noise.connection import NoiseConnection, Keypair
19
20
  from google.protobuf import descriptor_pb2, descriptor_pool, message_factory
20
21
 
@@ -119,33 +120,41 @@ def fetch_hatch_token(cookies, access_token, vm_id):
119
120
 
120
121
 
121
122
  def load_cookies(path):
122
- """Accept a curl-style 'a=b; c=d' file or {"cookies": {...}} JSON."""
123
- raw = open(path).read().strip()
123
+ """Accept an 'a=b; c=d' line, {"cookies": {...}} JSON, or a Netscape cookie jar."""
124
+ with open(path) as fh:
125
+ text = fh.read()
126
+ raw = text.strip()
124
127
  if raw.startswith("{"):
125
128
  try:
126
129
  d = json.loads(raw)
127
130
  if isinstance(d, dict) and "cookies" in d and isinstance(d["cookies"], dict):
128
131
  return "; ".join(f"{k}={v}" for k, v in d["cookies"].items())
129
- return "; ".join(f"{k}={v}" for k, v in d.items())
132
+ if isinstance(d, dict):
133
+ return "; ".join(f"{k}={v}" for k, v in d.items())
130
134
  except json.JSONDecodeError:
131
135
  pass
132
- if "hatch_sess=" in raw or "datr=" in raw:
136
+ # Netscape cookie-jar format (checked before 'k=v' substring heuristics so
137
+ # a cookie value containing e.g. base64 'datr=' cannot misclassify a jar).
138
+ parts, jar_rows = [], False
139
+ for line in text.splitlines():
140
+ # curl marks HttpOnly cookies, hatch_sess among them, with this prefix.
141
+ line = line.removeprefix("#HttpOnly_")
142
+ if not line.strip() or line.lstrip().startswith("#"):
143
+ continue
144
+ cols = line.split("\t")
145
+ if len(cols) >= 7:
146
+ jar_rows = True
147
+ if cols[0].lower() in ("muse.ai", ".muse.ai"):
148
+ parts.append(f"{cols[5]}={cols[6]}")
149
+ if parts:
150
+ return "; ".join(parts)
151
+ if not jar_rows and ("hatch_sess=" in raw or "datr=" in raw):
133
152
  for line in raw.splitlines():
134
153
  line = line.strip()
135
154
  if line and not line.startswith("#") and "=" in line and ";" in line:
136
155
  return line
137
156
  return " ".join(raw.split())
138
- # Netscape cookie-jar format
139
- parts = []
140
- for line in raw.splitlines():
141
- if not line or line.startswith("#"):
142
- continue
143
- cols = line.split("\t")
144
- if len(cols) >= 7:
145
- parts.append(f"{cols[5]}={cols[6]}")
146
- if not parts:
147
- raise AuthError(f"could not parse cookies file {path}")
148
- return "; ".join(parts)
157
+ raise AuthError(f"could not parse cookies file {path}")
149
158
 
150
159
 
151
160
  def fetch_session_info(cookies):
@@ -181,16 +190,27 @@ class Gateway:
181
190
  self.ws = WebSocket()
182
191
  # verify=True is required: curl_cffi's WebSocket.connect defaults to
183
192
  # verify=None, which disables TLS certificate verification entirely.
184
- self.ws.connect(url, impersonate="chrome", timeout=20, verify=True)
185
- noise = NoiseConnection.from_name(b"Noise_XX_25519_AESGCM_SHA256")
186
- noise.set_as_initiator()
187
- noise.set_keypair_from_private_bytes(Keypair.STATIC, os.urandom(32))
188
- noise.start_handshake()
189
- self.ws.send_bytes(bytes(noise.write_message(b"")))
190
- m2, _ = self.ws.recv()
191
- noise.read_message(bytes(m2))
192
- self.ws.send_bytes(bytes(noise.write_message(b"")))
193
- assert noise.handshake_finished
193
+ try:
194
+ self.ws.connect(url, impersonate="chrome", timeout=20, verify=True)
195
+ except rq.exceptions.Timeout:
196
+ self.close()
197
+ raise TimeoutError("gateway connect timed out") from None
198
+ try:
199
+ noise = NoiseConnection.from_name(b"Noise_XX_25519_AESGCM_SHA256")
200
+ noise.set_as_initiator()
201
+ noise.set_keypair_from_private_bytes(Keypair.STATIC, os.urandom(32))
202
+ noise.start_handshake()
203
+ self.ws.send_bytes(bytes(noise.write_message(b"")), timeout=20)
204
+ m2, _ = self.ws.recv(timeout=20)
205
+ noise.read_message(bytes(m2))
206
+ self.ws.send_bytes(bytes(noise.write_message(b"")), timeout=20)
207
+ assert noise.handshake_finished
208
+ except (WebSocketTimeout, rq.exceptions.Timeout):
209
+ self.close()
210
+ raise TimeoutError("gateway handshake timed out") from None
211
+ except BaseException:
212
+ self.close()
213
+ raise
194
214
  self.noise = noise
195
215
  self.stream = 1
196
216
  self._send_lock = threading.Lock()
@@ -206,7 +226,7 @@ class Gateway:
206
226
  with self._send_lock:
207
227
  self.ws.send_bytes(bytes(self.noise.encrypt(fr.SerializeToString())))
208
228
 
209
- def _read_frame(self):
229
+ def _read_frame(self, deadline=None):
210
230
  # Serialized so two threads can never interleave ws.recv / Noise
211
231
  # decrypt (which corrupts the transport state -> BAD_DECRYPT).
212
232
  # Callers must still avoid *logical* races: only one thread should
@@ -216,7 +236,13 @@ class Gateway:
216
236
  # several transport frames sharing a chunk_id; only the joined
217
237
  # payload is a ServiceResponse. Keep reading until it is whole.
218
238
  while True:
219
- data, _flags = self.ws.recv()
239
+ remaining = None if deadline is None else deadline - time.monotonic()
240
+ if remaining is not None and remaining <= 0:
241
+ raise TimeoutError("gateway response timed out")
242
+ try:
243
+ data, _flags = self.ws.recv(timeout=remaining)
244
+ except WebSocketTimeout:
245
+ raise TimeoutError("gateway response timed out") from None
220
246
  pt = bytes(self.noise.decrypt(bytes(data)))
221
247
  ntf = NoiseTransportFrame()
222
248
  ntf.ParseFromString(pt)
@@ -280,14 +306,14 @@ class Gateway:
280
306
  query, body = body, None
281
307
  sid = self._open(method, path_params, body, query, route=route)
282
308
  status, headers, err, done = None, {}, [], False
283
- deadline = time.time() + timeout
309
+ deadline = time.monotonic() + timeout
284
310
 
285
311
  def feed(data):
286
312
  if data:
287
313
  (sink if 200 <= status < 300 else err.append)(data)
288
314
 
289
- while time.time() < deadline and not done:
290
- sf = self._read_frame()
315
+ while time.monotonic() < deadline and not done:
316
+ sf = self._read_frame(deadline=deadline)
291
317
  if sf.stream_id != sid:
292
318
  continue
293
319
  kind = sf.WhichOneof("kind")
File without changes
File without changes
File without changes