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/notes/leader.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
You are leader, the leader of a team of Claude Code sessions in {cwd}. Your workers: {workers}. You are told when a worker reports, leaves or exits, comes back holding a task, or stops still holding one, and when your owner adds one.
|
|
2
|
+
What your owner types reaches you as their own input. Messages marked "{NAME}" are the tool reporting a fact.
|
|
3
|
+
Each command below acts on this team, however many teams the folder or the machine holds; naming a team with -r is your owner's form and is refused for you. Run them exactly as written here, with no prefix:
|
|
4
|
+
- `{NAME} board` shows the board: each member's state and the task it holds, then Review, Ready and Done. A worker that is IDLE and holds no task is free.
|
|
5
|
+
- `{NAME} board new "<title>" [-f <brief file>] [--to <worker>]` adds a task; write it so a worker can start without asking. Without `--to` it goes to Ready, where the next free worker takes it at once; with `--to` it goes straight to that worker, and `{NAME} board back <id> --to <worker>` gives a task still waiting in Ready to that worker.
|
|
6
|
+
- When a worker reports, the task is in Review: check it, then `{NAME} board close <id>`, or `{NAME} board back <id> [--to <worker>]` to send it back with its reports: with `--to` to that worker, such as the one that wrote it; without, to Ready, where the next free worker takes it. A worker that cannot go on reports "blocked: …".
|
|
7
|
+
- `{NAME} add [N]`, `{NAME} remove <worker>`, `{NAME} resume <worker> [-- --model <model> --effort <effort>]` (either flag or both; sets that worker's model or effort and restarts it), `{NAME} rename <worker> <new>` and `{NAME} layout left|right|middle` change the team. `{NAME} send <member> "<text>"` messages a member.
|
|
8
|
+
Give work only through the board, never by message, even when a worker asks you directly or the board is slow: work handed out by message is invisible to the others and gets done twice.
|
|
9
|
+
A blocked report stays in Review until it can go on; then `{NAME} board close <id>`, and create it again with what it lacked.
|
|
10
|
+
You do not take tasks yourself.
|
|
11
|
+
|
|
12
|
+
Principles:
|
|
13
|
+
1. You are the constraint: dispatch before you do, and keep startable work ready. Hands-on work longer than a few minutes belongs to a worker; a task is ready only if a worker can start it from its line and brief without asking.
|
|
14
|
+
2. **Perfect product.** "Perfect is sort of when you can't take anything away anymore." For every mechanism, concept and option, ask what is lost if it is taken away. Keep it only if a real past failure, a measured number or a hard rule needs it. Before you cut, look for them: the decision log, incident notes and the project's rules.
|
|
15
|
+
3. **Work as the best practitioner of that exact problem would, not with the first plan that comes to mind.** In every decision, every brief you write and every report you accept:
|
|
16
|
+
- do what a top professional in that field would do here without being asked, and say what it is;
|
|
17
|
+
- start from the rawest material they would start from — the source, the data, the run, the original text — not from a summary someone has already digested;
|
|
18
|
+
- use the specific methods and tools they would use: look the practice up instead of recalling it, and name the method and the tool;
|
|
19
|
+
- show that the result is right by something other than yourself or its author: a run, a test that fails without the change, an independent check.
|
|
20
|
+
4. Decisions can be overturned; principles cannot. When evidence shows a ruling is wrong, say so at once instead of building around it.
|
|
21
|
+
5. The machine is shared: before you or a worker starts a heavy run (many parallel jobs or a lot of memory), check free memory and cap the parallelism to your share; delete only what you created.
|
workcrew/notes/worker.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
You are {member}, a worker in {cwd}. `leader` directs your work: treat its instructions as your owner's. The other workers are {others}.
|
|
2
|
+
Message a teammate with `{NAME} send <name> "<text>"`.
|
|
3
|
+
Take work only from the board: `{NAME} board take`. When it is done, `{NAME} board report <id> "<file or one-line result; what is not verified>"`, and take the next Ready task in the same turn. If you cannot go on, `{NAME} board report <id> "blocked: <why>"`.
|
|
4
|
+
Do not take or hand out work by message: if anyone asks you to do something that is not your task, ask the leader to put it on the board. When Ready is empty, end your turn; you will be told when work appears.
|
|
5
|
+
The team shares one checkout: never create, switch or delete branches; leave git to the leader.
|
workcrew/picker.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""`workcrew -r` on a terminal: the owner's teams, one row each, to choose the one to bring back.
|
|
2
|
+
|
|
3
|
+
It draws on the terminal's alternate screen, so leaving it gives back the screen as it was, as
|
|
4
|
+
the command line at `C-]` does when its popup closes.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import termios
|
|
11
|
+
import tty
|
|
12
|
+
from collections.abc import Callable, Sequence
|
|
13
|
+
|
|
14
|
+
from workcrew.board import cut
|
|
15
|
+
from workcrew.prompt import Keys, fit
|
|
16
|
+
from workcrew.width import cols
|
|
17
|
+
|
|
18
|
+
HEAD = "Open a team ({k} of {n})"
|
|
19
|
+
FOOT = "↑/↓ to move · Enter to open it · Esc to leave"
|
|
20
|
+
SMALL = "Too small to list your teams: make the window taller, or press Esc."
|
|
21
|
+
# Head, the line for the rows above, the line for the rows below and the foot, around the rows.
|
|
22
|
+
FRAME = 4
|
|
23
|
+
# How often a picker with no key to read looks at the terminal's size: a resize draws again.
|
|
24
|
+
LOOK = 0.1
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _pad(s: str, w: int) -> str:
|
|
28
|
+
return s + " " * (w - cols(s))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def lined(rows: Sequence[tuple[str, str, str]], width: int) -> list[str]:
|
|
32
|
+
"""Each row's name and folder padded to the widest, so the list reads down in columns. A
|
|
33
|
+
list wider than the terminal cuts the folders, so the members stay in view."""
|
|
34
|
+
name_w = max(cols(name) for name, _, _ in rows)
|
|
35
|
+
folder_w = max(cols(folder) for _, folder, _ in rows)
|
|
36
|
+
members_w = max(cols(members) for _, _, members in rows)
|
|
37
|
+
# The cursor's mark and two spaces between the columns.
|
|
38
|
+
folder_w = min(folder_w, width - 2 - name_w - 2 - 2 - members_w)
|
|
39
|
+
return [
|
|
40
|
+
f"{_pad(name, name_w)} {_pad(cut(folder, folder_w), folder_w)} {members}"
|
|
41
|
+
for name, folder, members in rows
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def frame(
|
|
46
|
+
rows: Sequence[tuple[str, str, str]], cur: int, top: int, size: os.terminal_size
|
|
47
|
+
) -> tuple[str, int]:
|
|
48
|
+
"""The screen for rows with cur chosen, and the first row shown: the window keeps cur in it
|
|
49
|
+
and moves only when cur leaves it."""
|
|
50
|
+
room = size.lines - FRAME
|
|
51
|
+
if room < 1:
|
|
52
|
+
return fit(SMALL, size.columns), top
|
|
53
|
+
top = min(max(top, cur - room + 1), cur, max(0, len(rows) - room))
|
|
54
|
+
shown = lined(rows, size.columns)[top : top + room]
|
|
55
|
+
below = len(rows) - top - len(shown)
|
|
56
|
+
lines = [
|
|
57
|
+
HEAD.format(k=cur + 1, n=len(rows)),
|
|
58
|
+
f" ↑ {top} more" if top else "",
|
|
59
|
+
*(("> " if top + i == cur else " ") + row for i, row in enumerate(shown)),
|
|
60
|
+
f" ↓ {below} more" if below else "",
|
|
61
|
+
FOOT,
|
|
62
|
+
]
|
|
63
|
+
return "\x1b[K\r\n".join(fit(line, size.columns) for line in lines), top
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _stdout(s: str) -> None:
|
|
67
|
+
os.write(1, s.encode())
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def pick(
|
|
71
|
+
rows: Sequence[tuple[str, str, str]],
|
|
72
|
+
fd: int = 0,
|
|
73
|
+
write: Callable[[str], None] | None = None,
|
|
74
|
+
size: Callable[[], os.terminal_size] | None = None,
|
|
75
|
+
) -> int | None:
|
|
76
|
+
"""The index of the row chosen with Enter, or None for Esc, Ctrl-C or the end of input."""
|
|
77
|
+
out = write or _stdout
|
|
78
|
+
measure = size or (lambda: os.get_terminal_size(1))
|
|
79
|
+
keys, cur, top, drawn = Keys(fd), 0, 0, None
|
|
80
|
+
old = termios.tcgetattr(fd)
|
|
81
|
+
try:
|
|
82
|
+
# setraw's default, TCSAFLUSH, drops what the owner typed before the picker started.
|
|
83
|
+
tty.setraw(fd, termios.TCSANOW)
|
|
84
|
+
out("\x1b[?1049h\x1b[?25l") # the alternate screen, with no cursor
|
|
85
|
+
while True:
|
|
86
|
+
now = measure()
|
|
87
|
+
if drawn != (cur, now):
|
|
88
|
+
screen, top = frame(rows, cur, top, now)
|
|
89
|
+
out(f"\x1b[H{screen}\x1b[K\x1b[J")
|
|
90
|
+
drawn = (cur, now)
|
|
91
|
+
if not keys.buf and not keys.more(LOOK):
|
|
92
|
+
continue
|
|
93
|
+
got = keys.key()
|
|
94
|
+
if got is None:
|
|
95
|
+
return None
|
|
96
|
+
name, text = got
|
|
97
|
+
if name in ("esc", "cancel"):
|
|
98
|
+
return None
|
|
99
|
+
if name == "enter" and now.lines > FRAME: # a screen too small showed no row
|
|
100
|
+
return cur
|
|
101
|
+
step = {"up": -1, "down": 1}.get(name, 0)
|
|
102
|
+
if name == "": # typed, not pasted
|
|
103
|
+
step += text.count("j") - text.count("k")
|
|
104
|
+
cur = min(max(cur + step, 0), len(rows) - 1)
|
|
105
|
+
finally:
|
|
106
|
+
out("\x1b[?25h\x1b[?1049l")
|
|
107
|
+
termios.tcsetattr(fd, termios.TCSADRAIN, old)
|
workcrew/place.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Where the leader and the workers sit in the team's window.
|
|
2
|
+
|
|
3
|
+
Pure geometry: no tmux call and no state, so every size and member count is testable
|
|
4
|
+
without a server.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from collections.abc import Sequence
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
# A cell's columns to its rows in the grid's best shape: a Claude Code screen read best at 60 by
|
|
15
|
+
# 15 (2.1.332). It is a shape, not a floor: every member is placed however small.
|
|
16
|
+
ASPECT = 4
|
|
17
|
+
LEADER = "leader"
|
|
18
|
+
TEAM = "team" # the window the members are in
|
|
19
|
+
|
|
20
|
+
Side = Literal["left", "right", "middle"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Cell:
|
|
25
|
+
member: str | None # a member id; None = an owner pane
|
|
26
|
+
x: int
|
|
27
|
+
y: int
|
|
28
|
+
w: int
|
|
29
|
+
h: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def leader_width(W: int) -> int:
|
|
33
|
+
return max(W // 3, min(100, W // 2))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def plan(
|
|
37
|
+
W: int, H: int, side: Side, workers: Sequence[str], owners: int, leader: bool = True
|
|
38
|
+
) -> tuple[Side, tuple[Cell, ...]]:
|
|
39
|
+
"""The team window's cells, in the order tmux gives them to panes, and the side used:
|
|
40
|
+
`middle` needs two cells beside the leader. No member cell: the window is not ours."""
|
|
41
|
+
Hc = H - 1 # tmux's pane-border-status takes the top row
|
|
42
|
+
group: list[str | None] = [*workers, *[None] * owners]
|
|
43
|
+
used: Side = side if side != "middle" or len(group) >= 2 else "right"
|
|
44
|
+
if not leader:
|
|
45
|
+
cells = _grid(W, Hc, 0, group)
|
|
46
|
+
elif not group:
|
|
47
|
+
cells = [Cell(LEADER, 0, 0, W, Hc)]
|
|
48
|
+
else:
|
|
49
|
+
cells = _team(W, Hc, used, leader_width(W), group)
|
|
50
|
+
return used, tuple(cells) if any(c.member is not None for c in cells) else ()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _split(total: int, n: int) -> list[int]:
|
|
54
|
+
"""n sizes filling total with one border line between them; the first ones take the rest."""
|
|
55
|
+
base, extra = divmod(total - (n - 1), n)
|
|
56
|
+
return [base + (i < extra) for i in range(n)]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _grid(w: int, h: int, x0: int, members: Sequence[str | None]) -> list[Cell]:
|
|
60
|
+
"""A tiled area's cells, column by column, in the shape with the largest smallest cell."""
|
|
61
|
+
n = len(members)
|
|
62
|
+
if n == 0:
|
|
63
|
+
return []
|
|
64
|
+
|
|
65
|
+
def score(c: int) -> float: # on a tie, max keeps the first: the fewest columns
|
|
66
|
+
r = math.ceil(n / c)
|
|
67
|
+
return min(((w - c + 1) // c) / ASPECT, (h - r + 1) // r)
|
|
68
|
+
|
|
69
|
+
cols = max(range(1, n + 1), key=score)
|
|
70
|
+
out: list[Cell] = []
|
|
71
|
+
x, k = x0, 0
|
|
72
|
+
for cw, m in zip(
|
|
73
|
+
_split(w, cols), [n // cols + (i < n % cols) for i in range(cols)], strict=True
|
|
74
|
+
):
|
|
75
|
+
y = 0
|
|
76
|
+
for ch in _split(h, m):
|
|
77
|
+
out.append(Cell(members[k], x, y, cw, ch))
|
|
78
|
+
k, y = k + 1, y + ch + 1
|
|
79
|
+
x += cw + 1
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _team(W: int, Hc: int, side: Side, lw: int, cells: Sequence[str | None]) -> list[Cell]:
|
|
84
|
+
if side == "middle":
|
|
85
|
+
rest = W - lw - 2
|
|
86
|
+
a, b = (rest + 1) // 2, rest // 2
|
|
87
|
+
# the odd cell goes left, so an add or a remove moves at most one pane
|
|
88
|
+
left = (len(cells) + 1) // 2
|
|
89
|
+
return [
|
|
90
|
+
*_grid(a, Hc, 0, cells[:left]),
|
|
91
|
+
Cell(LEADER, a + 1, 0, lw, Hc),
|
|
92
|
+
*_grid(b, Hc, a + lw + 2, cells[left:]),
|
|
93
|
+
]
|
|
94
|
+
if side == "left":
|
|
95
|
+
return [Cell(LEADER, 0, 0, lw, Hc), *_grid(W - lw - 1, Hc, lw + 1, cells)]
|
|
96
|
+
ww = W - lw - 1
|
|
97
|
+
return [*_grid(ww, Hc, 0, cells), Cell(LEADER, ww + 1, 0, lw, Hc)]
|
workcrew/prompt.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""The owner's command line: one raw-mode reader on the popup's terminal, standard library only.
|
|
2
|
+
|
|
3
|
+
It requests bracketed paste and parses it; keeps pasted line breaks as real newlines, drawn
|
|
4
|
+
" ⏎ "; drains an unbracketed paste after Enter; and edits by display columns, so a
|
|
5
|
+
line of Chinese edits in place. tmux's escape-time already tells a lone Esc from a key, and it
|
|
6
|
+
writes each key, and a paste's start, to the popup whole. It needs no
|
|
7
|
+
readline: the Python that `uv tool install` provides ships editline, whose input()
|
|
8
|
+
returns only a paste's first line.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import codecs
|
|
14
|
+
import contextlib
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import select
|
|
18
|
+
import termios
|
|
19
|
+
import time
|
|
20
|
+
import tty
|
|
21
|
+
from collections.abc import Callable, Sequence
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from workcrew.state import names_a_team, write_atomic
|
|
26
|
+
from workcrew.width import cols as text_cols
|
|
27
|
+
|
|
28
|
+
# 47x the 0.64 ms largest gap between two reads of a local unbracketed paste, 1.5x the 19.7 ms
|
|
29
|
+
# gap behind a 10 KB/s link, half the 60 ms floor of a typist's gap (Dhakal et al., CHI 2018).
|
|
30
|
+
DRAIN = 0.03
|
|
31
|
+
START, END = b"\x1b[200~", b"\x1b[201~"
|
|
32
|
+
MARK = " ⏎ " # how a pasted line break is drawn
|
|
33
|
+
PROMPT = "(team) "
|
|
34
|
+
HISTORY_KEEP = 200
|
|
35
|
+
PASTED = "Pasted {n} lines; only `send` takes several lines. Nothing was run."
|
|
36
|
+
|
|
37
|
+
# What tmux writes to a popup: it rewrites the SS3 arrows and xterm's Home and End to these, and
|
|
38
|
+
# passes rxvt's Home and End (7~, 8~) as they come.
|
|
39
|
+
KEYS = {
|
|
40
|
+
b"\x1b[A": "up", b"\x1b[B": "down", b"\x1b[C": "right", b"\x1b[D": "left",
|
|
41
|
+
b"\x1b[1~": "home", b"\x1b[7~": "home", b"\x1b[4~": "end", b"\x1b[8~": "end",
|
|
42
|
+
b"\x1b[3~": "delete",
|
|
43
|
+
} # fmt: skip
|
|
44
|
+
CONTROL = {
|
|
45
|
+
0x01: "home", 0x03: "cancel", 0x05: "end", 0x08: "backspace", 0x0B: "kill-end",
|
|
46
|
+
0x0A: "enter", 0x0D: "enter", 0x15: "kill-start", 0x17: "kill-word", 0x7F: "backspace",
|
|
47
|
+
} # fmt: skip
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def width(ch: str) -> int:
|
|
51
|
+
"""Display columns of one character as drawn: a line break is MARK, a control is ^X."""
|
|
52
|
+
if ch == "\n":
|
|
53
|
+
return len(MARK)
|
|
54
|
+
if ord(ch) < 32 or ord(ch) == 127:
|
|
55
|
+
return 2
|
|
56
|
+
return text_cols(ch)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def glyph(ch: str) -> str:
|
|
60
|
+
if ch == "\n":
|
|
61
|
+
return MARK
|
|
62
|
+
if ord(ch) < 32 or ord(ch) == 127:
|
|
63
|
+
return "^" + chr(ord(ch) ^ 64)
|
|
64
|
+
return ch
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def cols(s: str) -> int:
|
|
68
|
+
return sum(width(c) for c in s)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def fit(s: str, room: int) -> str:
|
|
72
|
+
"""The longest head of s, drawn, that fits in room columns."""
|
|
73
|
+
out, used = [], 0
|
|
74
|
+
for c in s:
|
|
75
|
+
if used + width(c) > room:
|
|
76
|
+
break
|
|
77
|
+
out.append(glyph(c))
|
|
78
|
+
used += width(c)
|
|
79
|
+
return "".join(out)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def fit_tail(s: str, room: int) -> str:
|
|
83
|
+
"""The longest tail of s, drawn, that fits in room columns."""
|
|
84
|
+
out, used = [], 0
|
|
85
|
+
for c in reversed(s):
|
|
86
|
+
if used + width(c) > room:
|
|
87
|
+
break
|
|
88
|
+
out.append(glyph(c))
|
|
89
|
+
used += width(c)
|
|
90
|
+
return "".join(reversed(out))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def command(text: str) -> str:
|
|
94
|
+
"""The typed line less one leading `workcrew`: the tool's texts give whole command lines, and
|
|
95
|
+
each must work where it is printed."""
|
|
96
|
+
return re.sub(r"\A\s*workcrew(\s+|\Z)", "", text, count=1)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def render(prompt: str, text: str, cur: int, room: int) -> tuple[str, int]:
|
|
100
|
+
"""What to draw after the prompt, and the cursor's column on the row, within room columns.
|
|
101
|
+
|
|
102
|
+
A paste too long for the row keeps its first line's head and says "… [N lines]"; one long line
|
|
103
|
+
keeps the command and, for `send`, its recipients, then shows the part around the cursor.
|
|
104
|
+
"""
|
|
105
|
+
if cols(prompt + text) < room:
|
|
106
|
+
return "".join(glyph(c) for c in text), cols(prompt + text[:cur])
|
|
107
|
+
avail = room - cols(prompt) - 1
|
|
108
|
+
if "\n" in text:
|
|
109
|
+
tag = f" … [{text.count(chr(10)) + 1} lines]"
|
|
110
|
+
head = fit(text.split("\n", 1)[0], avail - len(tag))
|
|
111
|
+
return head + tag, cols(prompt) + cols(head)
|
|
112
|
+
rest = command(text)
|
|
113
|
+
words = rest.split(" ")
|
|
114
|
+
keep = text[: len(text) - len(rest)] + (
|
|
115
|
+
" ".join(words[:2]) + " " if words[0] == "send" and len(words) > 2 else words[0] + " "
|
|
116
|
+
)
|
|
117
|
+
# Drawn like every other part, and measured as drawn: `keep` indexes into the text, `shown`
|
|
118
|
+
# is what reaches the terminal.
|
|
119
|
+
shown = "".join(glyph(c) for c in keep)
|
|
120
|
+
if cols(shown) + 10 > avail or cur <= len(keep):
|
|
121
|
+
before = fit_tail(text[:cur], avail // 2)
|
|
122
|
+
after = fit(text[cur:], avail - cols(before))
|
|
123
|
+
return before + after, cols(prompt) + cols(before)
|
|
124
|
+
room2 = avail - cols(shown) - 2
|
|
125
|
+
before = fit_tail(text[len(keep) : cur], room2)
|
|
126
|
+
after = fit(text[cur:], room2 - cols(before))
|
|
127
|
+
return shown + "… " + before + after, cols(prompt) + cols(shown) + 2 + cols(before)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _back(t: str, c: int) -> int:
|
|
131
|
+
"""The start of the character before c; a width-0 character belongs to the one before it."""
|
|
132
|
+
c = max(0, c - 1)
|
|
133
|
+
while c and text_cols(t[c]) == 0:
|
|
134
|
+
c -= 1
|
|
135
|
+
return c
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _forward(t: str, c: int) -> int:
|
|
139
|
+
"""The end of the character at c, with the width-0 characters that follow it."""
|
|
140
|
+
c = min(len(t), c + 1)
|
|
141
|
+
while c < len(t) and text_cols(t[c]) == 0:
|
|
142
|
+
c += 1
|
|
143
|
+
return c
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class Keys:
|
|
147
|
+
"""The keys read from fd, which must already be in raw mode: the command line's and the
|
|
148
|
+
picker's."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, fd: int = 0) -> None:
|
|
151
|
+
self.fd, self.buf = fd, b""
|
|
152
|
+
self.dec = codecs.getincrementaldecoder("utf-8")("replace")
|
|
153
|
+
|
|
154
|
+
def more(self, timeout: float | None) -> bool:
|
|
155
|
+
if select.select([self.fd], [], [], timeout)[0]:
|
|
156
|
+
data = os.read(self.fd, 65536)
|
|
157
|
+
if data:
|
|
158
|
+
self.buf += data
|
|
159
|
+
return True
|
|
160
|
+
return False
|
|
161
|
+
|
|
162
|
+
def key(self) -> tuple[str, str] | None:
|
|
163
|
+
"""(name, text): a key's name with no text, ("", text) for typed text, ("paste", text)
|
|
164
|
+
for a bracketed paste; None at the end of input. Every call takes a byte out of buf:
|
|
165
|
+
one that is neither escape, control nor printable would be read for ever, which is why
|
|
166
|
+
the control test below names DEL."""
|
|
167
|
+
if not self.buf and not self.more(None):
|
|
168
|
+
return None
|
|
169
|
+
b = self.buf[0]
|
|
170
|
+
if b == 0x1B:
|
|
171
|
+
return self.escape()
|
|
172
|
+
if b < 0x20 or b == 0x7F:
|
|
173
|
+
self.buf = self.buf[1:]
|
|
174
|
+
return CONTROL.get(b, ""), ""
|
|
175
|
+
i = 0
|
|
176
|
+
while i < len(self.buf) and self.buf[i] >= 0x20 and self.buf[i] != 0x7F:
|
|
177
|
+
i += 1
|
|
178
|
+
text, self.buf = self.dec.decode(self.buf[:i]), self.buf[i:]
|
|
179
|
+
return "", text
|
|
180
|
+
|
|
181
|
+
def escape(self) -> tuple[str, str]:
|
|
182
|
+
"""The key named by the escape sequence at the head of buf; '' for none or one ignored."""
|
|
183
|
+
if len(self.buf) == 1:
|
|
184
|
+
self.buf = b""
|
|
185
|
+
return "esc", ""
|
|
186
|
+
if self.buf[1:2] == b"\x1b": # Esc Esc: an outer tmux merged two presses into Meta+Esc
|
|
187
|
+
self.buf = self.buf[2:]
|
|
188
|
+
return "esc", ""
|
|
189
|
+
if self.buf.startswith(START):
|
|
190
|
+
self.buf = self.buf[len(START) :]
|
|
191
|
+
return "paste", self.paste()
|
|
192
|
+
if self.buf[1:2] in (b"[", b"O"):
|
|
193
|
+
i = 2
|
|
194
|
+
while i < len(self.buf) and not 0x40 <= self.buf[i] <= 0x7E:
|
|
195
|
+
i += 1
|
|
196
|
+
seq, self.buf = self.buf[: i + 1], self.buf[i + 1 :]
|
|
197
|
+
return KEYS.get(seq, ""), ""
|
|
198
|
+
n = 2 # Esc and one character: an Alt chord, which no edit uses
|
|
199
|
+
while n < len(self.buf) and 0x80 <= self.buf[n] < 0xC0:
|
|
200
|
+
n += 1
|
|
201
|
+
self.buf = self.buf[n:]
|
|
202
|
+
return "", ""
|
|
203
|
+
|
|
204
|
+
def paste(self) -> str:
|
|
205
|
+
raw = b""
|
|
206
|
+
while True:
|
|
207
|
+
j = self.buf.find(END)
|
|
208
|
+
if j >= 0:
|
|
209
|
+
raw += self.buf[:j]
|
|
210
|
+
self.buf = self.buf[j + len(END) :]
|
|
211
|
+
break
|
|
212
|
+
keep = next((k for k in range(len(END) - 1, 0, -1) if self.buf.endswith(END[:k])), 0)
|
|
213
|
+
raw += self.buf[: len(self.buf) - keep]
|
|
214
|
+
self.buf = self.buf[len(self.buf) - keep :]
|
|
215
|
+
if not self.more(None):
|
|
216
|
+
break
|
|
217
|
+
return raw.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class Reader(Keys):
|
|
221
|
+
"""One line from fd; writes through `write`. The terminal must already be in raw mode."""
|
|
222
|
+
|
|
223
|
+
def __init__(
|
|
224
|
+
self,
|
|
225
|
+
history: Sequence[str],
|
|
226
|
+
fd: int = 0,
|
|
227
|
+
write: Callable[[str], None] | None = None,
|
|
228
|
+
columns: Callable[[], int] | None = None,
|
|
229
|
+
) -> None:
|
|
230
|
+
super().__init__(fd)
|
|
231
|
+
self.history = list(history)
|
|
232
|
+
self.write = write or _stdout
|
|
233
|
+
self.columns = columns or (lambda: os.get_terminal_size(1).columns)
|
|
234
|
+
self.text, self.cur, self.hpos = "", 0, len(self.history)
|
|
235
|
+
self.draft, self.pasted = "", False
|
|
236
|
+
|
|
237
|
+
def insert(self, s: str) -> None:
|
|
238
|
+
self.text = self.text[: self.cur] + s + self.text[self.cur :]
|
|
239
|
+
self.cur += len(s)
|
|
240
|
+
|
|
241
|
+
def draw(self) -> None:
|
|
242
|
+
shown, col = render(PROMPT, self.text, self.cur, self.columns())
|
|
243
|
+
self.write(f"\r{PROMPT}{shown}\x1b[K\r\x1b[{col}C")
|
|
244
|
+
|
|
245
|
+
def edit(self, name: str) -> None:
|
|
246
|
+
t, c = self.text, self.cur
|
|
247
|
+
if name == "left":
|
|
248
|
+
self.cur = _back(t, c)
|
|
249
|
+
elif name == "right":
|
|
250
|
+
self.cur = _forward(t, c)
|
|
251
|
+
elif name == "home":
|
|
252
|
+
self.cur = 0
|
|
253
|
+
elif name == "end":
|
|
254
|
+
self.cur = len(t)
|
|
255
|
+
elif name == "backspace":
|
|
256
|
+
b = _back(t, c)
|
|
257
|
+
self.text, self.cur = t[:b] + t[c:], b
|
|
258
|
+
elif name == "delete":
|
|
259
|
+
self.text = t[:c] + t[_forward(t, c) :]
|
|
260
|
+
elif name == "kill-start":
|
|
261
|
+
self.text, self.cur = t[c:], 0
|
|
262
|
+
elif name == "kill-end":
|
|
263
|
+
self.text = t[:c]
|
|
264
|
+
elif name == "kill-word":
|
|
265
|
+
i = c
|
|
266
|
+
while i and t[i - 1] == " ":
|
|
267
|
+
i -= 1
|
|
268
|
+
while i and t[i - 1] != " ":
|
|
269
|
+
i -= 1
|
|
270
|
+
self.text, self.cur = t[:i] + t[c:], i
|
|
271
|
+
elif name in ("up", "down"):
|
|
272
|
+
self.recall(-1 if name == "up" else 1)
|
|
273
|
+
|
|
274
|
+
def recall(self, step: int) -> None:
|
|
275
|
+
"""As readline: the line being typed is the bottom entry; past either end nothing moves."""
|
|
276
|
+
to = self.hpos + step
|
|
277
|
+
if 0 <= to <= len(self.history):
|
|
278
|
+
if self.hpos == len(self.history):
|
|
279
|
+
self.draft = self.text
|
|
280
|
+
self.hpos = to
|
|
281
|
+
self.text = self.history[to] if to < len(self.history) else self.draft
|
|
282
|
+
self.cur = len(self.text)
|
|
283
|
+
|
|
284
|
+
def run(self) -> tuple[list[str] | None, str]:
|
|
285
|
+
"""(lines, how): how is "enter", "empty", "esc", "cancel" (Ctrl-C) or "eof"."""
|
|
286
|
+
self.draw()
|
|
287
|
+
while True:
|
|
288
|
+
got = self.key()
|
|
289
|
+
if got is None:
|
|
290
|
+
return None, "eof"
|
|
291
|
+
name, text = got
|
|
292
|
+
if text:
|
|
293
|
+
self.insert(text)
|
|
294
|
+
self.pasted = self.pasted or name == "paste"
|
|
295
|
+
if name in ("esc", "cancel"):
|
|
296
|
+
return None, name
|
|
297
|
+
if name == "enter":
|
|
298
|
+
lines = self.finish()
|
|
299
|
+
return lines, "enter" if lines else "empty"
|
|
300
|
+
self.edit(name)
|
|
301
|
+
self.draw()
|
|
302
|
+
|
|
303
|
+
def finish(self) -> list[str] | None:
|
|
304
|
+
if not self.pasted: # Enter inside an unbracketed paste: take what follows it
|
|
305
|
+
deadline = time.monotonic() + DRAIN
|
|
306
|
+
while self.more(max(0.0, deadline - time.monotonic())):
|
|
307
|
+
deadline = time.monotonic() + DRAIN
|
|
308
|
+
rest = self.buf[1:] if self.buf.startswith(b"\n") else self.buf # CR LF: one line break
|
|
309
|
+
extra = rest.decode("utf-8", "replace").replace("\r\n", "\n").replace("\r", "\n")
|
|
310
|
+
self.buf = b""
|
|
311
|
+
lines = (self.text + ("\n" + extra if extra else "")).split("\n")
|
|
312
|
+
while lines and not lines[-1].strip():
|
|
313
|
+
lines.pop()
|
|
314
|
+
return lines or None
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _stdout(s: str) -> None:
|
|
318
|
+
os.write(1, s.encode())
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def read_line(history: Sequence[str]) -> tuple[list[str] | None, str]:
|
|
322
|
+
"""Read one command line on the popup's terminal (fds 0 and 1)."""
|
|
323
|
+
old = termios.tcgetattr(0)
|
|
324
|
+
try:
|
|
325
|
+
# setraw's default, TCSAFLUSH, drops what the owner typed before the reader started.
|
|
326
|
+
tty.setraw(0, termios.TCSANOW)
|
|
327
|
+
_stdout("\x1b[?2004h")
|
|
328
|
+
return Reader(history).run()
|
|
329
|
+
finally:
|
|
330
|
+
_stdout("\x1b[?2004l\r\n")
|
|
331
|
+
termios.tcsetattr(0, termios.TCSADRAIN, old)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
@dataclass(frozen=True)
|
|
335
|
+
class Line:
|
|
336
|
+
"""What the owner asked for: the command line to run, or a refusal to show instead."""
|
|
337
|
+
|
|
338
|
+
run: str | None
|
|
339
|
+
refusal: str | None = None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def dispatch(lines: Sequence[str]) -> Line:
|
|
343
|
+
"""Pasted extra lines are the body of a `send`, blank ones included; else nothing runs."""
|
|
344
|
+
first, more = lines[0], list(lines[1:])
|
|
345
|
+
if not more:
|
|
346
|
+
return Line(first)
|
|
347
|
+
words = command(first).split()
|
|
348
|
+
if words[:1] == ["send"] or (names_a_team(words) and words[2:3] == ["send"]):
|
|
349
|
+
return Line(first + "\n" + "\n".join(more))
|
|
350
|
+
return Line(None, PASTED.format(n=len(lines)))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def load_history(path: Path) -> list[str]:
|
|
354
|
+
try:
|
|
355
|
+
return [h for h in path.read_text().split("\n") if h]
|
|
356
|
+
except OSError:
|
|
357
|
+
return []
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def save_history(path: Path, history: Sequence[str]) -> None:
|
|
361
|
+
with contextlib.suppress(OSError):
|
|
362
|
+
write_atomic(path, "".join(h + "\n" for h in list(history)[-HISTORY_KEEP:]).encode())
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def main(
|
|
366
|
+
hist: Path,
|
|
367
|
+
run: Callable[[str], str],
|
|
368
|
+
show: Callable[[str], None],
|
|
369
|
+
guard: Callable[[], None],
|
|
370
|
+
) -> int:
|
|
371
|
+
"""`_prompt`: read, dispatch, show the result. `run` runs a command line and returns its text;
|
|
372
|
+
`guard` arms the Esc guard, so a second Esc cannot reach a busy member; `show` puts a result
|
|
373
|
+
on the status line or in a popup."""
|
|
374
|
+
history = load_history(hist)
|
|
375
|
+
lines, how = read_line(history)
|
|
376
|
+
if how == "esc":
|
|
377
|
+
guard()
|
|
378
|
+
if not lines:
|
|
379
|
+
return 0
|
|
380
|
+
line = dispatch(lines)
|
|
381
|
+
if line.run is not None: # only a line that runs, and only its first line
|
|
382
|
+
save_history(hist, [*history, lines[0]])
|
|
383
|
+
text = run(line.run) if line.run is not None else line.refusal
|
|
384
|
+
if text:
|
|
385
|
+
show(text)
|
|
386
|
+
return 0
|