Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1564 lines (1379 loc) · 64.2 KB
/
Copy pathmain.py
File metadata and controls
1564 lines (1379 loc) · 64.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import fcntl
import glob
import json
import logging
import os
import pty
import pwd
import re
import shlex
import sys
import termios
import uuid
from collections import OrderedDict
# Decky imports this file by path, so the plugin directory is not guaranteed to
# be on sys.path — anchor it so the sibling module shared with mcp_server.py
# resolves either way.
_PLUGIN_DIR = os.path.dirname(os.path.abspath(__file__))
if _PLUGIN_DIR not in sys.path:
sys.path.insert(0, _PLUGIN_DIR)
import deck_common # noqa: E402 (needs the sys.path anchor above)
import machine_profile # noqa: E402
logger = logging.getLogger("decky-claude")
def _become_controlling_tty():
"""preexec_fn for pty-backed subprocesses: fd 0 is already dup'd to the
pty slave by the time this runs, but an inherited fd is never
auto-adopted as the controlling terminal on Linux — only setsid() +
TIOCSCTTY does that. Without this, whether `sudo`/`pkexec` inside the
spawned `claude` find a controlling terminal is down to accidental
leftover session state, not this fd wiring.
"""
os.setsid()
fcntl.ioctl(0, termios.TIOCSCTTY, 0)
_ANSI_ESCAPE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
_SESSION_URL_BASE = "https://claude.ai/code/"
# Fallback only. The TUI redraws by skipping cells that already hold the right
# character, so after stripping escapes a printed URL can lose letters (seen:
# "claude.ai/cde/session_…"). Match loosely and rebuild from the id.
_URL_PATTERN = re.compile(r"https://claude\.ai/\S{0,12}?(session_[A-Za-z0-9]+)")
# `claude auth login` prints its OAuth URL wrapped in an OSC-8 hyperlink, so
# stop at ESC/BEL/] rather than whitespace.
_OAUTH_URL = re.compile(r"https://[^\s\x1b\x07\]]*/oauth/[^\s\x1b\x07\]]+")
# Claude 2.1+ blocks `--resume` of a large/old transcript on an interactive
# picker ("Resume from summary?"). A remote-control session has no one at the
# keyboard, so that prompt is why Resume Session looked like a fresh start.
_RESUME_PROMPT = re.compile(
r"Resume from summary \(recommended\)|Resuming the full session will consume",
re.I,
)
# A logged-out CLI keeps the TUI open with this footer instead of exiting, so
# without it the panel waited out the timeout and then claimed "running".
# The TUI positions words with cursor moves, so stripped output has no spaces.
_NOT_LOGGED_IN = re.compile(r"Not\s*logged\s*in", re.I)
# Sentinel used to mark the block we inject into CLAUDE.md
_MD_START = "<!-- decky-claude-start -->"
_MD_END = "<!-- decky-claude-end -->"
def _resolve_user() -> tuple[str, int]:
"""Home directory and uid of the desktop user owning the Steam session.
Hardcoding /home/deck only works on SteamOS. Decky exports DECKY_USER /
DECKY_USER_HOME, and the backend normally already runs as the desktop user,
so prefer those signals and treat "deck" as a last-resort guess.
"""
home = os.environ.get("DECKY_USER_HOME")
user = os.environ.get("DECKY_USER")
if user:
try:
entry = pwd.getpwnam(user)
return home or entry.pw_dir, entry.pw_uid
except KeyError:
pass
if home:
try:
return home, pwd.getpwnam(os.path.basename(home)).pw_uid
except KeyError:
return home, os.getuid()
# Normal case: the plugin backend runs as the desktop user already.
uid = os.getuid()
if uid != 0:
try:
entry = pwd.getpwuid(uid)
return entry.pw_dir, uid
except KeyError:
pass
try:
entry = pwd.getpwnam("deck")
return entry.pw_dir, entry.pw_uid
except KeyError:
return os.path.expanduser("~"), uid
_USER_HOME, _USER_UID = _resolve_user()
# Directories scanned for the steam-debugger skill. A personal copy in
# ~/.claude/skills overrides the one bundled with the plugin.
_SKILL_BASES = [
os.path.join(_USER_HOME, ".claude", "skills"),
os.path.join(_PLUGIN_DIR, "skills"),
]
def _claude_md_block(skill_name: str | None, machine_md: str = "") -> str:
skill_section = ""
if skill_name:
skill_section = f"""
## Steam debugger skill — preloaded, always active
The `{skill_name}` skill's SKILL.md is already part of your system prompt
(the plugin injects it on every start and resume). Follow it for all Steam,
Steam Input, gamescope, Proton and game work, and read its reference files
as it directs before experimenting. It is also linked at
`.claude/skills/{skill_name}`.
"""
machine_section = f"\n{machine_md}\n" if machine_md else ""
return f"""\
{_MD_START}
# decky-claude session
You are running via the decky-claude Decky Loader plugin, launched from the
Steam Quick Access menu. The user is messaging you from the Claude app, most
likely on their phone, and may not be able to read long output comfortably.
{machine_section}{skill_section}
## MCP tools you have
- **steam_snippet** — Curated, pre-verified SteamClient queries for the
common problems: `downloads`, `login`, `library`, `running`, `client_info`,
plus the `refresh_library` and `check_updates` actions. Try this before
hand-writing JS: several namespaces (Downloads especially) expose no getters
at all, only RegisterFor* callbacks, so the obvious expression returns
nothing.
- **steam_ui_targets** / **steam_ui_eval** — The general debugging tools.
Steam's UI is embedded Chromium; `steam_ui_eval` runs JavaScript inside it
via the Chrome DevTools Protocol. `SharedJSContext` hosts the `SteamClient`
API — inspect Steam's real state and trigger real actions instead of
clicking pixels.
- **screenshot** — Capture the current display. Returns a PNG image. By
default this is the game/desktop frame only (same as the controller's
screenshot button) — the Steam overlay (Quick Access Menu, notifications)
is excluded. Pass `include_steam_ui: true` when the QAM or an overlay
dialog itself is what needs to be seen.
- **send_key** — Send a key press to the focused window
(e.g. `escape`, `Return`, `space`, `Tab`, `F1`, `ctrl+c`).
- **type_text** — Type a string into the focused window.
- **mouse_move_click** — Move to (x, y) pixel coordinates and click.
Steam Deck native resolution is 1280×800.
- **session_context** — Live check: Gaming vs Desktop Mode (screenshot/input
only work in Gaming Mode) and whether this session runs inside the plugin.
## Behaviour rules
1. **The primary mission is debugging Steam and the Steam UI.** For those
problems, prefer `steam_ui_eval` (structured, reliable) over pixel input;
use `screenshot` to correlate with what the user sees.
2. **Look before answering**: for anything about the current visual state
(errors, dialogs, games), call `screenshot` first. Never guess — look.
3. **Read the logs**: `~/.steam/steam/logs/`, `journalctl --user`, Proton
logs — combine the terminal view with the visual view.
4. **After sending input or triggering an action**: verify via another
screenshot or `steam_ui_eval` read.
5. **Check where you are, live**: call `session_context` before using
`screenshot`/`send_key`/`type_text`/`mouse_move_click` and before
restarting `plugin_loader.service`. The mode can change mid-session; the
machine profile above is only a snapshot from session start. A session
launched by this plugin runs under PluginLoader and **dies instantly, with
no auto-resume, when `plugin_loader.service` restarts** — warn the user and
do it last (or let them run it). Standalone terminal sessions are unaffected.
{_MD_END}
"""
# ── self-update ────────────────────────────────────────────────────────────────
# The plugin is not in the Decky store, so Decky never tells anyone a new
# version exists. We ask GitHub for the latest release ourselves; the actual
# install is handed to Decky's own installer by the frontend
# (utilities/install_plugin), exactly the path the store uses. Nothing here
# writes plugin files.
_UPDATE_REPO = "TuxLux40/decky-claude"
_UPDATE_API = f"https://api.github.com/repos/{_UPDATE_REPO}/releases/latest"
_UPDATE_ASSET = "decky-claude.zip"
_UPDATE_TTL = 6 * 3600 # a successful check is good for this long
_UPDATE_RETRY = 15 * 60 # back off this long after a failed check
_SHA256_RE = re.compile(r"\b[0-9a-fA-F]{64}\b")
def _plugin_setting_dir(env_key: str, fallback: str) -> str:
path = os.environ.get(env_key) or os.path.join(
_USER_HOME, "homebrew", fallback, "decky-claude"
)
os.makedirs(path, exist_ok=True)
return path
def _settings_path() -> str:
# Decky keeps DECKY_PLUGIN_SETTINGS_DIR across reinstalls/updates (only the
# plugin directory is replaced), so this survives the updates it enables.
return os.path.join(_plugin_setting_dir("DECKY_PLUGIN_SETTINGS_DIR", "settings"), "settings.json")
def _load_settings() -> dict:
try:
with open(_settings_path()) as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except (OSError, ValueError):
return {}
def _save_setting(key: str, value) -> None:
"""Read-modify-write so keys owned by other features are preserved."""
data = _load_settings()
data[key] = value
path = _settings_path()
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp, path)
async def _emit(event: str, *args) -> None:
"""decky.emit, tolerating its absence and its failures.
The decky module only exists inside Decky's plugin runtime, and a push the
frontend misses is recovered by the panel's own status poll — neither is
worth breaking the session code path over.
"""
try:
import decky
await decky.emit(event, *args)
except Exception as exc:
logger.warning("could not emit %s: %s", event, exc)
def _installed_version() -> str:
try:
with open(os.path.join(_PLUGIN_DIR, "package.json")) as f:
return str(json.load(f).get("version") or "0.0.0")
except (OSError, ValueError):
return os.environ.get("DECKY_PLUGIN_VERSION", "0.0.0")
def _version_tuple(v: str) -> tuple[int, ...]:
"""'v1.2.3' / '1.2.3-rc1' -> (1, 2, 3). Unparseable parts count as 0."""
core = v.strip().lstrip("vV").split("-", 1)[0].split("+", 1)[0]
out = []
for part in core.split("."):
m = re.match(r"\d+", part)
out.append(int(m.group(0)) if m else 0)
while len(out) < 3:
out.append(0)
return tuple(out)
def _ssl_context():
import ssl
# Decky's bundled Python may not find the distro CA store on its own;
# certifi ships with it (aiohttp depends on it), then fall back to the
# usual system bundle locations.
try:
import certifi # type: ignore
return ssl.create_default_context(cafile=certifi.where())
except Exception:
pass
for cafile in (
"/etc/ssl/certs/ca-certificates.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/cert.pem",
):
if os.path.isfile(cafile):
try:
return ssl.create_default_context(cafile=cafile)
except Exception:
continue
return ssl.create_default_context()
def _http_get(url: str, headers: dict | None = None, timeout: float = 10):
"""Blocking GET -> (status, headers, body). 304 is returned, not raised."""
import urllib.error
import urllib.request
req = urllib.request.Request(url, headers={
"User-Agent": "decky-claude-updater",
**(headers or {}),
})
try:
with urllib.request.urlopen(req, timeout=timeout, context=_ssl_context()) as resp:
return resp.status, dict(resp.headers), resp.read()
except urllib.error.HTTPError as exc:
if exc.code == 304:
return 304, dict(exc.headers or {}), b""
raise
def _parse_release(data: dict, sha_fetcher) -> dict:
tag = str(data.get("tag_name") or "")
asset = next(
(a for a in data.get("assets") or [] if a.get("name") == _UPDATE_ASSET), None
)
if not tag or not asset:
raise ValueError(f"latest release {tag or '?'} has no {_UPDATE_ASSET}")
# GitHub reports "digest": "sha256:<hex>" on assets; the CI also publishes
# a .sha256 asset as a fallback for older API responses.
digest = str(asset.get("digest") or "")
sha = digest.split(":", 1)[1] if digest.startswith("sha256:") else ""
if not sha:
sha_asset = next(
(a for a in data.get("assets") or []
if a.get("name") == _UPDATE_ASSET + ".sha256"),
None,
)
if sha_asset:
m = _SHA256_RE.search(sha_fetcher(sha_asset["browser_download_url"]))
sha = m.group(0) if m else ""
return {
"tag": tag,
"version": tag.lstrip("vV"),
"artifact": asset["browser_download_url"],
"hash": sha.lower(),
"url": data.get("html_url") or "",
"published_at": data.get("published_at") or "",
}
def _fetch_latest_release(etag: str) -> tuple[dict | None, str]:
"""Blocking. Returns (release or None if unchanged, new etag)."""
headers = {"Accept": "application/vnd.github+json"}
if etag:
# Conditional requests answered with 304 don't count against the
# 60/h unauthenticated rate limit.
headers["If-None-Match"] = etag
status, resp_headers, body = _http_get(_UPDATE_API, headers)
new_etag = resp_headers.get("ETag") or resp_headers.get("Etag") or ""
if status == 304:
return None, new_etag or etag
release = _parse_release(
json.loads(body),
lambda url: _http_get(url)[2].decode("utf-8", errors="replace"),
)
return release, new_etag
class _Updater:
"""Cached, non-blocking latest-release lookup."""
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._cache: dict = {}
self._error: str | None = None
self._error_at = 0.0
self._loaded = False
@staticmethod
def _cache_path() -> str:
return os.path.join(_plugin_setting_dir("DECKY_PLUGIN_RUNTIME_DIR", "data"), "update_cache.json")
def _load(self) -> None:
if self._loaded:
return
self._loaded = True
try:
with open(self._cache_path()) as f:
data = json.load(f)
if isinstance(data, dict):
self._cache = data
except (OSError, ValueError):
pass
def _store(self) -> None:
try:
with open(self._cache_path(), "w") as f:
json.dump(self._cache, f)
except OSError:
logger.warning("could not persist update cache", exc_info=True)
async def latest(self, force: bool = False) -> tuple[dict | None, str | None]:
import time
async with self._lock:
self._load()
now = time.time()
fresh = now - float(self._cache.get("checked_at") or 0) < _UPDATE_TTL
backing_off = now - self._error_at < _UPDATE_RETRY
if not force and (fresh or backing_off):
return self._cache.get("release"), self._error
try:
release, etag = await asyncio.wait_for(
asyncio.to_thread(
_fetch_latest_release,
self._cache.get("etag", "") if self._cache.get("release") else "",
),
timeout=30,
)
except Exception as exc:
import urllib.error
if isinstance(exc, urllib.error.HTTPError) and exc.code in (403, 429):
msg = "GitHub rate limit reached, will retry later"
elif isinstance(exc, urllib.error.HTTPError) and exc.code == 404:
msg = "No release published yet"
elif isinstance(exc, (urllib.error.URLError, OSError, asyncio.TimeoutError)):
msg = "Offline or GitHub unreachable"
else:
msg = f"Update check failed: {exc}"
logger.info("update check: %s (%r)", msg, exc)
self._error, self._error_at = msg, now
return self._cache.get("release"), self._error
if release is not None:
self._cache["release"] = release
self._cache["etag"] = etag
self._cache["checked_at"] = now
self._error, self._error_at = None, 0.0
self._store()
return self._cache.get("release"), None
def checked_at(self) -> float:
return float(self._cache.get("checked_at") or 0)
_updater: _Updater | None = None
def _get_updater() -> _Updater:
# Created lazily so its asyncio.Lock binds to Decky's running loop.
global _updater
if _updater is None:
_updater = _Updater()
return _updater
# ── end self-update ────────────────────────────────────────────────────────────
def _is_plugin_skill_link(path: str) -> bool:
"""True if path is a symlink into this plugin's bundled skills."""
if not os.path.islink(path):
return False
target = os.path.abspath(os.path.join(os.path.dirname(path), os.readlink(path)))
return target.startswith(os.path.join(_PLUGIN_DIR, "skills") + os.sep)
class Plugin:
# ── session state ──────────────────────────────────────────────────────────
_process: asyncio.subprocess.Process | None = None
_pty_master_fd: int | None = None
_session_url: str | None = None
_status: str = "stopped"
_working_dir: str = _USER_HOME
_resume_id: str = ""
_session_id: str = ""
_error_msg: str | None = None
_not_logged_in: bool = False
# Set while stop_session() tears the process down, so the output drain
# doesn't mistake a requested stop for the session ending on its own.
_stopping: bool = False
# Decky tears the event loop down right after _unload, so a push queued
# then is never sent and only leaves a "Task was destroyed" warning.
_unloading: bool = False
_log_lines: list[str] = []
_skill_name: str | None = None
_skill_link_created: str | None = None
# ── login flow state ───────────────────────────────────────────────────────
_login_proc: asyncio.subprocess.Process | None = None
_login_fd: int | None = None
_login_url: str | None = None
@staticmethod
def _machine_md() -> str:
"""Machine description for the session's CLAUDE.md.
Regenerated per session rather than cached: it costs ~50ms of file
reads, and the parts most worth knowing (free space, installed games,
whether Gaming Mode is active) are exactly the parts that go stale.
Never fatal — a session without a profile is merely less informed.
"""
try:
return machine_profile.render(machine_profile.collect(_USER_HOME, _USER_UID))
except Exception:
logger.exception("could not build machine profile")
return ""
# ── lifecycle ──────────────────────────────────────────────────────────────
async def _main(self):
logger.info("decky-claude loaded")
self._log_lines = []
async def _unload(self):
self._unloading = True
await self.cancel_login()
await self.stop_session()
# ── session API ────────────────────────────────────────────────────────────
async def start_session(self, working_dir: str = "", resume_id: str = ""):
if self._process and self._process.returncode is None:
return {"success": False, "error": "Session already running"}
# A transcript only replays in the directory it was recorded in, so the
# session's own cwd wins over whatever the panel had selected.
if resume_id:
recorded = self._session_dir(resume_id)
if not recorded:
return {"success": False, "error": "That session no longer exists"}
working_dir = recorded
working_dir = working_dir or _USER_HOME
self._working_dir = working_dir
self._resume_id = resume_id
self._session_url = None
self._error_msg = None
self._not_logged_in = False
self._status = "starting"
self._log_lines = []
self._publish()
claude_bin = await self._find_claude()
if not claude_bin:
self._status = "error"
self._error_msg = (
"claude not found. Install via: npm install -g @anthropic-ai/claude-code"
)
self._publish()
return {"success": False, "error": self._error_msg}
try:
mcp_config = self._setup_working_dir(working_dir)
except OSError as exc:
logger.error("could not prepare %s: %s", working_dir, exc)
self._status = "error"
self._error_msg = (
f"Could not prepare {working_dir}: {exc}. "
"Pick a directory you can write to."
)
self._publish()
return {"success": False, "error": self._error_msg}
self._trust_working_dir(working_dir)
# claude falls back to non-interactive "-p" behaviour (which then
# demands a prompt) whenever stdout isn't a TTY, so a plain pipe
# can't be used here — give it a pty to keep it in interactive
# remote-control mode while we still capture its output.
# stdin has to be the pty too: the TUI only renders when all three
# streams are a terminal, and with stdin on /dev/null it prints
# nothing at all, so the session URL never appears.
master_fd, slave_fd = pty.openpty()
argv = [claude_bin, "--remote-control", "--mcp-config", mcp_config]
# The skill is this plugin's core; an instruction to load it proved
# ignorable, so its SKILL.md goes straight into the system prompt.
preload = self._write_skill_preload()
if preload:
argv += ["--append-system-prompt-file", preload]
hooks = self._learning_loop_settings()
if hooks:
argv += ["--settings", hooks]
if resume_id:
argv += ["--resume", resume_id]
self._session_id = resume_id
else:
# Pin the id up front instead of hunting for the transcript claude
# picked, so the panel can point at its own session in the list.
self._session_id = str(uuid.uuid4())
argv += ["--session-id", self._session_id]
env = self._display_env()
try:
self._process = await asyncio.create_subprocess_exec(
*argv,
cwd=working_dir,
env=env,
stdout=slave_fd,
stderr=slave_fd,
stdin=slave_fd,
preexec_fn=_become_controlling_tty,
)
except Exception as exc:
os.close(slave_fd)
os.close(master_fd)
self._status = "error"
self._error_msg = str(exc)
self._publish()
return {"success": False, "error": self._error_msg}
os.close(slave_fd)
self._pty_master_fd = master_fd
asyncio.ensure_future(self._drain_output())
for _ in range(90):
self._adopt_session_from_state()
if self._session_url:
self._status = "running"
self._error_msg = None
return {"success": True, "url": self._session_url}
if self._not_logged_in:
return await self._fail_start(
"Claude is logged out on this PC. Log in again above, "
"then start the session."
)
if self._process.returncode is not None:
self._status = "error"
self._error_msg = "Process exited before providing a session URL"
self._publish()
return {"success": False, "error": self._error_msg}
await asyncio.sleep(0.5)
# Without a URL the session never registered with claude.ai, so it
# would not show up in the app. Reporting "running" here hid that.
last = self._log_lines[-1] if self._log_lines else "no output"
return await self._fail_start(
"The session did not connect to claude.ai within 45 seconds, so it "
f"would not show up in the Claude app. Last output: {last}"
)
async def _fail_start(self, message: str) -> dict:
await self.stop_session()
self._status = "error"
self._error_msg = message
self._publish()
return {"success": False, "error": message}
async def stop_session(self):
self._stopping = True
if self._process:
try:
self._process.terminate()
try:
await asyncio.wait_for(self._process.wait(), timeout=3)
except asyncio.TimeoutError:
self._process.kill()
except ProcessLookupError:
pass
self._process = None
if self._pty_master_fd is not None:
try:
os.close(self._pty_master_fd)
except OSError:
pass
self._pty_master_fd = None
self._cleanup_working_dir(self._working_dir)
self._session_url = None
self._status = "stopped"
self._error_msg = None
self._resume_id = ""
self._session_id = ""
self._stopping = False
self._publish()
return {"success": True}
async def get_status(self):
if self._process and self._process.returncode is not None:
self._process = None
self._session_url = None
if self._status not in ("stopped", "error"):
self._status = "stopped"
return self._status_payload()
def _status_payload(self) -> dict:
return {
"status": self._status,
"url": self._session_url,
"working_dir": self._working_dir,
"resume_id": self._resume_id,
"error": self._error_msg,
"skill": self._skill_name,
}
def _publish(self, event: str | None = None) -> None:
"""Push the session state to the frontend.
The panel only exists while the Quick Access menu shows it, so it can't
be what notices a URL arriving or a session ending after it closed.
``event`` names the transitions the frontend announces with a toast:
"ready" (the session is reachable from the Claude app) and "ended"
(it stopped without the panel's Stop).
"""
if self._unloading:
return
payload = dict(self._status_payload(), event=event)
asyncio.ensure_future(_emit("session_status", payload))
async def get_log(self):
return {"lines": self._log_lines[-30:]}
# ── authentication ─────────────────────────────────────────────────────────
async def get_auth(self):
"""Login state straight from the CLI, so it can't drift from reality."""
claude_bin = await self._find_claude()
if not claude_bin:
return {"logged_in": False, "error": "claude not found"}
try:
proc = await asyncio.create_subprocess_exec(
claude_bin, "auth", "status", "--json",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
env=self._display_env(),
)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=15)
data = json.loads(out.decode(errors="replace"))
except (OSError, asyncio.TimeoutError, json.JSONDecodeError) as exc:
return {"logged_in": False, "error": str(exc)}
return {
"logged_in": bool(data.get("loggedIn")),
"email": data.get("email"),
"org": data.get("orgName"),
"plan": data.get("subscriptionType"),
"method": data.get("authMethod"),
}
async def start_login(self):
"""Begin `claude auth login` and hand back the OAuth URL to show as a QR.
The CLI renders the URL as an OSC-8 hyperlink and then blocks on a
"Paste code here" prompt, so it needs a pty and the process has to stay
alive until submit_login_code() feeds the code back.
"""
if self._login_fd is not None:
if self._login_url:
return {"success": True, "url": self._login_url}
await self.cancel_login()
claude_bin = await self._find_claude()
if not claude_bin:
return {"success": False, "error": "claude not found"}
master_fd, slave_fd = pty.openpty()
try:
self._login_proc = await asyncio.create_subprocess_exec(
claude_bin, "auth", "login",
cwd=_USER_HOME,
env=self._display_env(),
stdout=slave_fd,
stderr=slave_fd,
stdin=slave_fd,
preexec_fn=_become_controlling_tty,
)
except Exception as exc:
os.close(slave_fd)
os.close(master_fd)
return {"success": False, "error": str(exc)}
os.close(slave_fd)
self._login_fd = master_fd
self._login_url = None
loop = asyncio.get_event_loop()
buf = b""
deadline = loop.time() + 30
while loop.time() < deadline:
try:
chunk = await asyncio.wait_for(
loop.run_in_executor(None, os.read, master_fd, 4096), timeout=5
)
except (asyncio.TimeoutError, OSError):
break
if not chunk:
break
buf += chunk
match = _OAUTH_URL.search(buf.decode("utf-8", errors="replace"))
if match:
self._login_url = match.group(0)
return {"success": True, "url": self._login_url}
await self.cancel_login()
return {"success": False, "error": "Timed out waiting for the login URL"}
async def submit_login_code(self, code: str):
"""Feed the pasted OAuth code back to the waiting login process."""
if self._login_fd is None:
return {"success": False, "error": "No login in progress"}
try:
os.write(self._login_fd, (code.strip() + "\n").encode())
except OSError as exc:
return {"success": False, "error": str(exc)}
try:
await asyncio.wait_for(self._login_proc.wait(), timeout=60)
except (asyncio.TimeoutError, AttributeError):
pass
await self.cancel_login()
auth = await self.get_auth()
if auth.get("logged_in"):
return {"success": True, **auth}
return {"success": False, "error": auth.get("error") or "Login did not complete"}
async def cancel_login(self):
if self._login_proc and self._login_proc.returncode is None:
try:
self._login_proc.kill()
except ProcessLookupError:
pass
self._login_proc = None
if self._login_fd is not None:
try:
os.close(self._login_fd)
except OSError:
pass
self._login_fd = None
self._login_url = None
return {"success": True}
# ── other sessions on this machine ─────────────────────────────────────────
async def list_sessions(self, limit: int = 3):
"""Recent Claude Code sessions belonging to this user.
Transcripts live in ~/.claude/projects/<encoded-cwd>/<session>.jsonl.
The encoded directory name is lossy (slashes and dashes collapse), so
read the real cwd out of the transcript instead.
"""
root = os.path.join(_USER_HOME, ".claude", "projects")
live = self._live_session_ids()
entries = []
try:
for project in os.listdir(root):
pdir = os.path.join(root, project)
if not os.path.isdir(pdir):
continue
for name in os.listdir(pdir):
if not name.endswith(".jsonl"):
continue
path = os.path.join(pdir, name)
try:
mtime = os.path.getmtime(path)
except OSError:
continue
entries.append((mtime, path, name[: -len(".jsonl")]))
except OSError as exc:
return {"sessions": [], "error": str(exc)}
entries.sort(reverse=True)
sessions = []
for mtime, path, session_id in entries[:limit]:
cwd = self._session_cwd(path) or self._decode_project_dir(
os.path.basename(os.path.dirname(path))
)
sessions.append({
"id": session_id,
"short_id": session_id[:8],
"cwd": cwd,
"label": os.path.basename(cwd.rstrip("/")) or cwd,
"preview": self._session_preview(path, mtime),
"mtime": int(mtime),
"live": session_id in live,
"current": session_id == self._session_id and self._status == "running",
})
return {"sessions": sessions}
# Keyed by transcript path, so it would otherwise grow with every session
# this machine has ever recorded. The panel only ever renders one page of
# list_sessions, so a few pages' worth of history is ample.
_PREVIEW_CACHE_MAX = 64
_preview_cache: "OrderedDict[str, tuple[float, str]]" = OrderedDict()
@classmethod
def _session_preview(cls, path: str, mtime: float) -> str:
"""First thing the user asked in that session — the only practical way
to tell two sessions in the same directory apart when picking one to
resume. Cached on mtime because the panel polls this list.
"""
cached = cls._preview_cache.get(path)
if cached and cached[0] == mtime:
cls._preview_cache.move_to_end(path)
return cached[1]
preview = ""
try:
with open(path, "r", errors="replace") as f:
for _ in range(400):
line = f.readline()
if not line:
break
if '"user"' not in line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if record.get("type") != "user":
continue
content = (record.get("message") or {}).get("content")
if isinstance(content, list):
content = next(
(b.get("text") for b in content
if isinstance(b, dict) and b.get("type") == "text"),
None,
)
if not isinstance(content, str):
continue
text = " ".join(content.split())
# Skip the synthetic openers (command stdout, hook output,
# caveats) that would otherwise become every session's title.
if not text or text.startswith("<") or text.startswith("Caveat:"):
continue
preview = text[:70]
break
except OSError:
pass
cls._preview_cache[path] = (mtime, preview)
cls._preview_cache.move_to_end(path)
while len(cls._preview_cache) > cls._PREVIEW_CACHE_MAX:
cls._preview_cache.popitem(last=False)
return preview
def _session_dir(self, session_id: str) -> str | None:
"""Directory a past session was recorded in, or None if it's gone.
`claude --resume <id>` only finds a transcript when it is started in the
same cwd, because that is what selects the ~/.claude/projects bucket.
"""
root = os.path.join(_USER_HOME, ".claude", "projects")
try:
projects = os.listdir(root)
except OSError:
return None
for project in projects:
path = os.path.join(root, project, f"{session_id}.jsonl")
if os.path.isfile(path):
return self._session_cwd(path) or self._decode_project_dir(project)
return None
@staticmethod
def _decode_project_dir(name: str) -> str:
"""Best-effort cwd from the encoded project directory name.
Claude encodes the cwd by replacing "/" with "-", which is lossy for
paths that already contain dashes. Only used when the transcript itself
carries no cwd, so an approximate path beats showing nothing.
"""
candidate = "/" + name.lstrip("-").replace("-", "/")
if os.path.isdir(candidate):
return candidate
return candidate.rstrip("/") or "/"
@staticmethod
def _session_cwd(path: str) -> str | None:
"""cwd from the first transcript lines that carry it (usually line ~3)."""
try:
with open(path, "r", errors="replace") as f:
for _ in range(12):
line = f.readline()
if not line:
break
try:
record = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(record, dict) and record.get("cwd"):
return record["cwd"]
except OSError:
pass
return None
@staticmethod
def _live_session_ids() -> set:
"""Session ids of running ``claude`` processes owned by this user.
Live used to be keyed by cwd, which made every transcript in
/home/oliver un-resumable whenever any Claude Code was open there —
the default working directory, so Resume Session had nothing to pick.
``--session-id`` / ``--resume`` on the argv is the actual occupancy.
"""
uid = os.getuid()
ids: set[str] = set()
flags = {b"--resume", b"-r", b"--session-id"}
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
base = f"/proc/{pid}"
try:
if os.stat(base).st_uid != uid:
continue
with open(f"{base}/cmdline", "rb") as f:
argv = f.read().split(b"\0")
except OSError:
continue
# Exact match: this plugin's own backend is titled "decky-claude",
# which would otherwise match a substring test against its own cwd.
if not argv or os.path.basename(argv[0] or b"") != b"claude":
continue
for i, arg in enumerate(argv):