workcrew 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.
- workcrew/__init__.py +1 -0
- workcrew/__main__.py +6 -0
- workcrew/board.py +555 -0
- workcrew/cli.py +2340 -0
- workcrew/harness/__init__.py +51 -0
- workcrew/harness/claude.py +523 -0
- workcrew/harness/claude_screen.py +84 -0
- workcrew/link.py +1061 -0
- workcrew/notes/leader.md +21 -0
- workcrew/notes/worker.md +5 -0
- workcrew/picker.py +107 -0
- workcrew/place.py +97 -0
- workcrew/prompt.py +386 -0
- workcrew/reconcile.py +411 -0
- workcrew/send.py +244 -0
- workcrew/state.py +516 -0
- workcrew/tmux.py +992 -0
- workcrew/width.py +30 -0
- workcrew-0.1.0.dist-info/METADATA +173 -0
- workcrew-0.1.0.dist-info/RECORD +23 -0
- workcrew-0.1.0.dist-info/WHEEL +4 -0
- workcrew-0.1.0.dist-info/entry_points.txt +2 -0
- workcrew-0.1.0.dist-info/licenses/LICENSE +18 -0
workcrew/reconcile.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"""Wanted state to tmux: starting and stopping members, exits, strays, placement."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import os
|
|
7
|
+
import signal
|
|
8
|
+
import subprocess
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from importlib import resources
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from workcrew import board, harness, link, place
|
|
15
|
+
from workcrew.board import Activity
|
|
16
|
+
from workcrew.state import (
|
|
17
|
+
Member,
|
|
18
|
+
Notice,
|
|
19
|
+
Refused,
|
|
20
|
+
Roster,
|
|
21
|
+
crash_point,
|
|
22
|
+
note,
|
|
23
|
+
save,
|
|
24
|
+
shown,
|
|
25
|
+
write_if_changed,
|
|
26
|
+
)
|
|
27
|
+
from workcrew.tmux import STATE_HOOKS, Gone, Lay, PaneView, Server, ServerView, conf_text
|
|
28
|
+
|
|
29
|
+
POLLER = "_link"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def laid_out(
|
|
33
|
+
view: ServerView, r: Roster, size: tuple[int, int] | None = None
|
|
34
|
+
) -> tuple[place.Side, tuple[place.Cell, ...]]:
|
|
35
|
+
"""The window as reconcile will lay it out, at `size` or the window's. The line a command
|
|
36
|
+
prints comes from here too, so it cannot describe a layout that was never made: only a
|
|
37
|
+
member with a pane is placed, and only the leader with one is given its own column."""
|
|
38
|
+
panes = {p.member for p in view.panes if p.member is not None}
|
|
39
|
+
owners = sum(1 for p in view.panes if p.member is None and p.team_window)
|
|
40
|
+
return place.plan(
|
|
41
|
+
*(size or (view.width, view.height)),
|
|
42
|
+
r.side,
|
|
43
|
+
[m.id for m in r.workers() if m.id in panes],
|
|
44
|
+
owners,
|
|
45
|
+
"leader" in panes,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def activity(view: ServerView, r: Roster) -> dict[str, Activity]:
|
|
50
|
+
panes = {p.member: p for p in view.panes if p.member is not None}
|
|
51
|
+
out: dict[str, Activity] = {}
|
|
52
|
+
for m in r.members:
|
|
53
|
+
p = panes.get(m.id)
|
|
54
|
+
if p is None:
|
|
55
|
+
# The started mark outlives the pane: a member whose pane closed has run, and taking
|
|
56
|
+
# it for one that never did would start it again on every pass. The owner's stop
|
|
57
|
+
# outlives the server.
|
|
58
|
+
out[m.id] = "exited" if m.id in view.started or m.stopping else "not-started"
|
|
59
|
+
elif p.dead:
|
|
60
|
+
out[m.id] = "exited"
|
|
61
|
+
elif p.state == "wait":
|
|
62
|
+
out[m.id] = "wait"
|
|
63
|
+
elif p.state == "busy":
|
|
64
|
+
out[m.id] = "busy"
|
|
65
|
+
else:
|
|
66
|
+
out[m.id] = "idle"
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _exit_text(d: Path, name: str, mid: str, pane: PaneView | None) -> str:
|
|
71
|
+
t = board.held(d, mid)
|
|
72
|
+
holds = f"it holds T{t.id}" if t else "it holds no task"
|
|
73
|
+
# remain-on-exit failed: only a failure leaves a dead pane; a clean exit closes it.
|
|
74
|
+
if pane is not None:
|
|
75
|
+
status = "unknown" if pane.status is None else pane.status
|
|
76
|
+
text = f"{name} exited with status {status} (not removed); {holds}"
|
|
77
|
+
# Only for a worker with a task: given the command, leaders brought back idle workers
|
|
78
|
+
# too (left alone 2 in 5, against 5 in 5 without it).
|
|
79
|
+
return text + (f"; `workcrew resume {name}` brings it back" if t else "")
|
|
80
|
+
text = f"{name} exited normally (not removed); {holds}; leave it unless your owner asks"
|
|
81
|
+
return text + (f", or `workcrew board back {t.id}` to free the task" if t else "")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def up(server: Server) -> ServerView | None:
|
|
85
|
+
"""The server's view while the team is up: a member's pane is on it. The owner's own panes
|
|
86
|
+
keep a server alive after `exit`, and that team is stopped."""
|
|
87
|
+
if not server.alive():
|
|
88
|
+
return None
|
|
89
|
+
try:
|
|
90
|
+
view = server.view()
|
|
91
|
+
except Gone: # it exited since `alive`
|
|
92
|
+
return None
|
|
93
|
+
return view if any(p.member not in (None, POLLER) for p in view.panes) else None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _bring_up(d: Path, r: Roster, server: Server, view: ServerView, linked: bool) -> bool:
|
|
97
|
+
"""What a command's save asks of the server: the team's name, the poller while a link is
|
|
98
|
+
on record, a member that has never started. Commands only save, so a command killed after
|
|
99
|
+
its save leaves nothing this pass does not finish. True if it started a member."""
|
|
100
|
+
if view.team != r.name:
|
|
101
|
+
conf = d / "tmux.conf"
|
|
102
|
+
write_if_changed(conf, conf_text(r.name).encode())
|
|
103
|
+
server.setup(str(conf), server.bin())
|
|
104
|
+
# A dead poller counts: its pane-died hook runs this pass, so restarting it here would
|
|
105
|
+
# restart a poller that fails on every pass without end. An owner's command restarts it.
|
|
106
|
+
if linked and not any(p.member == POLLER for p in view.panes):
|
|
107
|
+
# The poller is no member: it is never started, exited or told of. Before any start,
|
|
108
|
+
# which marks its members started: the poller's spawn writes this view's marks.
|
|
109
|
+
server.spawn([server.bin(), "_linkwatch"], r.cwd, POLLER, view.started, view.exited)
|
|
110
|
+
act = activity(view, r)
|
|
111
|
+
# Never started: not on this server and never said hello. After a server restart every
|
|
112
|
+
# member is not-started on it, and only the ones named by the command start. Never a dead
|
|
113
|
+
# one: every death fires a hook that runs this pass, so it would restart without end.
|
|
114
|
+
want = [m.id for m in r.members if act[m.id] == "not-started" and m.inbox is None]
|
|
115
|
+
return len(start(d, r, server, want, server.bin(), boots=False)) < len(want)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def reconcile(
|
|
119
|
+
d: Path, r: Roster, server: Server, how: Lay = "join", size: tuple[int, int] | None = None
|
|
120
|
+
) -> list[Notice]:
|
|
121
|
+
"""`how` the team window is laid out (Server.apply); at `size`, if given, for a window about
|
|
122
|
+
to take it. The arrangement it leaves is saved when it changed, for the next start."""
|
|
123
|
+
view = up(server)
|
|
124
|
+
if view is None:
|
|
125
|
+
return []
|
|
126
|
+
ids = {m.id for m in r.members}
|
|
127
|
+
# The poller exists exactly while a link is on record.
|
|
128
|
+
linked = bool(link.relays(d))
|
|
129
|
+
strays = [
|
|
130
|
+
p
|
|
131
|
+
for p in view.panes
|
|
132
|
+
if p.member is not None and p.member not in ids and (p.member != POLLER or not linked)
|
|
133
|
+
]
|
|
134
|
+
for p in strays:
|
|
135
|
+
# One that closed by itself since the view was read needs no killing, and the others
|
|
136
|
+
# still do: the caller's own change is already saved.
|
|
137
|
+
with contextlib.suppress(Gone):
|
|
138
|
+
server.kill_pane(p.id)
|
|
139
|
+
if strays:
|
|
140
|
+
# The last pane takes the server with it, and the command that asked for this has
|
|
141
|
+
# already done what it came to do.
|
|
142
|
+
remaining = up(server)
|
|
143
|
+
if remaining is None:
|
|
144
|
+
return []
|
|
145
|
+
view = remaining
|
|
146
|
+
try:
|
|
147
|
+
if _bring_up(d, r, server, view, linked):
|
|
148
|
+
view = server.view()
|
|
149
|
+
except Gone: # it ended: as with none at the start, nothing is left to do
|
|
150
|
+
return []
|
|
151
|
+
except Refused: # the folder is gone, so nothing starts; the rest of the pass still holds
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
act = activity(view, r)
|
|
155
|
+
notices: list[Notice] = []
|
|
156
|
+
# A live member keeps an exited mark: `start` drops the mark of every member it starts, so
|
|
157
|
+
# one still running with it is being stopped, and its death is no exit to tell. A member
|
|
158
|
+
# started any other way keeps its old mark, and its exits are never told. One the owner
|
|
159
|
+
# stopped is no exit either, on a server that holds no mark of it.
|
|
160
|
+
exited = {mid for mid, a in act.items() if a == "exited"} | (view.exited & ids)
|
|
161
|
+
panes = {p.member: p for p in view.panes if p.member is not None}
|
|
162
|
+
gone = [m for m in r.workers() if m.id in exited and m.id not in view.exited and not m.stopping]
|
|
163
|
+
notices += [Notice("leader", _exit_text(d, m.name, m.id, panes.get(m.id))) for m in gone]
|
|
164
|
+
if gone:
|
|
165
|
+
notices += board.ready_notices(d, [m.id for m in r.workers()], act)
|
|
166
|
+
|
|
167
|
+
_, cells = laid_out(view, r, size)
|
|
168
|
+
# A pane that closes during the pass fires its own hook, whose reconcile lays out again.
|
|
169
|
+
with contextlib.suppress(Gone):
|
|
170
|
+
h = harness.get(r.members[0].harness)
|
|
171
|
+
server.apply(view, cells, how, r.arrangement, (h.kept_columns, h.rows))
|
|
172
|
+
for m in r.members:
|
|
173
|
+
shown = panes.get(m.id)
|
|
174
|
+
if shown is not None and shown.name != m.name:
|
|
175
|
+
server.set_name(shown.id, m.name)
|
|
176
|
+
kept = server.arrangement()
|
|
177
|
+
# A window that a stop is closing is no arrangement anyone made: a stop killed half way
|
|
178
|
+
# leaves its members stopping, and their passes would save what is left.
|
|
179
|
+
if kept is not None and kept != r.arrangement and not any(m.stopping for m in r.members):
|
|
180
|
+
r.arrangement = kept
|
|
181
|
+
save(d, r)
|
|
182
|
+
# A server that ended during the pass took its marks with it.
|
|
183
|
+
with contextlib.suppress(Gone):
|
|
184
|
+
# Last: once marked, an exit is never told again, so nothing may fail after the mark.
|
|
185
|
+
# Only a change: setting an option repaints every attached client.
|
|
186
|
+
if exited != view.exited:
|
|
187
|
+
server.set_marks(view.started, exited)
|
|
188
|
+
return notices
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# The probe checks the user manager, the bus and a delegated memory controller in one call:
|
|
192
|
+
# with any of them missing, memory.max does not exist or differs from the cap it set.
|
|
193
|
+
_PROBE = [
|
|
194
|
+
"systemd-run",
|
|
195
|
+
"--user",
|
|
196
|
+
"--scope",
|
|
197
|
+
"--quiet",
|
|
198
|
+
"-p",
|
|
199
|
+
"MemoryMax=64M",
|
|
200
|
+
"-p",
|
|
201
|
+
"MemorySwapMax=0",
|
|
202
|
+
"-p",
|
|
203
|
+
"Delegate=yes",
|
|
204
|
+
"--",
|
|
205
|
+
"sh",
|
|
206
|
+
"-c",
|
|
207
|
+
"cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max",
|
|
208
|
+
]
|
|
209
|
+
# Delegate=yes, not OOMPolicy=continue: scopes accept OOMPolicy only from systemd 253, and with
|
|
210
|
+
# Delegate on it defaults to continue, so a job killed at the cap leaves the member running.
|
|
211
|
+
_SCOPE = [
|
|
212
|
+
"systemd-run",
|
|
213
|
+
"--user",
|
|
214
|
+
"--scope",
|
|
215
|
+
"--quiet",
|
|
216
|
+
"-p",
|
|
217
|
+
"MemoryMax=50%",
|
|
218
|
+
"-p",
|
|
219
|
+
"MemorySwapMax=0",
|
|
220
|
+
"-p",
|
|
221
|
+
"Delegate=yes",
|
|
222
|
+
"--",
|
|
223
|
+
]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cap_ok() -> bool:
|
|
227
|
+
# Off Linux there is no systemd-run to find.
|
|
228
|
+
try:
|
|
229
|
+
out = subprocess.run(_PROBE, capture_output=True, text=True, check=False)
|
|
230
|
+
except OSError:
|
|
231
|
+
return False
|
|
232
|
+
return out.stdout.strip() == str(64 * 1024 * 1024)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _note(r: Roster, m: Member) -> str:
|
|
236
|
+
names = r.names()
|
|
237
|
+
if m.id == "leader":
|
|
238
|
+
workers = (
|
|
239
|
+
", ".join(names[w.id] for w in r.workers()) or "none yet (`workcrew add` adds them)"
|
|
240
|
+
)
|
|
241
|
+
text = resources.files("workcrew.notes").joinpath("leader.md").read_text()
|
|
242
|
+
return text.format(NAME="workcrew", cwd=r.cwd, workers=workers)
|
|
243
|
+
others = ", ".join(names[w.id] for w in r.workers() if w.id != m.id) or "none"
|
|
244
|
+
text = resources.files("workcrew.notes").joinpath("worker.md").read_text()
|
|
245
|
+
return text.format(NAME="workcrew", cwd=r.cwd, member=m.name, others=others)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def need_folder(d: Path, r: Roster) -> None:
|
|
249
|
+
"""tmux starts a pane whose folder is gone in another folder, so a member would run in a
|
|
250
|
+
folder nobody chose."""
|
|
251
|
+
if not Path(r.cwd).is_dir():
|
|
252
|
+
raise Refused(
|
|
253
|
+
f"team {r.name}'s folder {shown(Path(r.cwd))} is gone; its state is in {shown(d)}."
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def start(
|
|
258
|
+
d: Path,
|
|
259
|
+
r: Roster,
|
|
260
|
+
server: Server,
|
|
261
|
+
members: Sequence[str],
|
|
262
|
+
bin: str,
|
|
263
|
+
*,
|
|
264
|
+
boots: bool,
|
|
265
|
+
again: bool = False,
|
|
266
|
+
) -> list[str]:
|
|
267
|
+
"""Starts `members`, but in a folder Claude Code does not trust yet only the leader: every
|
|
268
|
+
member would raise its own trust dialog. Returns those held back. Only an owner's command
|
|
269
|
+
`boots` a server that is gone: one booted by a member's command or a hook's would give
|
|
270
|
+
every member that caller's environment."""
|
|
271
|
+
need_folder(d, r)
|
|
272
|
+
held = (
|
|
273
|
+
[]
|
|
274
|
+
if harness.get(r.members[0].harness).trusted(Path(r.cwd))
|
|
275
|
+
else [m for m in members if m != "leader"]
|
|
276
|
+
)
|
|
277
|
+
members = [m for m in members if m not in held]
|
|
278
|
+
if not members:
|
|
279
|
+
return held
|
|
280
|
+
conf = d / "tmux.conf"
|
|
281
|
+
write_if_changed(conf, conf_text(r.name).encode())
|
|
282
|
+
scope = _SCOPE if r.cap and cap_ok() else []
|
|
283
|
+
# `alive()`, not `up()`: a stopped team's server, kept by the owner's pane, is started into;
|
|
284
|
+
# booting it fails, its session already being there.
|
|
285
|
+
view = server.view() if server.alive() else None
|
|
286
|
+
if view is not None:
|
|
287
|
+
server.setup(str(conf), bin)
|
|
288
|
+
panes = {p.member: p for p in view.panes} if view is not None else {}
|
|
289
|
+
started = set(view.started) if view is not None else set()
|
|
290
|
+
exited = set(view.exited) if view is not None else set()
|
|
291
|
+
by_id = {m.id: m for m in r.members}
|
|
292
|
+
# What runs on the server this pass read or started members on. If that server ends, a new
|
|
293
|
+
# one holds none of it, so the pass starts again from the new one, once. One the owner
|
|
294
|
+
# stopped stays stopped.
|
|
295
|
+
ran = [m for m, q in panes.items() if m in by_id and not q.dead and not by_id[m].stopping]
|
|
296
|
+
for mid in members:
|
|
297
|
+
p = panes.get(mid)
|
|
298
|
+
if p is not None and not p.dead:
|
|
299
|
+
continue
|
|
300
|
+
m = by_id[mid]
|
|
301
|
+
h = harness.get(m.harness)
|
|
302
|
+
# Rewriting a file a running member reads fails with EBUSY inside its sandbox.
|
|
303
|
+
write_if_changed(d / "settings.json", h.payload(STATE_HOOKS, bin))
|
|
304
|
+
write_if_changed(note(d, mid), _note(r, m).encode())
|
|
305
|
+
argv = [*scope, bin, "_exec", r.key, mid]
|
|
306
|
+
started.add(mid)
|
|
307
|
+
exited.discard(mid)
|
|
308
|
+
# In place: killing a dead pane that is the server's last ends the server, and the
|
|
309
|
+
# owner's client with it.
|
|
310
|
+
if p is not None:
|
|
311
|
+
try:
|
|
312
|
+
server.respawn(p.id, argv, r.cwd, started, exited)
|
|
313
|
+
except Gone: # the dead pane closed since the view: started as if it had none
|
|
314
|
+
p = None
|
|
315
|
+
if p is None and (server.alive() or not boots):
|
|
316
|
+
server.spawn(argv, r.cwd, mid, started, exited) # on a gone server, Gone
|
|
317
|
+
elif p is None:
|
|
318
|
+
# Begun again, a pass that must boot has lost a second server, whether it read that
|
|
319
|
+
# server or found it already gone.
|
|
320
|
+
if again:
|
|
321
|
+
raise Gone(
|
|
322
|
+
"the team's tmux server stopped twice while its members were starting.\n"
|
|
323
|
+
# Its key: `resume` finds its team by the folder, and a name can be two teams'.
|
|
324
|
+
f"Run `workcrew -r {r.key}` to start them."
|
|
325
|
+
)
|
|
326
|
+
server.boot(str(conf), bin, argv, r.cwd, mid)
|
|
327
|
+
if view is not None or ran:
|
|
328
|
+
again_for = list(dict.fromkeys([*members, *ran]))
|
|
329
|
+
return [*held, *start(d, r, server, again_for, bin, boots=True, again=True)]
|
|
330
|
+
ran.append(mid)
|
|
331
|
+
crash_point("reconcile.start")
|
|
332
|
+
return held
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def restart_poller(d: Path, r: Roster, server: Server) -> None:
|
|
336
|
+
"""In place, as `start` restarts a dead member's pane: an owner's command does this, never a
|
|
337
|
+
hook's reconcile."""
|
|
338
|
+
view = up(server)
|
|
339
|
+
if view is None or not link.relays(d):
|
|
340
|
+
return
|
|
341
|
+
for p in view.panes:
|
|
342
|
+
if p.member == POLLER and p.dead:
|
|
343
|
+
# A pane that closed since the view leaves no poller, and the reconcile that follows
|
|
344
|
+
# every owner's command starts one.
|
|
345
|
+
with contextlib.suppress(Gone):
|
|
346
|
+
server.respawn(p.id, [server.bin(), "_linkwatch"], r.cwd, view.started, view.exited)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def stop_members(server: Server, members: Sequence[str]) -> None:
|
|
350
|
+
"""Ends these members' sessions so that the start which follows begins them again: `start`
|
|
351
|
+
skips a member whose pane is alive. The roster has them `stopping` before this first signal,
|
|
352
|
+
so no pass tells anyone they exited."""
|
|
353
|
+
with contextlib.suppress(Gone): # the server ended, so their sessions did too
|
|
354
|
+
for p in server.view().panes:
|
|
355
|
+
if p.member in members and p.pid is not None:
|
|
356
|
+
with contextlib.suppress(ProcessLookupError):
|
|
357
|
+
os.kill(p.pid, signal.SIGTERM)
|
|
358
|
+
deadline = time.monotonic() + 8
|
|
359
|
+
while time.monotonic() < deadline and not _ended(server, members):
|
|
360
|
+
time.sleep(0.1)
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _ended(server: Server, members: Sequence[str]) -> bool:
|
|
364
|
+
"""Their panes are dead or closed, which is what `start` reads before it respawns one: a pane
|
|
365
|
+
whose process tmux has not reaped yet is still a live pane."""
|
|
366
|
+
panes = {p.member: p for p in server.view().panes}
|
|
367
|
+
return all(m not in panes or panes[m].dead for m in members)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def stop(server: Server, view: ServerView) -> int:
|
|
371
|
+
"""`view` is the command's, read under the lock that every start of a member holds."""
|
|
372
|
+
# Every tagged pane, not only the roster's: a remove killed before its reconcile leaves one.
|
|
373
|
+
ours = [p for p in view.panes if p.member is not None]
|
|
374
|
+
# The server can end at any step: since the command's read, or with its last pane.
|
|
375
|
+
with contextlib.suppress(Gone):
|
|
376
|
+
# Marked before the first signal: a crash mid-stop must not make the next reconcile tell
|
|
377
|
+
# the owner's stop as exits.
|
|
378
|
+
server.set_marks(
|
|
379
|
+
view.started, view.exited | {p.member for p in ours if p.member not in (None, POLLER)}
|
|
380
|
+
)
|
|
381
|
+
alive = {p.pid for p in ours if p.pid is not None}
|
|
382
|
+
for pid in alive:
|
|
383
|
+
# The pane's process may already be gone between the view and the signal.
|
|
384
|
+
with contextlib.suppress(ProcessLookupError):
|
|
385
|
+
os.kill(pid, signal.SIGTERM)
|
|
386
|
+
deadline = time.monotonic() + 8
|
|
387
|
+
while alive and time.monotonic() < deadline:
|
|
388
|
+
time.sleep(0.1)
|
|
389
|
+
alive = {pid for pid in alive if _running(pid)}
|
|
390
|
+
for p in ours:
|
|
391
|
+
# A member that answers SIGTERM by exiting 0 closes its own pane, since a pane is
|
|
392
|
+
# kept only when it failed. Gone by the time we reach it is gone.
|
|
393
|
+
with contextlib.suppress(Gone):
|
|
394
|
+
server.kill_pane(p.id)
|
|
395
|
+
crash_point("reconcile.stop")
|
|
396
|
+
# The owner's panes keep the server: with the members gone its marks go too, or the
|
|
397
|
+
# next team in this folder would take them for its own.
|
|
398
|
+
if server.alive():
|
|
399
|
+
server.set_marks((), ())
|
|
400
|
+
return sum(1 for p in server.view().panes if p.member is None)
|
|
401
|
+
# The server exited, and its marks with it.
|
|
402
|
+
server.wait_exit(view.socket_path)
|
|
403
|
+
return 0
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _running(pid: int) -> bool:
|
|
407
|
+
try:
|
|
408
|
+
os.kill(pid, 0)
|
|
409
|
+
except ProcessLookupError:
|
|
410
|
+
return False
|
|
411
|
+
return True
|
workcrew/send.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""The two delivery paths: the owner's text typed into panes; everything else by the inbox."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Container, Sequence
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Literal
|
|
7
|
+
|
|
8
|
+
from workcrew import harness
|
|
9
|
+
from workcrew.harness import Screen
|
|
10
|
+
from workcrew.state import Member, Notice, Roster
|
|
11
|
+
from workcrew.tmux import Gone, Server
|
|
12
|
+
|
|
13
|
+
# The owner's line names this wait: "did not show the text within 2 s".
|
|
14
|
+
_SHOWN_WITHIN = 2.0
|
|
15
|
+
# Claude Code 2.1.332 replaced the input box with a slash command's picker 14-26 ms after Enter;
|
|
16
|
+
# 0.4 s is a margin over that measurement, not a measurement.
|
|
17
|
+
_AFTER_ENTER = 0.4
|
|
18
|
+
|
|
19
|
+
# Why Enter was not pressed: the screen the text met, or a dialog that opened before it showed.
|
|
20
|
+
Held = Screen | Literal["prompt-unseen", "dialog-unseen", "picker-unseen"]
|
|
21
|
+
|
|
22
|
+
_TYPABLE: frozenset[Screen] = frozenset({"empty", "busy"}) # a busy member queues the line
|
|
23
|
+
_OPENED: frozenset[Screen] = frozenset({"dialog", "picker"})
|
|
24
|
+
|
|
25
|
+
_SKIPPED = {
|
|
26
|
+
"dialog": "{} has a dialog open, so nothing was typed there. "
|
|
27
|
+
"Answer it in its pane, then send again.",
|
|
28
|
+
"picker": "{} has a dialog open, so nothing was typed there. "
|
|
29
|
+
"Answer it in its pane, then send again.",
|
|
30
|
+
"prompt": "{} is waiting on a permission prompt, so nothing was typed there. "
|
|
31
|
+
"Answer it in its pane, then send again.",
|
|
32
|
+
"draft": "{} already has text in its input box, so nothing was typed there. "
|
|
33
|
+
"Clear it in its pane, then send again.",
|
|
34
|
+
"copy-mode": "{} is scrolled back in copy mode, so nothing was typed there. "
|
|
35
|
+
"Press q in its pane, then send again.",
|
|
36
|
+
"not-running": "{} is not running, so nothing was typed there. Bring it back with `{resume}`.",
|
|
37
|
+
}
|
|
38
|
+
_SMALL = (
|
|
39
|
+
"{}'s pane is {} columns by {} rows, too small to read, so nothing was typed there. "
|
|
40
|
+
"Make the window larger or zoom the pane, then send again."
|
|
41
|
+
)
|
|
42
|
+
# the text was pasted, but Enter was not pressed
|
|
43
|
+
_HELD = {
|
|
44
|
+
"empty": "{} did not show the text within 2 s, so Enter was not pressed. "
|
|
45
|
+
"Look at its pane: the text may be in its input box.",
|
|
46
|
+
"busy": "{} did not show the text within 2 s, so Enter was not pressed. "
|
|
47
|
+
"Look at its pane: the text may be in its input box.",
|
|
48
|
+
"prompt": "{} opened a permission prompt after the text was pasted, so Enter was not pressed. "
|
|
49
|
+
"Answer it in its pane; the text is still in its input box.",
|
|
50
|
+
"dialog": "{} opened a dialog after the text was pasted, so Enter was not pressed. "
|
|
51
|
+
"Answer it in its pane; the text is still in its input box.",
|
|
52
|
+
"picker": "{} opened a dialog after the text was pasted, so Enter was not pressed. "
|
|
53
|
+
"Answer it in its pane; the text is still in its input box.",
|
|
54
|
+
# opened before the text showed: it may never have reached the box
|
|
55
|
+
"prompt-unseen": "{} opened a permission prompt as the text was pasted, so Enter was not "
|
|
56
|
+
"pressed. Answer it in its pane, then look at its input box: the text may not have reached it.",
|
|
57
|
+
"dialog-unseen": "{} opened a dialog as the text was pasted, so Enter was not pressed. "
|
|
58
|
+
"Answer it in its pane, then look at its input box: the text may not have reached it.",
|
|
59
|
+
"picker-unseen": "{} opened a dialog as the text was pasted, so Enter was not pressed. "
|
|
60
|
+
"Answer it in its pane, then look at its input box: the text may not have reached it.",
|
|
61
|
+
}
|
|
62
|
+
_UNSEEN: dict[Screen, Held] = {
|
|
63
|
+
"prompt": "prompt-unseen",
|
|
64
|
+
"dialog": "dialog-unseen",
|
|
65
|
+
"picker": "picker-unseen",
|
|
66
|
+
}
|
|
67
|
+
_NOW_OPEN = {
|
|
68
|
+
"picker": "{} now has a picker open: answer it in its pane.",
|
|
69
|
+
"dialog": "{} now has a dialog open: answer it in its pane.",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Typed:
|
|
75
|
+
done: list[str]
|
|
76
|
+
skipped: list[tuple[str, Screen | Literal["not-running", "copy-mode"]]]
|
|
77
|
+
opened: list[tuple[str, Screen]]
|
|
78
|
+
held: list[tuple[str, Held]]
|
|
79
|
+
stopped: list[str] = field(default_factory=list) # not reached: the team's server had ended
|
|
80
|
+
small: list[tuple[str, int, int]] = field(default_factory=list) # its columns and rows
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def type_to(server: Server, targets: Sequence[tuple[Member, str | None]], text: str) -> Typed:
|
|
84
|
+
"""Type `text` into each member's pane in turn; a pane of None: the member is not running."""
|
|
85
|
+
done: list[str] = []
|
|
86
|
+
skipped: list[tuple[str, Screen | Literal["not-running", "copy-mode"]]] = []
|
|
87
|
+
opened: list[tuple[str, Screen]] = []
|
|
88
|
+
held: list[tuple[str, Held]] = []
|
|
89
|
+
stopped: list[str] = []
|
|
90
|
+
small: list[tuple[str, int, int]] = []
|
|
91
|
+
for i, (member, pane) in enumerate(targets):
|
|
92
|
+
if pane is None:
|
|
93
|
+
skipped.append((member.name, "not-running"))
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
_type_one(server, member, pane, text, done, skipped, opened, held, small)
|
|
97
|
+
except Gone:
|
|
98
|
+
if not server.alive():
|
|
99
|
+
# The whole team ended, not this member: none from here on can be reached.
|
|
100
|
+
stopped = [m.name for m, _ in targets[i:] if m.name not in done]
|
|
101
|
+
break
|
|
102
|
+
# The pane closed under us. After Enter the member was typed to: `/exit` ends it.
|
|
103
|
+
if member.name not in done:
|
|
104
|
+
skipped.append((member.name, "not-running"))
|
|
105
|
+
return Typed(done, skipped, opened, held, stopped, small)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _type_one(
|
|
109
|
+
server: Server,
|
|
110
|
+
member: Member,
|
|
111
|
+
pane: str,
|
|
112
|
+
text: str,
|
|
113
|
+
done: list[str],
|
|
114
|
+
skipped: list[tuple[str, Screen | Literal["not-running", "copy-mode"]]],
|
|
115
|
+
opened: list[tuple[str, Screen]],
|
|
116
|
+
held: list[tuple[str, Held]],
|
|
117
|
+
small: list[tuple[str, int, int]],
|
|
118
|
+
) -> None:
|
|
119
|
+
h = harness.get(member.harness)
|
|
120
|
+
if _unfit(server, h, member, pane, skipped, small):
|
|
121
|
+
return
|
|
122
|
+
screen = h.screen(server.capture(pane))
|
|
123
|
+
if screen not in _TYPABLE:
|
|
124
|
+
skipped.append((member.name, screen))
|
|
125
|
+
return
|
|
126
|
+
server.paste(pane, text)
|
|
127
|
+
if _unfit(
|
|
128
|
+
server, h, member, pane, skipped, small
|
|
129
|
+
): # the paste checked the same, and pasted nothing
|
|
130
|
+
return
|
|
131
|
+
screen = _wait_for_draft(server, h, pane)
|
|
132
|
+
seen = screen == "draft"
|
|
133
|
+
if seen:
|
|
134
|
+
# A prompt that opens between this capture and the key still gets the Enter: tmux
|
|
135
|
+
# has no send-keys that checks the screen first.
|
|
136
|
+
screen = h.screen(server.capture(pane))
|
|
137
|
+
if screen != "draft":
|
|
138
|
+
held.append((member.name, screen if seen or screen in _TYPABLE else _UNSEEN[screen]))
|
|
139
|
+
return
|
|
140
|
+
server.enter(pane)
|
|
141
|
+
time.sleep(_AFTER_ENTER)
|
|
142
|
+
done.append(member.name)
|
|
143
|
+
screen = h.screen(server.capture(pane))
|
|
144
|
+
if screen in _OPENED:
|
|
145
|
+
opened.append((member.name, screen))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _unfit(
|
|
149
|
+
server: Server,
|
|
150
|
+
h: harness.Harness,
|
|
151
|
+
member: Member,
|
|
152
|
+
pane: str,
|
|
153
|
+
skipped: list[tuple[str, Screen | Literal["not-running", "copy-mode"]]],
|
|
154
|
+
small: list[tuple[str, int, int]],
|
|
155
|
+
) -> bool:
|
|
156
|
+
"""A dead pane, one scrolled back in copy mode, or one too small to read is not typed into;
|
|
157
|
+
it is named."""
|
|
158
|
+
state = server.state(pane)
|
|
159
|
+
if state[:1].isdigit():
|
|
160
|
+
columns, rows = map(int, state.split())
|
|
161
|
+
if columns < h.columns or rows < h.rows:
|
|
162
|
+
small.append((member.name, columns, rows))
|
|
163
|
+
return True
|
|
164
|
+
return False
|
|
165
|
+
skipped.append((member.name, "not-running" if state == "dead" else "copy-mode"))
|
|
166
|
+
return True
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _wait_for_draft(server: Server, h: harness.Harness, pane: str) -> Screen:
|
|
170
|
+
deadline = time.monotonic() + _SHOWN_WITHIN
|
|
171
|
+
while True:
|
|
172
|
+
screen = h.screen(server.capture(pane))
|
|
173
|
+
if screen not in _TYPABLE or time.monotonic() > deadline:
|
|
174
|
+
return screen
|
|
175
|
+
time.sleep(0.05) # a polling interval: nobody measured it, and nothing rests on its value
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def typed_text(t: Typed, resume: str, back: str) -> tuple[str, int]:
|
|
179
|
+
"""The owner's `send` result, as printed, and its exit code. `resume` starts a member again
|
|
180
|
+
and `back` brings the team back, each as the reader types it."""
|
|
181
|
+
dialogs = [name for name, why in t.skipped if why in ("dialog", "picker")]
|
|
182
|
+
if not t.done and not t.held and len(dialogs) > 1 and len(dialogs) == len(t.skipped):
|
|
183
|
+
both = "both" if len(dialogs) == 2 else "all"
|
|
184
|
+
return (
|
|
185
|
+
f"Nothing was typed. {_and(dialogs)} {both} have a dialog open; "
|
|
186
|
+
"answer them in their panes, then send again.",
|
|
187
|
+
1,
|
|
188
|
+
)
|
|
189
|
+
lines = [f"Typed to {', '.join(t.done)}."] if t.done else []
|
|
190
|
+
lines += [_NOW_OPEN[why].format(name) for name, why in t.opened]
|
|
191
|
+
lines += [_HELD[why].format(name) for name, why in t.held]
|
|
192
|
+
lines += [_SKIPPED[why].format(name, resume=resume) for name, why in t.skipped]
|
|
193
|
+
lines += [_SMALL.format(name, columns, rows) for name, columns, rows in t.small]
|
|
194
|
+
if t.stopped:
|
|
195
|
+
lines.append(
|
|
196
|
+
"The team's tmux server stopped while the text was being typed, so nothing was typed "
|
|
197
|
+
f"to {_and(t.stopped)}. Run `{back}` to bring the team back."
|
|
198
|
+
)
|
|
199
|
+
return "\n".join(lines), 1 if t.skipped or t.held or t.stopped or t.small else 0
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def inbox_to(
|
|
203
|
+
targets: Sequence[Member], sender: str, text: str, live: Container[str | None]
|
|
204
|
+
) -> tuple[str, int]:
|
|
205
|
+
"""A member's `send`: one inbox line each, `live` the ids with a live pane. A member that
|
|
206
|
+
cannot be reached is still starting while its pane runs, and not running once it does not:
|
|
207
|
+
its inbox alone cannot say, being missing before the first hello and stale after a resume."""
|
|
208
|
+
sent: list[str] = []
|
|
209
|
+
down: list[str] = []
|
|
210
|
+
starting: list[str] = []
|
|
211
|
+
for m in targets:
|
|
212
|
+
if m.inbox is not None and harness.get(m.harness).deliver(m.inbox, sender, text):
|
|
213
|
+
sent.append(m.name)
|
|
214
|
+
elif m.id in live:
|
|
215
|
+
starting.append(m.name)
|
|
216
|
+
else:
|
|
217
|
+
down.append(m.name)
|
|
218
|
+
if not down and not starting:
|
|
219
|
+
return f"Sent to {', '.join(sent)}.", 0
|
|
220
|
+
clauses = [
|
|
221
|
+
f"{_and(names)} {_be(names)} {what}"
|
|
222
|
+
for names, what in ((down, "not running"), (starting, "still starting"))
|
|
223
|
+
if names
|
|
224
|
+
]
|
|
225
|
+
return f"{'; '.join(clauses)}; sent to {', '.join(sent) or 'nobody'}.", 1
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def notify(r: Roster, notices: Sequence[Notice]) -> list[Notice]:
|
|
229
|
+
"""Notices, each under its sender; the ones that did not arrive. A failed one is not sent
|
|
230
|
+
again: the change already stands."""
|
|
231
|
+
missed = []
|
|
232
|
+
for n in notices:
|
|
233
|
+
m = r.by_id(n.to)
|
|
234
|
+
if m is None or not harness.get(m.harness).deliver(m.inbox, n.sender, n.text):
|
|
235
|
+
missed.append(n)
|
|
236
|
+
return missed
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _and(names: Sequence[str]) -> str:
|
|
240
|
+
return names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _be(names: Sequence[str]) -> str:
|
|
244
|
+
return "is" if len(names) == 1 else "are"
|