pymol-hyperpowers 0.2.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.
@@ -0,0 +1,571 @@
1
+ """Usage claims: which agent conversations have selected which PyMOL session.
2
+
3
+ Each MCP server records the session it has selected in ``claims/<session_id>.<server_id>.json``
4
+ beside the session registry, and holds an exclusive ``flock`` on that file for as long as the
5
+ selection stands. The owner removes its file before closing the descriptor, so a claim file whose
6
+ lock is free belongs to a server that ended without cleaning up, and any reader removes it. See
7
+ docs/hyperpowers/specs/2026-11-23-session-usage-claims-design.md.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import atexit
13
+ import contextlib
14
+ import datetime as dt
15
+ import fcntl
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+ import threading
21
+ import time
22
+ import uuid
23
+ import weakref
24
+ from collections.abc import Callable, Iterator, Sequence
25
+ from pathlib import Path
26
+ from typing import Any, NamedTuple
27
+
28
+ from pymol_hyperpowers import plugin
29
+ from pymol_hyperpowers.types import SessionUser
30
+
31
+ CLAIMS_DIR_NAME = "claims"
32
+ TEMP_PREFIX = ".claim-"
33
+ TEMP_SUFFIX = ".tmp"
34
+ TEMP_MAX_AGE_S = 60.0
35
+ MAX_RECORD_BYTES = 65536
36
+
37
+ # Session IDs (from the plugin) and server IDs are both str(uuid.uuid4()); any other name in the
38
+ # directory is not a claim and is never touched.
39
+ _UUID4 = r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
40
+ ID_RE = re.compile(rf"^{_UUID4}$")
41
+ CLAIM_NAME_RE = re.compile(rf"^({_UUID4})\.({_UUID4})\.json$")
42
+ TEMP_NAME_RE = re.compile(rf"^{re.escape(TEMP_PREFIX)}{_UUID4}{re.escape(TEMP_SUFFIX)}$")
43
+
44
+ UNREADABLE = "another conversation (details unreadable)"
45
+ MINUTE_S = 60
46
+ HOUR_MIN = 60
47
+ DAY_H = 24
48
+
49
+
50
+ class ClaimName(NamedTuple):
51
+ """The two IDs a claim's filename carries; the filename is authoritative for both."""
52
+
53
+ session_id: str
54
+ server_id: str
55
+
56
+
57
+ class Probe(NamedTuple):
58
+ """What a probe found: ``free`` (the owner ended), ``held`` (a live owner), or ``error``."""
59
+
60
+ state: str
61
+ fd: int | None
62
+
63
+
64
+ def claims_dir() -> Path:
65
+ """The claims directory, ``state_dir() / "claims"``, a sibling of ``sessions/``."""
66
+ return plugin.state_dir() / CLAIMS_DIR_NAME
67
+
68
+
69
+ def claim_path(directory: Path, session_id: str, server_id: str) -> Path:
70
+ """The claim file for ``session_id`` owned by ``server_id``."""
71
+ return directory / f"{session_id}.{server_id}.json"
72
+
73
+
74
+ def parse_claim_name(name: str) -> ClaimName | None:
75
+ """The IDs in a claim filename, or None for any other name."""
76
+ match = CLAIM_NAME_RE.match(name)
77
+ return None if match is None else ClaimName(match[1], match[2])
78
+
79
+
80
+ def iso_utc(timestamp: float) -> str:
81
+ """``timestamp`` in the registry's ISO 8601 UTC form, such as ``2026-11-20T10:42:07.512Z``."""
82
+ moment = dt.datetime.fromtimestamp(timestamp, dt.UTC)
83
+ return f"{moment:%Y-%m-%dT%H:%M:%S}.{moment.microsecond // 1000:03d}Z"
84
+
85
+
86
+ def home_relative(directory: str) -> str:
87
+ """``directory`` with the home directory written as ``~``."""
88
+ home = str(Path.home())
89
+ if directory == home:
90
+ return "~"
91
+ if directory.startswith(home + os.sep):
92
+ return "~" + directory[len(home) :]
93
+ return directory
94
+
95
+
96
+ @contextlib.contextmanager
97
+ def probe(path: Path) -> Iterator[Probe]:
98
+ """Open ``path`` and try a shared non-blocking lock, held until the block ends.
99
+
100
+ Shared, so two readers probing at once do not mistake each other for the owner. Holding it
101
+ lets the caller remove an ended claim while no one else can lock it.
102
+
103
+ :raises FileNotFoundError: When ``path`` no longer exists.
104
+ """
105
+ try:
106
+ fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
107
+ except OSError as e:
108
+ if isinstance(e, FileNotFoundError):
109
+ raise
110
+ fd = None
111
+ if fd is None:
112
+ yield Probe("error", None)
113
+ return
114
+ try:
115
+ try:
116
+ fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
117
+ except BlockingIOError:
118
+ state = "held"
119
+ except OSError:
120
+ state = "error"
121
+ else:
122
+ state = "free"
123
+ yield Probe(state, fd)
124
+ finally:
125
+ os.close(fd) # also releases the probe's lock
126
+
127
+
128
+ def unlink_if_same(path: Path, fd: int) -> bool:
129
+ """Unlink ``path`` if it still names the file open on ``fd``.
130
+
131
+ :returns: False when ``path`` now names another file, as when its owner re-created its claim.
132
+ :raises FileNotFoundError: When ``path`` no longer exists.
133
+ """
134
+ current = path.stat()
135
+ opened = os.fstat(fd)
136
+ if (current.st_dev, current.st_ino) != (opened.st_dev, opened.st_ino):
137
+ return False
138
+ path.unlink()
139
+ return True
140
+
141
+
142
+ def read_record(fd: int) -> dict[str, Any] | None:
143
+ """The JSON object in the file open on ``fd``, or None when it is unreadable or not an object."""
144
+ chunks: list[bytes] = []
145
+ total = 0
146
+ try:
147
+ os.lseek(fd, 0, os.SEEK_SET)
148
+ while chunk := os.read(fd, 8192):
149
+ total += len(chunk)
150
+ if total > MAX_RECORD_BYTES:
151
+ return None
152
+ chunks.append(chunk)
153
+ value = json.loads(b"".join(chunks).decode("utf-8"))
154
+ except (OSError, UnicodeDecodeError, ValueError):
155
+ return None
156
+ return value if isinstance(value, dict) else None
157
+
158
+
159
+ def record_valid(name: ClaimName, record: dict[str, Any]) -> bool:
160
+ """Whether ``record`` carries the filename's IDs and the field types a claim record has."""
161
+ client = record.get("client")
162
+ pid = record.get("pid")
163
+ return (
164
+ record.get("session_id") == name.session_id
165
+ and record.get("server_id") == name.server_id
166
+ and (client is None or isinstance(client, str))
167
+ and isinstance(record.get("directory"), str)
168
+ and isinstance(pid, int)
169
+ and not isinstance(pid, bool)
170
+ and isinstance(record.get("selected_at"), str)
171
+ )
172
+
173
+
174
+ def user_from(name: ClaimName, record: dict[str, Any] | None, mtime: float | None) -> SessionUser:
175
+ """The user a live claim reports; an unusable record gives the unreadable user."""
176
+ last = None if mtime is None else iso_utc(mtime)
177
+ if record is None or not record_valid(name, record):
178
+ return SessionUser(client=None, directory=None, last_active_at=last, pid=None)
179
+ return SessionUser(
180
+ client=record["client"],
181
+ directory=home_relative(record["directory"]),
182
+ last_active_at=last,
183
+ pid=record["pid"],
184
+ )
185
+
186
+
187
+ def _read_claim(path: Path, name: ClaimName, *, own: bool) -> SessionUser | None:
188
+ """A live claim's user; None for an ended claim, which is removed, or a live claim of this server.
189
+
190
+ Every claim is probed first, this server's own included, so an own claim whose release
191
+ failed to unlink it (its lock is free) is removed like any other ended claim.
192
+ """
193
+ for _attempt in range(2):
194
+ try:
195
+ with probe(path) as probed:
196
+ if probed.state == "free" and probed.fd is not None:
197
+ if unlink_if_same(path, probed.fd):
198
+ return None
199
+ continue # its owner re-created it after the probe opened the old file
200
+ if own:
201
+ return None
202
+ if probed.fd is None:
203
+ return user_from(name, None, None)
204
+ record = read_record(probed.fd) if probed.state == "held" else None
205
+ return user_from(name, record, os.fstat(probed.fd).st_mtime)
206
+ except FileNotFoundError:
207
+ return None
208
+ except OSError:
209
+ return None if own else user_from(name, None, None)
210
+ # Re-created again during the second probe: its owner is alive.
211
+ return None if own else user_from(name, None, None)
212
+
213
+
214
+ def _remove_old_temp(path: Path, now: float) -> None:
215
+ """Remove a temp file a server killed mid-claim left, once it is old and unlocked."""
216
+ try:
217
+ if now - path.stat().st_mtime <= TEMP_MAX_AGE_S:
218
+ return
219
+ with probe(path) as probed:
220
+ if probed.state == "free" and probed.fd is not None:
221
+ unlink_if_same(path, probed.fd)
222
+ except OSError:
223
+ pass # gone already, or not ours to remove
224
+
225
+
226
+ def read_users(
227
+ own_server_id: str, directory: Path | None = None, now: float | None = None
228
+ ) -> dict[str, list[SessionUser]] | None:
229
+ """The other servers' live claims, by session ID, removing ended claims and old temp files.
230
+
231
+ :param own_server_id: This server's ID; its own live claims are not reported.
232
+ :param directory: The claims directory; defaults to ``claims_dir()``.
233
+ :param now: The time to judge temp-file age by; defaults to the current time.
234
+ :returns: An empty dict when the directory does not exist; None when it cannot be listed.
235
+ """
236
+ where = claims_dir() if directory is None else directory
237
+ try:
238
+ entries = sorted(entry.name for entry in where.iterdir())
239
+ except FileNotFoundError:
240
+ return {}
241
+ except OSError:
242
+ return None
243
+ moment = time.time() if now is None else now
244
+ users: dict[str, list[SessionUser]] = {}
245
+ for entry in entries:
246
+ name = parse_claim_name(entry)
247
+ if name is not None:
248
+ user = _read_claim(where / entry, name, own=name.server_id == own_server_id)
249
+ if user is not None:
250
+ users.setdefault(name.session_id, []).append(user)
251
+ elif TEMP_NAME_RE.match(entry):
252
+ _remove_old_temp(where / entry, moment)
253
+ return users
254
+
255
+
256
+ def user_text(user: SessionUser, *, pid: bool = False) -> str:
257
+ """One user as text, such as ``claude-code in ~/Development/foo``."""
258
+ if user.directory is None and user.pid is None:
259
+ text = UNREADABLE
260
+ else:
261
+ text = user.client or "another conversation"
262
+ if user.directory:
263
+ text += f" in {user.directory}"
264
+ if pid and user.pid is not None:
265
+ text += f" (pid {user.pid})"
266
+ return text
267
+
268
+
269
+ def users_text(users: Sequence[SessionUser], *, pid: bool = False) -> str:
270
+ """Several users joined with "and"."""
271
+ return " and ".join(user_text(user, pid=pid) for user in users)
272
+
273
+
274
+ def relative_time(iso: str | None, now: float | None = None) -> str | None:
275
+ """How long ago ``iso`` was: "just now" under a minute, then minutes, hours, days."""
276
+ if iso is None:
277
+ return None
278
+ try:
279
+ then = dt.datetime.fromisoformat(iso).timestamp()
280
+ except ValueError:
281
+ return None
282
+ seconds = max(0.0, (time.time() if now is None else now) - then)
283
+ if seconds < MINUTE_S:
284
+ return "just now"
285
+ minutes = int(seconds // MINUTE_S)
286
+ if minutes < HOUR_MIN:
287
+ return f"{minutes} min ago"
288
+ hours = minutes // HOUR_MIN
289
+ if hours < DAY_H:
290
+ return f"{hours} h ago"
291
+ days = hours // DAY_H
292
+ return "1 day ago" if days == 1 else f"{days} days ago"
293
+
294
+
295
+ def in_use_message(name: str, users: Sequence[SessionUser], now: float | None = None) -> str:
296
+ """The error automatic selection raises when other conversations use the only session."""
297
+ parts = []
298
+ for user in users:
299
+ when = relative_time(user.last_active_at, now)
300
+ parts.append(user_text(user) if when is None else f"{user_text(user)} (last active {when})")
301
+ return (
302
+ f'PyMOL session "{name}" is in use by '
303
+ + " and ".join(parts)
304
+ + f'. Call use_session("{name}") to share it, or ask the user.'
305
+ )
306
+
307
+
308
+ # This process's server ID; regenerated in a forked child, so read it at call time.
309
+ SERVER_ID = str(uuid.uuid4())
310
+
311
+ # Test seam: called after the temp claim is written and locked, just before it is renamed into place.
312
+ before_rename: Callable[[], None] | None = None
313
+
314
+
315
+ class Diagnostics:
316
+ """One stderr line per process for all claim failures; later failures print nothing."""
317
+
318
+ def __init__(self) -> None:
319
+ self.printed = False
320
+ self._lock = threading.Lock()
321
+
322
+ def warn(self, label: str, error: BaseException) -> None:
323
+ """Print the claim-failure line for session ``label`` unless one was printed already."""
324
+ with self._lock:
325
+ if self.printed:
326
+ return
327
+ self.printed = True
328
+ # The claim is advisory, so a closed pipe, a closed file (ValueError) or a missing stderr
329
+ # (None under pythonw, hence AttributeError) must not fail the caller; the attempt is spent.
330
+ try:
331
+ sys.stderr.write(
332
+ f'pymol-hyperpowers: could not record this conversation\'s use of PyMOL session "{label}" '
333
+ f"({error}); other conversations may not see it\n"
334
+ )
335
+ sys.stderr.flush()
336
+ except (OSError, ValueError, AttributeError):
337
+ pass
338
+
339
+ def _reset_in_child(self) -> None:
340
+ """In a forked child: start a new one-line budget behind a lock no other thread holds."""
341
+ # The child is a new process with its own budget. The inherited lock may be held by a thread
342
+ # that does not exist in the child, which would block every later warning forever.
343
+ self.printed = False
344
+ self._lock = threading.Lock()
345
+
346
+
347
+ DIAGNOSTICS = Diagnostics()
348
+
349
+ # Claim descriptors in this process (held, or being claimed). A child forked without exec would
350
+ # share their locks and keep an ended server's claim looking alive, so the child closes its copies.
351
+ # _fork_lock is held from just before a temp file is opened until its descriptor is in the set, and
352
+ # while one is removed and closed, so no claim descriptor exists outside the set while a fork runs.
353
+ _fork_lock = threading.Lock()
354
+ _tracked_fds: set[int] = set()
355
+ _keepers: weakref.WeakSet[ClaimKeeper] = weakref.WeakSet()
356
+
357
+
358
+ def _close_tracked(fd: int) -> None:
359
+ with _fork_lock:
360
+ _tracked_fds.discard(fd)
361
+ os.close(fd)
362
+
363
+
364
+ def _before_fork() -> None:
365
+ _fork_lock.acquire()
366
+
367
+
368
+ def _after_fork_in_parent() -> None:
369
+ _fork_lock.release()
370
+
371
+
372
+ def _after_fork_in_child() -> None:
373
+ global _fork_lock, SERVER_ID # noqa: PLW0603 - the inherited lock is held by the parent's forking thread
374
+ for fd in _tracked_fds:
375
+ with contextlib.suppress(OSError):
376
+ os.close(fd)
377
+ _tracked_fds.clear()
378
+ # The child is a separate server: sharing the parent's ID would make their claims one file, so
379
+ # each could replace the other's and readers would hide it. Keepers with an explicit ID keep it.
380
+ inherited_id = SERVER_ID
381
+ SERVER_ID = str(uuid.uuid4())
382
+ for keeper in list(_keepers):
383
+ if keeper.server_id == inherited_id:
384
+ keeper.server_id = SERVER_ID
385
+ keeper._forget_in_child() # noqa: SLF001 - module-private protocol between the handler and keepers
386
+ keeper._diagnostics._reset_in_child() # noqa: SLF001 - same protocol; a shared instance is reset twice
387
+ DIAGNOSTICS._reset_in_child() # noqa: SLF001 - same protocol
388
+ _fork_lock = threading.Lock()
389
+
390
+
391
+ os.register_at_fork(before=_before_fork, after_in_parent=_after_fork_in_parent, after_in_child=_after_fork_in_child)
392
+
393
+
394
+ def _release_all() -> None:
395
+ """Remove every claim this process holds; run at normal exit."""
396
+ for keeper in list(_keepers):
397
+ keeper.release()
398
+
399
+
400
+ atexit.register(_release_all)
401
+
402
+
403
+ class ClaimKeeper:
404
+ """This server's claim: at most one, for the session it has selected.
405
+
406
+ ``Selection`` calls it under its own lock, so selection and claim change together; the
407
+ keeper's lock guards its state against the exit handler.
408
+ """
409
+
410
+ def __init__(
411
+ self, directory: Path | None = None, server_id: str | None = None, diagnostics: Diagnostics | None = None
412
+ ) -> None:
413
+ self._directory = directory
414
+ self.server_id = SERVER_ID if server_id is None else server_id
415
+ self.client: str | None = None
416
+ self._diagnostics = DIAGNOSTICS if diagnostics is None else diagnostics
417
+ self._lock = threading.Lock()
418
+ self._fd: int | None = None
419
+ self._path: Path | None = None
420
+ self._session_id: str | None = None # the session to claim; kept after a failure for retries
421
+ self._session_name = ""
422
+ _keepers.add(self)
423
+
424
+ @property
425
+ def directory(self) -> Path:
426
+ """The claims directory, resolved when used so a changed state directory is followed."""
427
+ return claims_dir() if self._directory is None else self._directory
428
+
429
+ @property
430
+ def session_id(self) -> str | None:
431
+ """The session this keeper claims, held or waiting for a retry."""
432
+ return self._session_id
433
+
434
+ @property
435
+ def holds_claim(self) -> bool:
436
+ """Whether a claim file is held now."""
437
+ return self._fd is not None
438
+
439
+ def users(self) -> dict[str, list[SessionUser]] | None:
440
+ """The other servers' live claims, by session ID; see ``read_users``."""
441
+ return read_users(self.server_id, self.directory)
442
+
443
+ @contextlib.contextmanager
444
+ def exclusive(self, name: str) -> Iterator[bool]:
445
+ """Hold the registry lock (``sessions/.lock``), which serialises automatic selection.
446
+
447
+ :param name: The session being selected, for the diagnostic line.
448
+ :returns: (yields) Whether the lock is held. When it is not, the caller must not write a
449
+ claim: another server could be checking at the same moment.
450
+ """
451
+ sessions = self.directory.parent / "sessions"
452
+ with contextlib.ExitStack() as stack:
453
+ try:
454
+ plugin.ensure_sessions_dir(sessions)
455
+ stack.enter_context(plugin.registry_lock(sessions))
456
+ except OSError as e:
457
+ self._diagnostics.warn(name, e)
458
+ locked = False
459
+ else:
460
+ locked = True
461
+ yield locked
462
+
463
+ def claim(self, session_id: str, name: str) -> bool:
464
+ """Claim ``session_id``, releasing a claim for another session first.
465
+
466
+ :param name: The session's name, for the diagnostic line.
467
+ :returns: Whether a claim is held afterwards.
468
+ """
469
+ with self._lock:
470
+ if self._session_id == session_id and self._fd is not None:
471
+ return True
472
+ self._release_locked()
473
+ self._session_id, self._session_name = session_id, name
474
+ return self._create_or_warn_locked()
475
+
476
+ def refresh(self) -> None:
477
+ """Mark the claim active now; re-create it if its file was deleted or a claim is pending."""
478
+ with self._lock:
479
+ if self._session_id is None:
480
+ return
481
+ fd = self._fd
482
+ if fd is None:
483
+ self._create_or_warn_locked()
484
+ return
485
+ try:
486
+ if os.fstat(fd).st_nlink == 0: # someone deleted the file
487
+ self._fd = self._path = None
488
+ try:
489
+ self._create_or_warn_locked()
490
+ finally:
491
+ _close_tracked(fd)
492
+ else:
493
+ os.utime(fd)
494
+ except OSError as e:
495
+ self._diagnostics.warn(self._session_name, e)
496
+
497
+ def release(self, session_id: str | None = None) -> None:
498
+ """Remove the claim, only if it is for ``session_id`` when one is given, then close it."""
499
+ with self._lock:
500
+ if session_id is not None and self._session_id != session_id:
501
+ return
502
+ self._release_locked()
503
+ self._session_id, self._session_name = None, ""
504
+
505
+ def _create_or_warn_locked(self) -> bool:
506
+ session_id = self._session_id
507
+ if session_id is None:
508
+ return False
509
+ try:
510
+ self._create_locked(session_id)
511
+ except (OSError, ValueError) as e:
512
+ self._diagnostics.warn(self._session_name, e)
513
+ return False
514
+ return True
515
+
516
+ def _create_locked(self, session_id: str) -> None:
517
+ if not (ID_RE.match(session_id) and ID_RE.match(self.server_id)):
518
+ raise ValueError(f"session ID {session_id!r} or server ID {self.server_id!r} is not a UUID4")
519
+ directory = self.directory
520
+ if not directory.is_dir():
521
+ # Only a new directory is made private: ensure_sessions_dir also chmods, and an
522
+ # existing directory's mode is its owner's choice (and a test's setup).
523
+ plugin.ensure_sessions_dir(directory)
524
+ read_users(self.server_id, directory) # removes ended claims first, which bounds the directory
525
+ record = {
526
+ "session_id": session_id,
527
+ "server_id": self.server_id,
528
+ "client": self.client,
529
+ "directory": str(Path.cwd()),
530
+ "pid": os.getpid(),
531
+ "selected_at": plugin.utc_timestamp(),
532
+ }
533
+ data = (json.dumps(record, indent=2) + "\n").encode("utf-8")
534
+ temp = directory / f"{TEMP_PREFIX}{uuid.uuid4()}{TEMP_SUFFIX}"
535
+ final = claim_path(directory, session_id, self.server_id)
536
+ with _fork_lock:
537
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
538
+ _tracked_fds.add(fd)
539
+ try:
540
+ with open(fd, "wb", closefd=False) as handle: # writes through the held descriptor
541
+ handle.write(data)
542
+ fcntl.flock(fd, fcntl.LOCK_EX)
543
+ if before_rename is not None:
544
+ before_rename()
545
+ temp.rename(final)
546
+ except BaseException:
547
+ with contextlib.suppress(OSError):
548
+ temp.unlink()
549
+ _close_tracked(fd)
550
+ raise
551
+ self._fd, self._path = fd, final
552
+
553
+ def _release_locked(self) -> None:
554
+ fd, path = self._fd, self._path
555
+ self._fd = self._path = None
556
+ if fd is None or path is None:
557
+ return
558
+ try:
559
+ unlink_if_same(path, fd) # never removes a file at our path that is not ours
560
+ except FileNotFoundError:
561
+ pass
562
+ except OSError as e:
563
+ self._diagnostics.warn(self._session_name, e)
564
+ finally:
565
+ _close_tracked(fd)
566
+
567
+ def _forget_in_child(self) -> None:
568
+ """In a forked child: drop the inherited claim without touching the parent's file."""
569
+ self._fd = self._path = None
570
+ self._session_id, self._session_name = None, ""
571
+ self._lock = threading.Lock()