clawmeets-daemon 0.1.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,276 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """
3
+ clawmeets/utils/agent_processes.py
4
+
5
+ Agent discovery and process liveness on ONE machine — the single copy of the
6
+ logic that answers "which agents are set up here, and which of them are
7
+ actually running right now".
8
+
9
+ Extracted from ``cli_lifecycle.py`` because it now has two consumers that must
10
+ never disagree:
11
+
12
+ - ``clawmeets/cli_lifecycle.py`` — the ``clawmeets start / stop / status``
13
+ commands a human runs in a terminal.
14
+ - ``clawmeets_daemon/`` — the connection daemon shipped as the separate
15
+ ``clawmeets-daemon`` distribution, which reports the same facts to the
16
+ server so the web UI can show them.
17
+
18
+ The daemon is a DIFFERENT distribution and cannot import ``clawmeets`` (that
19
+ is the whole point — it must install in seconds and start even when the
20
+ runner's heavy dependency stack is broken). ``scripts/build-daemon-package.sh``
21
+ therefore copies this file verbatim into the daemon wheel as
22
+ ``clawmeets_daemon/agent_processes.py``, and ``clawmeets_daemon/discovery.py``
23
+ imports whichever copy exists. Two consequences, both load-bearing:
24
+
25
+ 1. **Stdlib only.** No ``clawmeets.*`` import, no third-party import, not even
26
+ ``typer``. Anything added here that is not in the standard library breaks
27
+ the daemon's "tiny dependencies" guarantee. Reporting is the caller's job:
28
+ the functions here return values and never print.
29
+ 2. **Public names only.** ``discovery.py`` re-exports with ``import *``, which
30
+ skips underscore-prefixed names. A helper that needs to be visible to the
31
+ daemon must not start with ``_``.
32
+
33
+ ``cli_lifecycle`` keeps its historical ``_``-prefixed aliases (``_pid_is_alive``
34
+ and friends) so existing imports and tests continue to resolve.
35
+ """
36
+ from __future__ import annotations
37
+
38
+ import os
39
+ import signal
40
+ import subprocess
41
+ import sys
42
+ import time
43
+ from pathlib import Path
44
+
45
+ IS_WINDOWS = sys.platform == "win32"
46
+
47
+ # How long a graceful stop is given before escalating to a force kill. Kept
48
+ # here rather than at the call sites so a terminal `clawmeets stop` and a
49
+ # remote stop driven from the web behave identically.
50
+ STOP_GRACE_SECONDS = 5.0
51
+ _STOP_POLL_SECONDS = 0.25
52
+
53
+
54
+ def popen_detached_kwargs() -> dict:
55
+ """Popen kwargs that detach the child so it outlives the parent shell.
56
+
57
+ Windows needs DETACHED_PROCESS (no inherited console) plus
58
+ CREATE_NEW_PROCESS_GROUP (so we can later deliver CTRL_BREAK_EVENT).
59
+ POSIX just needs start_new_session=True.
60
+ """
61
+ if IS_WINDOWS:
62
+ flags = (
63
+ getattr(subprocess, "DETACHED_PROCESS", 0)
64
+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
65
+ )
66
+ return {"creationflags": flags}
67
+ return {"start_new_session": True}
68
+
69
+
70
+ def pid_is_alive(pid: int) -> bool:
71
+ """Check whether a PID refers to a live process, without signaling it.
72
+
73
+ On Windows, ``os.kill(pid, 0)`` actually terminates the target — so we
74
+ must use a non-signaling query (tasklist) instead.
75
+ """
76
+ if IS_WINDOWS:
77
+ result = subprocess.run(
78
+ ["tasklist", "/FI", f"PID eq {pid}", "/NH", "/FO", "CSV"],
79
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
80
+ text=True, check=False,
81
+ )
82
+ return f'"{pid}"' in (result.stdout or "")
83
+ try:
84
+ os.kill(pid, 0)
85
+ return True
86
+ except (OSError, ProcessLookupError):
87
+ return False
88
+
89
+
90
+ def signal_terminate(pid: int) -> None:
91
+ """Send a graceful termination request. Silently no-ops if the target is gone.
92
+
93
+ POSIX: SIGTERM. Windows: CTRL_BREAK_EVENT to the process group (works
94
+ because agents are spawned with CREATE_NEW_PROCESS_GROUP).
95
+ """
96
+ try:
97
+ if IS_WINDOWS:
98
+ os.kill(pid, getattr(signal, "CTRL_BREAK_EVENT", 15))
99
+ else:
100
+ os.kill(pid, signal.SIGTERM)
101
+ except (OSError, ProcessLookupError):
102
+ pass
103
+
104
+
105
+ def signal_kill(pid: int) -> None:
106
+ """Force-kill a process. Silently no-ops on failure.
107
+
108
+ POSIX: SIGKILL. Windows: ``taskkill /F`` — reliable even when graceful
109
+ signaling didn't land.
110
+ """
111
+ try:
112
+ if IS_WINDOWS:
113
+ subprocess.run(
114
+ ["taskkill", "/F", "/PID", str(pid)],
115
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
116
+ check=False,
117
+ )
118
+ else:
119
+ os.kill(pid, signal.SIGKILL)
120
+ except OSError:
121
+ pass
122
+
123
+
124
+ def read_pid(pid_file: Path) -> int | None:
125
+ """The live PID recorded in ``pid_file``, or None.
126
+
127
+ None covers all three "not running" shapes with one answer: no pidfile, an
128
+ unreadable/garbage pidfile, and a pidfile naming a process that has since
129
+ died (the stale-pidfile case). Callers that need to tell the last one apart
130
+ check ``pid_file.exists()`` themselves.
131
+ """
132
+ if not pid_file.exists():
133
+ return None
134
+ try:
135
+ pid = int(pid_file.read_text().strip())
136
+ return pid if pid_is_alive(pid) else None
137
+ except (ValueError, OSError):
138
+ return None
139
+
140
+
141
+ def stop_pid(pid_file: Path) -> int | None:
142
+ """Stop the process named by ``pid_file``. Returns the PID it stopped, else None.
143
+
144
+ Graceful first (SIGTERM / CTRL_BREAK_EVENT), then a force kill after a
145
+ :data:`STOP_GRACE_SECONDS` grace period (SIGKILL / taskkill /F). The
146
+ pidfile is removed either way, including when it was already stale — that
147
+ cleanup is why a caller should prefer this over signalling by hand.
148
+
149
+ Returns None when there was nothing to stop, so a caller can distinguish
150
+ "stopped it" from "it wasn't running" without a second probe. Never prints:
151
+ the terminal CLI and the remote daemon word the outcome differently.
152
+ """
153
+ if not pid_file.exists():
154
+ return None
155
+ try:
156
+ pid = int(pid_file.read_text().strip())
157
+ except (ValueError, OSError):
158
+ pid_file.unlink(missing_ok=True)
159
+ return None
160
+
161
+ if not pid_is_alive(pid):
162
+ pid_file.unlink(missing_ok=True)
163
+ return None
164
+
165
+ signal_terminate(pid)
166
+ for _ in range(int(STOP_GRACE_SECONDS / _STOP_POLL_SECONDS)):
167
+ time.sleep(_STOP_POLL_SECONDS)
168
+ if not pid_is_alive(pid):
169
+ break
170
+ else:
171
+ signal_kill(pid)
172
+
173
+ pid_file.unlink(missing_ok=True)
174
+ return pid
175
+
176
+
177
+ def agents_dir(data_dir: Path) -> Path:
178
+ """``{data_dir}/agents`` — where every locally registered agent lives."""
179
+ return Path(data_dir).expanduser() / "agents"
180
+
181
+
182
+ def prefixed_name(username: str, agent_name: str) -> str:
183
+ """``budget-analyst`` -> ``alice-budget-analyst`` (idempotent)."""
184
+ prefix = f"{username}-"
185
+ return agent_name if agent_name.startswith(prefix) else f"{prefix}{agent_name}"
186
+
187
+
188
+ def find_agent_dir(agents_root: Path, prefixed: str) -> Path | None:
189
+ """Find an agent's directory matching ``{prefixed}-{id}/``.
190
+
191
+ Requires ``credential.json`` so a half-registered directory is invisible,
192
+ the same rule :func:`list_owned_agent_short_names` applies.
193
+ """
194
+ if not agents_root.exists():
195
+ return None
196
+ for d in agents_root.iterdir():
197
+ if d.is_dir() and d.name.startswith(f"{prefixed}-"):
198
+ if (d / "credential.json").exists():
199
+ return d
200
+ return None
201
+
202
+
203
+ def list_owned_agent_short_names(agents_root: Path, username: str) -> list[str]:
204
+ """Return owned agents' short names by globbing the filesystem.
205
+
206
+ Pattern: ``{agents_root}/{username}-{short}-{id}/`` with ``credential.json``
207
+ present. Skips ``DELETED-*`` (renamed by self-destruct) and any dir
208
+ without a ``credential.json`` (half-registered). The trailing ``-{id}``
209
+ is stripped off the right.
210
+
211
+ Deliberately a filesystem glob rather than a read of ``settings.json``:
212
+ the directory is what a process can actually be started from, so an agent
213
+ that exists on disk is reported even if some config file forgot it.
214
+ """
215
+ if not agents_root.exists():
216
+ return []
217
+ prefix = f"{username}-"
218
+ names: list[str] = []
219
+ for entry in sorted(agents_root.iterdir()):
220
+ if not entry.is_dir() or entry.name.startswith("DELETED-"):
221
+ continue
222
+ if not entry.name.startswith(prefix):
223
+ continue
224
+ if not (entry / "credential.json").exists():
225
+ continue
226
+ rest = entry.name[len(prefix):]
227
+ short = rest.rsplit("-", 1)[0] if "-" in rest else rest
228
+ if short:
229
+ names.append(short)
230
+ return names
231
+
232
+
233
+ def agent_pid_file(agent_dir: Path) -> Path:
234
+ """The pidfile ``clawmeets start`` writes for one agent."""
235
+ return Path(agent_dir) / "agent.pid"
236
+
237
+
238
+ def scan_agents(agents_root: Path, username: str) -> list[dict]:
239
+ """One dict per locally registered agent, with its OBSERVED run state.
240
+
241
+ ``[{"short_name", "name", "dir", "pid", "state"}, …]`` sorted by
242
+ ``short_name``, where ``state`` is one of:
243
+
244
+ - ``"running"`` — the pidfile names a live process.
245
+ - ``"crashed"`` — a pidfile exists but the process is gone. The machine
246
+ started this agent and it exited without being asked to; the web UI
247
+ shows it as "Stopped on its own" so the user can tell it apart from a
248
+ stop they performed.
249
+ - ``"stopped"`` — no pidfile. Never started, or stopped cleanly.
250
+
251
+ Observed, never remembered: the state is read off the filesystem on every
252
+ call, so an agent that died without saying goodbye reads as ``crashed``
253
+ within one scan rather than lingering as "running" until something notices.
254
+ """
255
+ rows: list[dict] = []
256
+ for short in list_owned_agent_short_names(agents_root, username):
257
+ full = prefixed_name(username, short)
258
+ agent_dir = find_agent_dir(agents_root, full)
259
+ if agent_dir is None:
260
+ continue
261
+ pid_file = agent_pid_file(agent_dir)
262
+ pid = read_pid(pid_file)
263
+ if pid is not None:
264
+ state = "running"
265
+ elif pid_file.exists():
266
+ state = "crashed"
267
+ else:
268
+ state = "stopped"
269
+ rows.append({
270
+ "short_name": short,
271
+ "name": full,
272
+ "dir": str(agent_dir),
273
+ "pid": pid,
274
+ "state": state,
275
+ })
276
+ return rows