protonpass-tray 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,6 @@
1
+ """Unofficial tray icon and unlock prompt for the Proton Pass CLI session lock.
2
+
3
+ Not affiliated with, endorsed by, or supported by Proton AG.
4
+ """
5
+
6
+ __version__ = "0.2.0"
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,431 @@
1
+ """What the five operations actually do, with no opinion about how to talk to a person.
2
+
3
+ cli.py prints the results of these and returns their exit codes; tray.py shows them in a
4
+ dialog. Keeping them here is what makes the two front-ends the same program rather than two
5
+ programs that agree for now - and it is why the exit codes live here too: they are the
6
+ interface a shell hook branches on, so they belong next to the logic that decides them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ from . import passcli, state
14
+ from .passcli import Verdict
15
+ from .state import Lock
16
+
17
+ EXIT_OK = 0
18
+ EXIT_USAGE = 2
19
+ EXIT_UNRECOGNISED = 3
20
+ EXIT_NO_PASS_CLI = 4
21
+ EXIT_LOCKED = 10
22
+ EXIT_NO_LOCK = 11
23
+ EXIT_NO_SESSION = 12
24
+ #: pass-cli's own copy of the session disagrees with the server about the lock, and every way
25
+ #: out is gated on whichever side disagrees. Its own place in the interface because no code and
26
+ #: no retry helps: a face must stop offering the field and say what does.
27
+ EXIT_WEDGED = 13
28
+
29
+ _CODE_OF = {
30
+ Lock.UNLOCKED: EXIT_OK,
31
+ Lock.LOCKED: EXIT_LOCKED,
32
+ Lock.NO_LOCK: EXIT_NO_LOCK,
33
+ Lock.NO_SESSION: EXIT_NO_SESSION,
34
+ Lock.UNKNOWN: EXIT_UNRECOGNISED,
35
+ }
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Outcome:
40
+ exit_code: int
41
+ #: Safe to show anyone: our own words, or one line of pass-cli's. Never item content.
42
+ message: str = ""
43
+ is_error: bool = False
44
+ state: state.State | None = None
45
+
46
+ @property
47
+ def ok(self) -> bool:
48
+ return self.exit_code == EXIT_OK
49
+
50
+
51
+ def exit_code_for(status: Lock) -> int:
52
+ return _CODE_OF[status]
53
+
54
+
55
+ def status() -> state.State:
56
+ """The cached belief. Free, and asks nothing - see state.py."""
57
+ return state.load()
58
+
59
+
60
+ def refresh() -> Outcome:
61
+ """Establish the state for real. Two API calls, and it resets the idle timer.
62
+
63
+ `info` says whether a lock exists and what its timeout is, but not whether the session is
64
+ locked at this moment. So a second, harmless read - `vault list`, which prints vault names
65
+ and no secrets - is what distinguishes locked from unlocked.
66
+
67
+ THE PROBE RUNS EVEN WHEN `info` SAYS THERE IS NO LOCK, and that is not caution: on
68
+ 2026-11-11 a live session answered `info` with "Session has lock: no" while every other
69
+ call refused with "Session is locked. Please unlock your session and try again." Returning
70
+ early on `info` published "no lock configured" for hours, so every face offered the one
71
+ thing that fixes that - create a lock - which pass-cli also refuses on a locked session.
72
+ A reading that contradicts the behaviour loses to the behaviour.
73
+ """
74
+ details = passcli.info()
75
+ if details.verdict is Verdict.NO_SESSION:
76
+ st = state.record(Lock.NO_SESSION, source="pass-cli info", idle_timeout=0)
77
+ return Outcome(EXIT_NO_SESSION, st.describe(), state=st)
78
+
79
+ probe = passcli.run(["vault", "list"])
80
+ timeout = details.idle_timeout
81
+ if probe.verdict is Verdict.LOCKED:
82
+ # The source carries the contradiction when there is one: a cache saying "locked" on
83
+ # a session whose `info` denies the lock is the single most useful thing to find here
84
+ # next time, and it would otherwise be invisible.
85
+ source = "pass-cli vault list"
86
+ if details.has_lock is False:
87
+ source += " (info said no lock)"
88
+ st = state.record(Lock.LOCKED, source=source, idle_timeout=timeout)
89
+ elif probe.verdict is Verdict.NO_SESSION:
90
+ st = state.record(Lock.NO_SESSION, source="pass-cli vault list", idle_timeout=0)
91
+ elif details.has_lock is False:
92
+ st = state.record(Lock.NO_LOCK, source="pass-cli info", idle_timeout=0)
93
+ elif probe.returncode == 0:
94
+ st = state.record(Lock.UNLOCKED, source="pass-cli vault list", idle_timeout=timeout)
95
+ else:
96
+ st = state.record(Lock.UNKNOWN, source=f"pass-cli vault list: {probe.message}")
97
+ return Outcome(exit_code_for(st.status), st.describe(), state=st)
98
+
99
+
100
+ def _reconciled() -> state.State | None:
101
+ """What the session actually looks like, or None if that could not be established.
102
+
103
+ The point is the CACHE as much as the answer. An operation whose outcome cannot be read
104
+ leaves the cached state untouched, so every face reading that cache goes on offering the
105
+ operation that just failed - which is how a Plasma widget came to ask for a PIN again and
106
+ again, for a lock that no longer existed, reporting pass-cli's own prompt as the reason.
107
+
108
+ A failed second opinion must not replace the first failure, so anything it raises means
109
+ None and the caller keeps what it already knew. NotInstalled is the exception: pass-cli
110
+ went away mid-run, and cli.py has a better sentence for that than this does.
111
+ """
112
+ try:
113
+ outcome = refresh()
114
+ except passcli.NotInstalled:
115
+ raise
116
+ except Exception: # noqa: BLE001
117
+ return None
118
+ if outcome.state is None or outcome.state.status is Lock.UNKNOWN:
119
+ return None
120
+ return outcome.state
121
+
122
+
123
+ def _unreadable(said: str, fallback: str, *, unchanged: tuple[Lock, ...] = ()) -> Outcome:
124
+ """An operation whose answer could not be read: repair the cache, then answer.
125
+
126
+ Repairing the cache is unconditional and is half the point - a face reads it to decide
127
+ what to offer next. Choosing the MESSAGE is the other half, and getting that order wrong
128
+ cost an evening on 2026-11-11 in each direction. pass-cli's own sentence comes first when
129
+ there is one, because it is the most specific thing anyone knows: answering with the state
130
+ instead turned "Error locking session" into "No lock configured" - true, and no answer at
131
+ all to someone who had just asked for a lock to be created.
132
+
133
+ `unchanged` is the state, or states, the operation was trying to LEAVE. Finding the
134
+ session still in one of them says only that the operation failed, so it is no answer
135
+ either - and in particular must not become one of the exit codes that mean "here is the
136
+ state", which a face reads as an instruction to offer that same operation again.
137
+ """
138
+ st = _reconciled()
139
+ said = said.strip()
140
+ informative = st is not None and st.status not in unchanged
141
+ if informative and not said:
142
+ return Outcome(
143
+ exit_code_for(st.status),
144
+ st.describe(),
145
+ is_error=st.status is not Lock.UNLOCKED,
146
+ state=st,
147
+ )
148
+ code = exit_code_for(st.status) if informative else EXIT_UNRECOGNISED
149
+ # A failure never exits 0, whatever the state turned out to be: a shell hook branches on
150
+ # this before it reads anything.
151
+ return Outcome(code or EXIT_UNRECOGNISED, said or fallback, is_error=True, state=st)
152
+
153
+
154
+ def _timeout_for_unlock() -> int | None:
155
+ """The idle timeout to record after an unlock: None keeps what the cache already knows.
156
+
157
+ `state.record` carries the previous number forward, which is right almost always. But
158
+ after any spell where the cache believed there was no lock it carries 0, and 0 means "no
159
+ countdown" to every face: `expires_in()` returns None, so the tray's `expires_in() == 0`
160
+ inference never fires and the icon reads "unlocked" until something else refreshes it.
161
+ Found on 2026-11-11 in the cache written by the unlock that proved the lock had been there
162
+ all along - `idle_timeout: 0` on a session with a live 300s lock. One `info` call, and
163
+ only when the number is actually missing.
164
+ """
165
+ if state.load().idle_timeout:
166
+ return None
167
+ try:
168
+ return passcli.info().idle_timeout or None
169
+ except Exception: # noqa: BLE001
170
+ return None
171
+
172
+
173
+ #: What to do about it. The only route found on 2026-11-11, after lock, unlock, remove-lock and
174
+ #: create-lock had each been refused.
175
+ WEDGED = (
176
+ "pass-cli has lost the lock the server is still enforcing, so none of its lock "
177
+ "commands will run. Recover with a fresh session: pass-cli logout --force && pass-cli login"
178
+ )
179
+
180
+
181
+ def _wedged() -> Outcome | None:
182
+ """The deadlock of 2026-11-11, if that is what this is.
183
+
184
+ pass-cli answers a lock command out of its OWN copy of the session, and that copy does not
185
+ learn about a lock the SERVER engaged on idleness. Once the two disagree there is no way
186
+ through: `unlock` and `remove-lock` refuse with "Session is not locked", `lock` with
187
+ "Session has no lock", and `create-lock` with "Session is locked" - each gated by whichever
188
+ side disagrees. Six commands, no exit; only a fresh session clears it.
189
+
190
+ This program is the only thing that sees both halves, because it probes with `vault list`
191
+ AND runs the lock commands. So it is the only thing that can name the situation instead of
192
+ relaying a sentence that contradicts what the operator can see on screen.
193
+
194
+ pass-cli 2.7.1 fixed it at the source: every lock command asks the server first, and the
195
+ session file no longer lets a stale copy write the lock away. Kept, because 2.5.1 to 2.7.0
196
+ are still installed, and on 2.7.1 it costs nothing - the sentences that lead here then
197
+ carry the server's word, so the probe agrees with them and this returns None.
198
+ """
199
+ st = _reconciled()
200
+ if st is None or st.status is not Lock.LOCKED:
201
+ return None
202
+ return Outcome(EXIT_WEDGED, WEDGED, is_error=True, state=st)
203
+
204
+
205
+ def lock() -> Outcome:
206
+ result = passcli.run(["session", "lock"])
207
+ if result.verdict in (Verdict.OK, Verdict.LOCKED):
208
+ st = state.record(Lock.LOCKED, source="protonpass-tray lock")
209
+ return Outcome(EXIT_OK, st.describe(), state=st)
210
+ if result.verdict is Verdict.NO_LOCK:
211
+ if wedged := _wedged():
212
+ return wedged
213
+ st = state.record(Lock.NO_LOCK, source="protonpass-tray lock", idle_timeout=0)
214
+ return Outcome(
215
+ EXIT_NO_LOCK,
216
+ "This session has no lock yet. Run: protonpass-tray setup",
217
+ is_error=True,
218
+ state=st,
219
+ )
220
+ if result.verdict is Verdict.NO_SESSION:
221
+ return Outcome(
222
+ EXIT_NO_SESSION, "No Proton Pass session. Run: pass-cli login", is_error=True
223
+ )
224
+ return _unreadable(
225
+ result.message, "pass-cli could not lock the session", unchanged=(Lock.UNLOCKED,)
226
+ )
227
+
228
+
229
+ def unlock(code: str) -> Outcome:
230
+ result = passcli.feed_code(["session", "unlock"], code)
231
+ if result.verdict is Verdict.OK:
232
+ st = state.record(
233
+ Lock.UNLOCKED, source="protonpass-tray unlock", idle_timeout=_timeout_for_unlock()
234
+ )
235
+ return Outcome(EXIT_OK, st.describe(), state=st)
236
+ if result.verdict is Verdict.NOT_LOCKED:
237
+ # "Session is not locked" is pass-cli's LOCAL belief, and it goes stale: on 2026-11-11
238
+ # `session unlock` answered exactly that while `vault list` was being refused with
239
+ # "Session is locked" - the server had auto-locked on idleness and the client had not
240
+ # found out. Recording "unlocked" on its word is the same mistake as believing `info`,
241
+ # and it would have had every face show a green icon over a session that could not
242
+ # read a single secret. So probe, and report what the probe says. (2.7.1 says it on
243
+ # the server's word and exits 0; the probe then agrees, and this is one extra read.)
244
+ if wedged := _wedged():
245
+ return wedged
246
+ st = _reconciled()
247
+ if st is None:
248
+ st = state.record(
249
+ Lock.UNLOCKED,
250
+ source="pass-cli: was not locked",
251
+ idle_timeout=_timeout_for_unlock(),
252
+ )
253
+ return Outcome(
254
+ exit_code_for(st.status),
255
+ st.describe(),
256
+ is_error=st.status is not Lock.UNLOCKED,
257
+ state=st,
258
+ )
259
+ if result.verdict is Verdict.NO_LOCK:
260
+ if wedged := _wedged():
261
+ return wedged
262
+ st = state.record(Lock.NO_LOCK, source="protonpass-tray unlock", idle_timeout=0)
263
+ return Outcome(EXIT_NO_LOCK, "This session has no lock.", is_error=True, state=st)
264
+ if result.verdict is Verdict.WRONG_CODE:
265
+ # "Wrong code" is a guess, and the one other thing it looks like matters: an unlock
266
+ # with NO LOCK left to unlock also fails in wording this cannot read. Telling a face
267
+ # "wrong code" for that leaves it offering the same field forever, which is exactly
268
+ # what it did. So the state is re-established before the sentence is chosen.
269
+ st = _reconciled()
270
+ if st is not None and st.status is not Lock.LOCKED:
271
+ return Outcome(
272
+ exit_code_for(st.status),
273
+ st.describe(),
274
+ is_error=st.status is not Lock.UNLOCKED,
275
+ state=st,
276
+ )
277
+ return Outcome(EXIT_LOCKED, "That code was not accepted.", is_error=True, state=st)
278
+ return _unreadable(
279
+ result.message, "pass-cli could not unlock the session", unchanged=(Lock.LOCKED,)
280
+ )
281
+
282
+
283
+ def create_lock(code: str, idle_timeout: int) -> Outcome:
284
+ if not 30 <= idle_timeout <= 900:
285
+ return Outcome(
286
+ EXIT_USAGE, "--idle-timeout must be between 30 and 900 seconds", is_error=True
287
+ )
288
+ result = passcli.feed_code(
289
+ ["session", "create-lock", "--idle-timeout", str(idle_timeout)], code
290
+ )
291
+ if result.verdict is Verdict.OK:
292
+ # Established, not assumed. pass-cli answers a successful create-lock with "Session
293
+ # locked successfully" - the same sentence it uses for `session lock` - so whether
294
+ # creating a lock also ENGAGES it cannot be read off the output, and guessing
295
+ # "unlocked" would have every face cheerfully counting down a session that was already
296
+ # locked. One extra API call at setup time settles it.
297
+ outcome = refresh()
298
+ return Outcome(
299
+ EXIT_OK,
300
+ f"Lock created. The session locks itself after {idle_timeout}s unused.",
301
+ state=outcome.state,
302
+ )
303
+ if result.verdict is Verdict.HAS_LOCK:
304
+ # pass-cli 2.7.1 answers this on a LOCKED session too, where 2.5.1 said "Session is
305
+ # locked": it asks the server, which reports the lock, and stops there. "Remove it
306
+ # first" is then the wrong advice twice over - removing needs the code anyway, and a
307
+ # face reading EXIT_USAGE keeps the create form up. So find out which it is.
308
+ st = _reconciled()
309
+ if st is not None and st.status is Lock.LOCKED:
310
+ return Outcome(
311
+ EXIT_LOCKED,
312
+ "This session already has a lock, and it is locked. Unlock it first.",
313
+ is_error=True,
314
+ state=st,
315
+ )
316
+ return Outcome(
317
+ EXIT_USAGE,
318
+ "This session already has a lock. Remove it first to change the timeout.",
319
+ is_error=True,
320
+ state=st,
321
+ )
322
+ if result.verdict is Verdict.UNSUPPORTED:
323
+ return Outcome(
324
+ EXIT_USAGE,
325
+ "Personal-access-token and agent sessions cannot carry a session lock.",
326
+ is_error=True,
327
+ )
328
+ # NO_LOCK is the state create-lock was asked to change, so finding it afterwards is
329
+ # not news - it is the failure, and reporting it as the state is what sent a widget
330
+ # back to the same button that had just failed.
331
+ return _unreadable(
332
+ result.message, "pass-cli could not create the lock", unchanged=(Lock.NO_LOCK,)
333
+ )
334
+
335
+
336
+ def remove_lock(code: str) -> Outcome:
337
+ result = passcli.feed_code(["session", "remove-lock"], code)
338
+ if result.verdict is Verdict.OK:
339
+ st = state.record(Lock.NO_LOCK, source="protonpass-tray remove-lock", idle_timeout=0)
340
+ return Outcome(EXIT_OK, "Lock removed. The session is no longer gated by a code.", state=st)
341
+ if result.verdict in (Verdict.NOT_LOCKED, Verdict.NO_LOCK):
342
+ if wedged := _wedged():
343
+ return wedged
344
+ st = state.record(Lock.NO_LOCK, source="pass-cli: no lock to remove", idle_timeout=0)
345
+ return Outcome(EXIT_NO_LOCK, "This session has no lock to remove.", state=st)
346
+ if result.verdict is Verdict.WRONG_CODE:
347
+ if wedged := _wedged():
348
+ return wedged
349
+ return Outcome(EXIT_LOCKED, "That code was not accepted.", is_error=True)
350
+ # Either state means the lock is still there, so neither answers a removal.
351
+ return _unreadable(
352
+ result.message,
353
+ "pass-cli could not remove the lock",
354
+ unchanged=(Lock.LOCKED, Lock.UNLOCKED),
355
+ )
356
+
357
+
358
+ def set_timeout(code: str, idle_timeout: int) -> Outcome:
359
+ """Change how long idle is too long, keeping the same code.
360
+
361
+ pass-cli has no command for it: a lock's timeout is fixed when the lock is created, and
362
+ create-lock refuses while there is one. So this removes the lock and creates it again with
363
+ the code just given - which the server has checked by then, since it took the removal. The
364
+ one bad ending is a removal that worked and a creation that did not, and that is said in
365
+ words and never as a state: the session would otherwise stand open under a message that
366
+ reads like an ordinary refusal.
367
+
368
+ Only on an unlocked session. Whether the server lets a locked one drop its lock was never
369
+ measured, and a change of timeout must not be how anyone finds out.
370
+ """
371
+ if not 30 <= idle_timeout <= 900:
372
+ return Outcome(
373
+ EXIT_USAGE, "--idle-timeout must be between 30 and 900 seconds", is_error=True
374
+ )
375
+ before = refresh()
376
+ status = before.state.status if before.state else Lock.UNKNOWN
377
+ if status is Lock.NO_LOCK:
378
+ return Outcome(
379
+ EXIT_NO_LOCK,
380
+ "This session has no lock yet. Run: protonpass-tray setup",
381
+ is_error=True,
382
+ state=before.state,
383
+ )
384
+ if status is Lock.LOCKED:
385
+ return Outcome(
386
+ EXIT_LOCKED,
387
+ "The session is locked. Unlock it first.",
388
+ is_error=True,
389
+ state=before.state,
390
+ )
391
+ if status is not Lock.UNLOCKED:
392
+ return Outcome(before.exit_code, before.message, is_error=True, state=before.state)
393
+
394
+ removed = passcli.feed_code(["session", "remove-lock"], code)
395
+ if removed.verdict is not Verdict.OK:
396
+ st = _reconciled()
397
+ # A removal whose answer was lost still happened, and stopping there would leave the
398
+ # session with no lock at all.
399
+ if st is None or st.status is not Lock.NO_LOCK:
400
+ # Not EXIT_LOCKED: a face reads that as "here is the state" and shows nothing.
401
+ said = (
402
+ "That code was not accepted."
403
+ if removed.verdict is Verdict.WRONG_CODE
404
+ else removed.message or "pass-cli could not change the lock."
405
+ )
406
+ rest = "The lock is unchanged." if st else "Check the lock before relying on it."
407
+ return Outcome(EXIT_USAGE, f"{said} {rest}", is_error=True, state=st)
408
+
409
+ has_lock = (Lock.UNLOCKED, Lock.LOCKED)
410
+ for _attempt in range(2):
411
+ created = create_lock(code, idle_timeout)
412
+ # A creation that says it failed may have happened all the same, its answer lost. The
413
+ # session says which, and any lock on it now is the new one.
414
+ after = created.state if created.ok else _reconciled()
415
+ if after is not None and after.status in has_lock:
416
+ break
417
+ else:
418
+ st = state.record(Lock.NO_LOCK, source="protonpass-tray set-timeout", idle_timeout=0)
419
+ return Outcome(
420
+ EXIT_UNRECOGNISED,
421
+ "The lock was removed and could not be created again, so this session has NO LOCK "
422
+ f"now. Create it again. ({created.message})",
423
+ is_error=True,
424
+ state=st,
425
+ )
426
+ if after.status is Lock.LOCKED:
427
+ # It was unlocked when this began, and the code is at hand.
428
+ after = unlock(code).state
429
+ return Outcome(
430
+ EXIT_OK, f"The session now locks itself after {idle_timeout}s unused.", state=after
431
+ )
@@ -0,0 +1,178 @@
1
+ """Saying that a prompt is waiting for the lock code, so that a desktop face can tell its user.
2
+
3
+ A prompt in a terminal is easy to miss: the tab is behind another, the recipe that needs the
4
+ code was started an hour ago. While one waits, a small file in $XDG_RUNTIME_DIR says so, and
5
+ a face that reads it can raise a notification. Nothing here is an API call.
6
+
7
+ THE FILE PROVES ITSELF OR IS IGNORED. A prompt that is killed cannot take its file away, and
8
+ a notification about a prompt that is gone cannot be answered. So a waiting prompt rewrites
9
+ its file every few seconds, and a reader believes one only for STALE_S after the last write -
10
+ which needs no process table, and so works for a QML widget that can only `cat`.
11
+
12
+ WHAT IT SAYS is the program that was started, its directory's name and the terminal. Never a
13
+ command line: those carry secrets, and this text ends up in a notification.
14
+
15
+ The other direction is one empty file, `listening`, which a face that raises notifications
16
+ touches while it runs. Something with no terminal may wait for the code only while it is
17
+ fresh: with nobody to tell, waiting is a hang.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import contextlib
23
+ import json
24
+ import os
25
+ import re
26
+ import time
27
+ from pathlib import Path
28
+
29
+ #: How often a waiting prompt says it is still there, and how long that is believed. The
30
+ #: second is three of the first, so one slow write does not close a notification.
31
+ BEAT_S = 5.0
32
+ STALE_S = 15.0
33
+
34
+ #: After a wait nobody answered, how long the next one fails at once. One run of a recipe asks
35
+ #: for several secrets, and each would otherwise wait its whole time for someone who is away.
36
+ UNANSWERED_S = 300.0
37
+
38
+ #: Anything a notification server could read as markup, and control characters.
39
+ _UNSAFE = re.compile(r"[^\w .,@:/+-]")
40
+
41
+
42
+ def directory() -> Path:
43
+ runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
44
+ return Path(runtime) / "protonpass-tray" / "asking"
45
+
46
+
47
+ def _fresh(path: Path, seconds: float) -> bool:
48
+ try:
49
+ return time.time() - path.stat().st_mtime < seconds
50
+ except OSError:
51
+ return False
52
+
53
+
54
+ def listening() -> bool:
55
+ """Is there a face running that would tell its user we are waiting?"""
56
+ return _fresh(directory().parent / "listening", STALE_S)
57
+
58
+
59
+ def unanswered() -> bool:
60
+ """Has a wait just ended with nobody answering it?"""
61
+ return _fresh(directory().parent / "unanswered", UNANSWERED_S)
62
+
63
+
64
+ def went_unanswered() -> None:
65
+ with contextlib.suppress(OSError):
66
+ (directory().parent / "unanswered").touch(mode=0o600)
67
+
68
+
69
+ def _clean(text: str) -> str:
70
+ return _UNSAFE.sub("", text).strip()[:60]
71
+
72
+
73
+ def _stat(pid: int) -> tuple[str, int, int]:
74
+ """A process's name, its parent and its session, from /proc."""
75
+ raw = Path(f"/proc/{pid}/stat").read_text()
76
+ # The name is in brackets and may itself hold brackets and spaces, so from the last one.
77
+ name = raw[raw.index("(") + 1 : raw.rindex(")")]
78
+ fields = raw[raw.rindex(")") + 2 :].split()
79
+ return name, int(fields[1]), int(fields[3])
80
+
81
+
82
+ def asker() -> str:
83
+ """The program the code is wanted for: the one the shell of this terminal started.
84
+
85
+ Between it and us are the scripts that led here - `just`, a bash, another bash, us - and
86
+ the outermost is the one its user would recognise. The session leader itself is that
87
+ shell, so the walk stops below it. Empty when we were started by hand.
88
+ """
89
+ ours = os.getpid()
90
+ try:
91
+ _, parent, session = _stat(ours)
92
+ best = ""
93
+ while parent > 1 and parent != session:
94
+ name, above, its_session = _stat(parent)
95
+ if its_session != session:
96
+ break
97
+ best = name
98
+ parent = above
99
+ return _clean(best)
100
+ except (OSError, ValueError, IndexError):
101
+ return "" # no /proc, or a process that ended while we looked
102
+
103
+
104
+ def _terminal() -> str:
105
+ for fd in (0, 2):
106
+ with contextlib.suppress(OSError):
107
+ return os.ttyname(fd).removeprefix("/dev/")
108
+ return ""
109
+
110
+
111
+ def _starter() -> str:
112
+ """What started this session, for one with no terminal to name: systemd, cron, an agent."""
113
+ try:
114
+ session = os.getsid(0)
115
+ return _stat(_stat(session)[1])[0]
116
+ except (OSError, ValueError, IndexError):
117
+ return ""
118
+
119
+
120
+ def describe() -> str:
121
+ """What to call this prompt: "just in jimi-ansible (pts/47)", or "A terminal (pts/47)"."""
122
+ name = asker()
123
+ terminal = _terminal()
124
+ if name:
125
+ with contextlib.suppress(OSError):
126
+ place = _clean(os.path.basename(os.getcwd()))
127
+ name = f"{name} in {place}" if place else name
128
+ else:
129
+ name = "A terminal" if terminal else "A program"
130
+ where = _clean(terminal or _starter())
131
+ return f"{name} ({where})" if where else name
132
+
133
+
134
+ class Asking:
135
+ """A context manager: the file exists while it is open. `beat()` keeps it believed."""
136
+
137
+ def __init__(self) -> None:
138
+ self.path = directory() / f"{os.getpid()}.json"
139
+ self.since = time.time()
140
+ self.who = describe()
141
+ self._last = 0.0
142
+
143
+ def __enter__(self) -> Asking:
144
+ _prune()
145
+ self.beat()
146
+ return self
147
+
148
+ def __exit__(self, *_exc) -> None:
149
+ with contextlib.suppress(OSError):
150
+ self.path.unlink()
151
+
152
+ def beat(self) -> None:
153
+ """Say we are still here, at most every BEAT_S. Safe to call as often as one likes."""
154
+ now = time.time()
155
+ if 0 <= now - self._last < BEAT_S:
156
+ return
157
+ self._last = now
158
+ record = {"id": f"{os.getpid()}-{self.since:.3f}", "who": self.who}
159
+ record.update(since=self.since, alive=now)
160
+ # A prompt that cannot announce itself still asks.
161
+ with contextlib.suppress(OSError):
162
+ self.path.parent.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
163
+ self.path.parent.parent.chmod(0o700)
164
+ self.path.parent.mkdir(exist_ok=True, mode=0o700)
165
+ tmp = self.path.with_suffix(".tmp")
166
+ # One line each: a reader `cat`s them all at once.
167
+ tmp.write_text(json.dumps(record) + "\n")
168
+ tmp.chmod(0o600)
169
+ tmp.replace(self.path)
170
+
171
+
172
+ def _prune() -> None:
173
+ """Take away what killed prompts left. A stopped one that resumes writes its own again."""
174
+ with contextlib.suppress(OSError):
175
+ for path in directory().iterdir():
176
+ with contextlib.suppress(OSError):
177
+ if time.time() - path.stat().st_mtime > STALE_S:
178
+ path.unlink()