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
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""The member-program contract: everything specific to one coding agent lives behind `Harness`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING, Literal, Protocol
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from workcrew.state import Member, Roster
|
|
12
|
+
|
|
13
|
+
Screen = Literal["empty", "draft", "prompt", "dialog", "picker", "busy"]
|
|
14
|
+
# A stop's own background work: none, work whose end wakes the member, or work that may run on.
|
|
15
|
+
Background = Literal["", "wakes", "runs"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Hello:
|
|
20
|
+
session_id: str
|
|
21
|
+
inbox: str | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Harness(Protocol):
|
|
25
|
+
rows: int # the fewest rows its screen can be read in
|
|
26
|
+
columns: int # and the fewest columns
|
|
27
|
+
# Below `columns`: a pane the owner made narrow is theirs; tmux scaling one to a sliver is not.
|
|
28
|
+
kept_columns: int # the fewest columns an arrangement put back may leave a member's pane
|
|
29
|
+
|
|
30
|
+
def check(self) -> None: ...
|
|
31
|
+
def gate(self, flags: Sequence[str]) -> None: ...
|
|
32
|
+
def member_flags(self, flags: Sequence[str]) -> None: ...
|
|
33
|
+
def new_id(self) -> str: ...
|
|
34
|
+
def argv(self, r: Roster, m: Member, note: Path, payload: Path) -> list[str]: ...
|
|
35
|
+
def env(self, base: Mapping[str, str], tmpdir: Path) -> dict[str, str]: ...
|
|
36
|
+
def payload(self, hooks: Mapping[str, str], bin: str) -> bytes: ...
|
|
37
|
+
def hello(self, stdin: bytes, env: Mapping[str, str]) -> Hello: ...
|
|
38
|
+
def trusted(self, folder: Path) -> bool: ...
|
|
39
|
+
def deliver(self, inbox: str | None, sender: str, text: str) -> bool: ...
|
|
40
|
+
def screen(self, text: str) -> Screen: ...
|
|
41
|
+
def stopping(self, stdin: bytes) -> bool: ...
|
|
42
|
+
def background(self, stdin: bytes) -> Background: ...
|
|
43
|
+
def refuse(self, reason: str) -> str: ...
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# After Hello and Screen, which the adapter imports from here.
|
|
47
|
+
from workcrew.harness.claude import Claude # noqa: E402
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def get(name: str) -> Harness:
|
|
51
|
+
return {"claude": Claude}[name]()
|
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
"""Claude Code as a member: the only module that names its flags, files, hooks and inbox."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import socket
|
|
10
|
+
import subprocess
|
|
11
|
+
import uuid
|
|
12
|
+
from collections.abc import Container, Mapping, Sequence
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import NamedTuple
|
|
16
|
+
|
|
17
|
+
from workcrew.harness import Background, Hello, Screen, claude_screen
|
|
18
|
+
from workcrew.state import Member, Refused, Roster, UsageError, escape
|
|
19
|
+
|
|
20
|
+
NEED = (2, 1, 225) # the first release with messages between sessions
|
|
21
|
+
|
|
22
|
+
# Set by a Claude Code session for its children (ran: a 2.1.332 session's Bash and hooks). A member
|
|
23
|
+
# started from inside a session would otherwise share the caller's inbox, session id and effort.
|
|
24
|
+
SESSION_ENV = frozenset(
|
|
25
|
+
{
|
|
26
|
+
"CLAUDECODE",
|
|
27
|
+
"CLAUDE_CODE_CHILD_NOTES_DIR",
|
|
28
|
+
"CLAUDE_CODE_CHILD_SESSION",
|
|
29
|
+
"CLAUDE_CODE_ENTRYPOINT",
|
|
30
|
+
"CLAUDE_CODE_EXECPATH",
|
|
31
|
+
"CLAUDE_CODE_HOST_HTTP_PROXY_PORT",
|
|
32
|
+
"CLAUDE_CODE_HOST_SOCKS_PROXY_PORT",
|
|
33
|
+
"CLAUDE_CODE_MESSAGING_SOCKET",
|
|
34
|
+
"CLAUDE_CODE_MESSAGING_TOKEN",
|
|
35
|
+
"CLAUDE_CODE_PROXY_RESOLVES_HOSTS",
|
|
36
|
+
"CLAUDE_CODE_SESSION_ATTENDED",
|
|
37
|
+
"CLAUDE_CODE_SESSION_ID",
|
|
38
|
+
"CLAUDE_CODE_SIMPLE", # --bare sets it (claude --help): no hooks, so no _hello
|
|
39
|
+
"CLAUDE_CODE_TMPDIR",
|
|
40
|
+
"CLAUDE_EFFORT",
|
|
41
|
+
"CLAUDE_ENV_FILE",
|
|
42
|
+
"CLAUDE_PID",
|
|
43
|
+
"CLAUDE_PROJECT_DIR",
|
|
44
|
+
"CLAUDE_STREAM_IDLE_TIMEOUT_MS",
|
|
45
|
+
"CLAUDE_TMPDIR",
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
# Flags the tool sets itself, or that make no sense for an interactive member; one text per set.
|
|
50
|
+
SESSION = frozenset(
|
|
51
|
+
{
|
|
52
|
+
"--session-id",
|
|
53
|
+
"-r",
|
|
54
|
+
"--resume",
|
|
55
|
+
"-c",
|
|
56
|
+
"--continue",
|
|
57
|
+
"--fork-session",
|
|
58
|
+
"--from-pr",
|
|
59
|
+
"--teleport",
|
|
60
|
+
"--resume-session-at",
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
APPEND_FILE = "--append-system-prompt-file" # the last one wins: it would replace the note
|
|
64
|
+
OWNED = SESSION | {
|
|
65
|
+
APPEND_FILE,
|
|
66
|
+
"--settings",
|
|
67
|
+
"--debug-file",
|
|
68
|
+
"-w",
|
|
69
|
+
"--worktree",
|
|
70
|
+
"--tmux",
|
|
71
|
+
"--messaging-socket-path",
|
|
72
|
+
}
|
|
73
|
+
NAMING = frozenset({"-n", "--name"})
|
|
74
|
+
OWN = frozenset({"-v", "--version", "-h", "--help"})
|
|
75
|
+
PRINT = frozenset({"-p", "--print"})
|
|
76
|
+
NO_SENSE = frozenset(
|
|
77
|
+
{
|
|
78
|
+
# print-only companions ("only works with --print", claude --help)
|
|
79
|
+
"--output-format",
|
|
80
|
+
"--input-format",
|
|
81
|
+
"--json-schema",
|
|
82
|
+
"--max-budget-usd",
|
|
83
|
+
"--include-partial-messages",
|
|
84
|
+
"--replay-user-messages",
|
|
85
|
+
"--no-session-persistence",
|
|
86
|
+
"--bg",
|
|
87
|
+
"--background",
|
|
88
|
+
"--cloud",
|
|
89
|
+
"--remote-control",
|
|
90
|
+
"--remote-control-session-name-prefix",
|
|
91
|
+
"--desktop",
|
|
92
|
+
"--file",
|
|
93
|
+
"--brief",
|
|
94
|
+
"--restricted",
|
|
95
|
+
"--bare",
|
|
96
|
+
"--safe-mode",
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
KNOWN = NAMING | OWNED | OWN | PRINT | NO_SENSE # the flags the gate answers by name
|
|
101
|
+
# The shapes 2.1.332's parser reads as a flag; any other token, '- keep diffs' too, is a value.
|
|
102
|
+
FLAG = re.compile(r"--.|-[A-Za-z]")
|
|
103
|
+
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Choice(NamedTuple):
|
|
107
|
+
"""A session's model or effort."""
|
|
108
|
+
|
|
109
|
+
value: str
|
|
110
|
+
at: datetime # when the session came to this value
|
|
111
|
+
first: bool # still the value it was started with, rather than one it changed to
|
|
112
|
+
typed: bool # a `/model` or `/effort` the user ran and Claude Code confirmed
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
COMMAND = re.compile(
|
|
116
|
+
r"<command-name>/(model|effort)</command-name>.*?<command-args>(.*?)</command-args>", re.S
|
|
117
|
+
)
|
|
118
|
+
STDOUT = re.compile(r"<local-command-stdout>(.*?)</local-command-stdout>", re.S)
|
|
119
|
+
SET_EFFORT = re.compile(r"^Set effort level to (" + "|".join(EFFORTS) + r")\b")
|
|
120
|
+
SET_MODEL = re.compile(r"^Set model to `")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# A member's `link send` asks the owner however its command is wrapped. The ask rule matches the
|
|
124
|
+
# text after Claude Code strips the wrappers it knows, never inside `sh -c '...'`, which with the
|
|
125
|
+
# sandbox off and `Bash(*)` ran unasked; a PreToolUse hook's `ask` beats any allow rule (ran:
|
|
126
|
+
# 2.1.332). The hook gets one line of compact JSON (captured), and `tool_input.command` is a JSON
|
|
127
|
+
# string, which holds no unescaped `"`. One grep costs 0.9 ms a Bash call; Python, 10 ms on every
|
|
128
|
+
# call of every member.
|
|
129
|
+
_LINK_SEND = r'"command":"([^"\\]|\\.)*workcrew([^"\\]|\\.)*link([^"\\]|\\.)*send'
|
|
130
|
+
_ASK = json.dumps(
|
|
131
|
+
{
|
|
132
|
+
"hookSpecificOutput": {
|
|
133
|
+
"hookEventName": "PreToolUse",
|
|
134
|
+
"permissionDecision": "ask",
|
|
135
|
+
"permissionDecisionReason": "workcrew link send needs the owner to approve it",
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
)
|
|
139
|
+
_ASK_LINK_SEND = f"if grep -qE '{_LINK_SEND}'; then printf '%s\\n' '{_ASK}'; fi"
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# The two flags a tail after `resume MEMBER…` takes, with the shape each value keeps and the line
|
|
143
|
+
# naming what the flag wants. A value reaches Claude Code as an argv entry, never a tmux format
|
|
144
|
+
# and never a shell (rules 2 and 3), so a pattern is what guards it.
|
|
145
|
+
MEMBER_FLAGS: dict[str, tuple[re.Pattern[str], str]] = {
|
|
146
|
+
"--model": (
|
|
147
|
+
re.compile(r"[a-z0-9][a-z0-9.-]{0,63}(\[1m\])?"),
|
|
148
|
+
"--model takes a model name like haiku, sonnet, opus or claude-opus-5-5.",
|
|
149
|
+
),
|
|
150
|
+
"--effort": (
|
|
151
|
+
re.compile("|".join(EFFORTS)),
|
|
152
|
+
f"--effort takes one of {', '.join(EFFORTS[:-1])} or {EFFORTS[-1]}.",
|
|
153
|
+
),
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Claude:
|
|
158
|
+
def check(self) -> None:
|
|
159
|
+
try:
|
|
160
|
+
out = subprocess.run(
|
|
161
|
+
["claude", "--version"], # noqa: S607 -- the user's own claude, from PATH
|
|
162
|
+
capture_output=True,
|
|
163
|
+
text=True,
|
|
164
|
+
check=False,
|
|
165
|
+
).stdout.strip()
|
|
166
|
+
except FileNotFoundError:
|
|
167
|
+
raise Refused(
|
|
168
|
+
"'claude' is not on PATH, and every member of the team is a Claude Code session.\n"
|
|
169
|
+
"Install Claude Code (https://code.claude.com/docs), then run workcrew again."
|
|
170
|
+
) from None
|
|
171
|
+
have = out.split(" ", 1)[0]
|
|
172
|
+
m = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", have)
|
|
173
|
+
if not m or tuple(int(g) for g in m.groups()) < NEED:
|
|
174
|
+
raise Refused(
|
|
175
|
+
f"Claude Code {have} is too old; workcrew needs 2.1.225 or newer for messages "
|
|
176
|
+
"between sessions.\nRun 'claude update', then run workcrew again."
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def member_flags(self, flags: Sequence[str]) -> None:
|
|
180
|
+
"""The tail after `resume MEMBER…`, which starts those members on a model and an effort.
|
|
181
|
+
Nothing else is taken: a third flag could switch off another member's permission checks.
|
|
182
|
+
The team's own tail is the owner's and keeps everything `gate` allows."""
|
|
183
|
+
seen: list[str] = []
|
|
184
|
+
i = 0
|
|
185
|
+
while i < len(flags):
|
|
186
|
+
flag = flags[i]
|
|
187
|
+
if flag not in MEMBER_FLAGS:
|
|
188
|
+
raise UsageError(
|
|
189
|
+
f"{flag!r} is not one of the two flags a member's tail takes,"
|
|
190
|
+
" --model and --effort."
|
|
191
|
+
)
|
|
192
|
+
if flag in seen:
|
|
193
|
+
raise UsageError(f"{flag!r} is given once in a member's tail.")
|
|
194
|
+
seen.append(flag)
|
|
195
|
+
shape, wants = MEMBER_FLAGS[flag]
|
|
196
|
+
if i + 1 == len(flags):
|
|
197
|
+
raise UsageError(wants)
|
|
198
|
+
value = flags[i + 1]
|
|
199
|
+
if shape.fullmatch(value) is None:
|
|
200
|
+
raise UsageError(f"{value!r} is not a value for {flag!r}.\n{wants}")
|
|
201
|
+
i += 2
|
|
202
|
+
|
|
203
|
+
def gate(self, flags: Sequence[str]) -> None:
|
|
204
|
+
for i, tok in enumerate(flags):
|
|
205
|
+
if tok == "--": # workcrew's own --model and --effort would follow it as prompt text
|
|
206
|
+
raise UsageError(
|
|
207
|
+
"'--' is not a flag; everything after the first '--' is already "
|
|
208
|
+
"Claude Code's.\nDrop the second '--'."
|
|
209
|
+
)
|
|
210
|
+
if not FLAG.match(tok):
|
|
211
|
+
if i == 0: # a goal typed after `--`; later bare words are values of flags
|
|
212
|
+
raise UsageError(
|
|
213
|
+
f"everything after '--' is Claude Code flags, and '{tok}' is not a flag.\n"
|
|
214
|
+
"To give the leader its goal, type it in the leader's pane."
|
|
215
|
+
)
|
|
216
|
+
continue
|
|
217
|
+
flag = tok.split("=", 1)[0]
|
|
218
|
+
# As it stands: a short flag that takes a value takes the rest of its token, '=' too.
|
|
219
|
+
# One with its own answer below still gets that answer.
|
|
220
|
+
if not tok.startswith("--") and len(tok) > 2 and not (len(flag) == 2 and flag in KNOWN):
|
|
221
|
+
raise UsageError(
|
|
222
|
+
f"'{tok}' is not one flag; write short flags separately, "
|
|
223
|
+
"and a flag's value after a space."
|
|
224
|
+
)
|
|
225
|
+
if flag in NAMING:
|
|
226
|
+
name = _value(flags, i) or "NAME"
|
|
227
|
+
raise UsageError(
|
|
228
|
+
f"there is no '{flag}'. To name a new team: workcrew --name {name}."
|
|
229
|
+
f" To rename a team: workcrew rename {name}."
|
|
230
|
+
)
|
|
231
|
+
if flag in OWNED:
|
|
232
|
+
how = (
|
|
233
|
+
"workcrew gives every member its own --session-id and resumes it for you. "
|
|
234
|
+
f"Drop '{flag}'."
|
|
235
|
+
if flag in SESSION
|
|
236
|
+
# both reach the member (ran: 2.1.332)
|
|
237
|
+
else "Drop it; to add to every member's instructions, use "
|
|
238
|
+
"--append-system-prompt TEXT."
|
|
239
|
+
if flag == APPEND_FILE
|
|
240
|
+
# all three reach the member (ran: 2.1.332)
|
|
241
|
+
else "Put those settings in ~/.claude/settings.json, .claude/settings.json or"
|
|
242
|
+
" .claude/settings.local.json: every member reads them."
|
|
243
|
+
if flag == "--settings"
|
|
244
|
+
else f"Drop '{flag}'."
|
|
245
|
+
)
|
|
246
|
+
raise UsageError(
|
|
247
|
+
f"'{flag}' is workcrew's to set, so it cannot be passed through.\n{how}"
|
|
248
|
+
)
|
|
249
|
+
if flag in OWN:
|
|
250
|
+
raise UsageError(
|
|
251
|
+
f"'{flag}' is workcrew's own, so it cannot be passed through.\n"
|
|
252
|
+
f"Run workcrew --version or workcrew --help; drop '{flag}' from the flags "
|
|
253
|
+
"after '--'."
|
|
254
|
+
)
|
|
255
|
+
if flag in PRINT:
|
|
256
|
+
raise UsageError(
|
|
257
|
+
f"'{flag}' makes no sense for a member; every member is an interactive "
|
|
258
|
+
f"session.\nDrop '{flag}'. To give the leader its goal, type it in the leader's"
|
|
259
|
+
" pane."
|
|
260
|
+
)
|
|
261
|
+
if flag in NO_SENSE:
|
|
262
|
+
raise UsageError(f"'{flag}' makes no sense for a member.\nDrop '{flag}'.")
|
|
263
|
+
|
|
264
|
+
def new_id(self) -> str:
|
|
265
|
+
return str(uuid.uuid4())
|
|
266
|
+
|
|
267
|
+
def argv(self, r: Roster, m: Member, note: Path, payload: Path) -> list[str]:
|
|
268
|
+
t = _transcript(r.cwd, m.session_id)
|
|
269
|
+
ident = "--resume" if t.exists() else "--session-id"
|
|
270
|
+
return [
|
|
271
|
+
"claude",
|
|
272
|
+
ident,
|
|
273
|
+
m.session_id,
|
|
274
|
+
"--name",
|
|
275
|
+
f"{r.key}-{m.name}",
|
|
276
|
+
"--settings",
|
|
277
|
+
str(payload),
|
|
278
|
+
"--append-system-prompt-file",
|
|
279
|
+
str(note),
|
|
280
|
+
*r.flags,
|
|
281
|
+
*m.flags,
|
|
282
|
+
# Both times are written by the same clock in the same width, so the later string is
|
|
283
|
+
# the later time, and a choice the member made itself wins only when it is newer.
|
|
284
|
+
# The flag names the owner's flags hold: Claude Code reads `--model=opus` as the
|
|
285
|
+
# flag `--model`, and the gate takes it as ours written that way too.
|
|
286
|
+
*_newer(t, max(r.flags_at, m.flags_at), _names(r.flags, m.flags)),
|
|
287
|
+
]
|
|
288
|
+
|
|
289
|
+
def env(self, base: Mapping[str, str], tmpdir: Path) -> dict[str, str]:
|
|
290
|
+
out = {k: v for k, v in base.items() if k not in SESSION_ENV}
|
|
291
|
+
out["TMPDIR"] = str(tmpdir)
|
|
292
|
+
return out
|
|
293
|
+
|
|
294
|
+
def payload(self, hooks: Mapping[str, str], bin: str) -> bytes:
|
|
295
|
+
def on(command: str, matcher: str | None = None) -> list[dict[str, object]]:
|
|
296
|
+
group: dict[str, object] = {"hooks": [{"type": "command", "command": command}]}
|
|
297
|
+
return [{"matcher": matcher, **group} if matcher else group]
|
|
298
|
+
|
|
299
|
+
settings = {
|
|
300
|
+
"hooks": {
|
|
301
|
+
"SessionStart": on(f"{shlex.quote(bin)} _hello", "startup|resume|clear|compact"),
|
|
302
|
+
"PreToolUse": on(_ASK_LINK_SEND, "Bash"),
|
|
303
|
+
# Not PermissionRequest: it fires for a request another hook allows, with no prompt
|
|
304
|
+
# shown; this fires 6.0 s after a prompt nobody has answered (ran: 2.1.332).
|
|
305
|
+
"Notification": on(hooks["wait"], "permission_prompt|elicitation_dialog"),
|
|
306
|
+
"UserPromptSubmit": on(hooks["busy"]),
|
|
307
|
+
"PostToolUse": on(hooks["busy"]),
|
|
308
|
+
"PostToolUseFailure": on(hooks["busy"]),
|
|
309
|
+
# a worker's stop may be refused, so the tool answers it; a failed turn is only told
|
|
310
|
+
"Stop": on(f"{shlex.quote(bin)} _idle"),
|
|
311
|
+
"StopFailure": on(f"{shlex.quote(bin)} _idle failed"),
|
|
312
|
+
},
|
|
313
|
+
# Without these a member's workcrew command waits for approval (ran: 2.1.332, the
|
|
314
|
+
# owner's own settings left out). No contract key: an owner whose settings allow
|
|
315
|
+
# Bash(*) passes it anyway. Every member gets the leader's commands: the tool refuses a
|
|
316
|
+
# worker them by identity.
|
|
317
|
+
"permissions": {
|
|
318
|
+
"allow": [
|
|
319
|
+
"Bash(workcrew board)",
|
|
320
|
+
"Bash(workcrew board *)",
|
|
321
|
+
"Bash(workcrew send *)",
|
|
322
|
+
"Bash(workcrew add)",
|
|
323
|
+
"Bash(workcrew add *)",
|
|
324
|
+
"Bash(workcrew remove *)",
|
|
325
|
+
"Bash(workcrew rename *)",
|
|
326
|
+
"Bash(workcrew layout *)",
|
|
327
|
+
"Bash(workcrew resume)",
|
|
328
|
+
"Bash(workcrew resume *)",
|
|
329
|
+
"Bash(workcrew link)",
|
|
330
|
+
"Bash(workcrew link read*)",
|
|
331
|
+
],
|
|
332
|
+
"ask": ["Bash(workcrew link send *)"],
|
|
333
|
+
},
|
|
334
|
+
"sandbox": {"excludedCommands": ["workcrew *"]},
|
|
335
|
+
# With no value, a member that bypasses permission prompts holds each of workcrew's
|
|
336
|
+
# messages for approval (Claude Code docs, cross-session messaging, "Control inbound
|
|
337
|
+
# messages").
|
|
338
|
+
"crossSessionInbound": "accept",
|
|
339
|
+
}
|
|
340
|
+
return (json.dumps(settings, indent=1) + "\n").encode()
|
|
341
|
+
|
|
342
|
+
def hello(self, stdin: bytes, env: Mapping[str, str]) -> Hello:
|
|
343
|
+
d = json.loads(stdin)
|
|
344
|
+
return Hello(
|
|
345
|
+
session_id=d["session_id"],
|
|
346
|
+
inbox=env.get("CLAUDE_CODE_MESSAGING_SOCKET") or None,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
def trusted(self, folder: Path) -> bool:
|
|
350
|
+
try:
|
|
351
|
+
projects = json.loads(_config_file().read_text()).get("projects", {})
|
|
352
|
+
except OSError:
|
|
353
|
+
return False
|
|
354
|
+
here = folder
|
|
355
|
+
# Claude Code asks once per project root: a git repository's top level, whose trust is
|
|
356
|
+
# its own, or else the folder, which a trusted parent covers (ran with real members).
|
|
357
|
+
root = next((p for p in (here, *here.parents) if (p / ".git").exists()), None)
|
|
358
|
+
for p in [root] if root else [here, *here.parents]:
|
|
359
|
+
if projects.get(str(p), {}).get("hasTrustDialogAccepted"):
|
|
360
|
+
return True
|
|
361
|
+
return False
|
|
362
|
+
|
|
363
|
+
def deliver(self, inbox: str | None, sender: str, text: str) -> bool:
|
|
364
|
+
if not inbox:
|
|
365
|
+
return False
|
|
366
|
+
body = escape(text)
|
|
367
|
+
content = f'<cross-session-message from-name="{sender}">\n{body}\n</cross-session-message>'
|
|
368
|
+
line = json.dumps({"type": "user", "message": {"role": "user", "content": content}})
|
|
369
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
|
|
370
|
+
try:
|
|
371
|
+
s.connect(inbox)
|
|
372
|
+
s.sendall(line.encode() + b"\n") # the inbox never acknowledges
|
|
373
|
+
# No file, a stale file after kill -9, nobody listening, or a session that ended
|
|
374
|
+
# between the connect and the write.
|
|
375
|
+
except OSError:
|
|
376
|
+
return False
|
|
377
|
+
return True
|
|
378
|
+
|
|
379
|
+
rows = claude_screen.ROWS
|
|
380
|
+
columns = claude_screen.COLUMNS
|
|
381
|
+
kept_columns = 8
|
|
382
|
+
|
|
383
|
+
def screen(self, text: str) -> Screen:
|
|
384
|
+
return claude_screen.classify(text)
|
|
385
|
+
|
|
386
|
+
def stopping(self, stdin: bytes) -> bool:
|
|
387
|
+
"""Whether this stop ends a turn the Stop hook already refused (ran: 2.1.332)."""
|
|
388
|
+
return json.loads(stdin).get("stop_hook_active") is True
|
|
389
|
+
|
|
390
|
+
def background(self, stdin: bytes) -> Background:
|
|
391
|
+
"""The member's own background work this stop leaves running. A subagent ends, and Claude
|
|
392
|
+
Code then starts the member's next turn: "wakes". Anything else may never end, a shell
|
|
393
|
+
running a dev server or a monitor: "runs". A subagent's own background shell is listed
|
|
394
|
+
as a shell (ran: 2.1.332)."""
|
|
395
|
+
tasks = json.loads(stdin).get("background_tasks") or []
|
|
396
|
+
running = {t.get("type") for t in tasks if t.get("status") == "running"}
|
|
397
|
+
if "subagent" in running:
|
|
398
|
+
return "wakes"
|
|
399
|
+
return "runs" if running else ""
|
|
400
|
+
|
|
401
|
+
def refuse(self, reason: str) -> str:
|
|
402
|
+
"""What the Stop hook prints to send the member back to work with `reason`. Feedback, not a
|
|
403
|
+
block: the turn goes on the same way, and the pane says "Stop hook says:", not "Stop hook
|
|
404
|
+
reported a problem" (Claude Code CHANGELOG 2.1.163; ran: 2.1.332)."""
|
|
405
|
+
out = {"hookEventName": "Stop", "additionalContext": escape(reason)}
|
|
406
|
+
return json.dumps({"hookSpecificOutput": out})
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _value(flags: Sequence[str], i: int) -> str | None:
|
|
410
|
+
tok = flags[i]
|
|
411
|
+
if "=" in tok:
|
|
412
|
+
return tok.split("=", 1)[1]
|
|
413
|
+
nxt = flags[i + 1] if i + 1 < len(flags) else None
|
|
414
|
+
return nxt if nxt and not nxt.startswith("-") else None
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _config_dir() -> Path | None:
|
|
418
|
+
d = os.environ.get("CLAUDE_CONFIG_DIR")
|
|
419
|
+
return Path(d) if d else None
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def _config_file() -> Path:
|
|
423
|
+
return (_config_dir() or Path.home()) / ".claude.json"
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _transcript(cwd: str, session_id: str) -> Path:
|
|
427
|
+
base = _config_dir() or Path.home() / ".claude"
|
|
428
|
+
return base / "projects" / re.sub(r"[^A-Za-z0-9]", "-", cwd) / f"{session_id}.jsonl"
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _newer(transcript: Path, flags_at: str, named: Container[str]) -> list[str]:
|
|
432
|
+
"""The member's own model and effort, where the session's own value still holds. A flag the
|
|
433
|
+
owner's flags name is overridden only by a value the session changed to after they were set:
|
|
434
|
+
where the session is simply still on the value it started with, the flags are what it was
|
|
435
|
+
started with. A flag nobody names has only the session to say what it is, so its value is
|
|
436
|
+
passed again where the session came to it after the flags, or ran a command for it at any
|
|
437
|
+
time: flags that name a model say nothing about an effort a person typed."""
|
|
438
|
+
since = datetime.fromisoformat(flags_at)
|
|
439
|
+
choice = _last_choice(transcript)
|
|
440
|
+
out: list[str] = []
|
|
441
|
+
for flag in ("--model", "--effort"):
|
|
442
|
+
if flag not in choice:
|
|
443
|
+
continue
|
|
444
|
+
c = choice[flag]
|
|
445
|
+
kept = (c.at > since and not c.first) if flag in named else (c.at > since or c.typed)
|
|
446
|
+
if kept:
|
|
447
|
+
out += [flag, c.value]
|
|
448
|
+
return out
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _names(*flags: Sequence[str]) -> set[str]:
|
|
452
|
+
return {w.split("=", 1)[0] for f in flags for w in f}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _chose(best: dict[str, Choice], flag: str, value: str, at: datetime) -> None:
|
|
456
|
+
"""When the session came to the value it is on, and whether that value is simply where it was
|
|
457
|
+
started. A request carries the value in use, not a choice made at that moment, so one equal to
|
|
458
|
+
the value before it moves nothing."""
|
|
459
|
+
if flag not in best:
|
|
460
|
+
best[flag] = Choice(value, at, True, False)
|
|
461
|
+
elif best[flag][0] != value:
|
|
462
|
+
best[flag] = Choice(value, at, False, False)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _last_choice(transcript: Path) -> dict[str, Choice]:
|
|
466
|
+
"""The last request's model and effort, superseded by a later /model or /effort that Claude
|
|
467
|
+
Code confirmed. Anything not understood leaves the request's values."""
|
|
468
|
+
best: dict[str, Choice] = {}
|
|
469
|
+
typed: tuple[str, str, datetime] | None = None # (flag, argument, time) awaiting its stdout
|
|
470
|
+
try:
|
|
471
|
+
lines = transcript.read_text(errors="replace").split("\n")
|
|
472
|
+
except OSError:
|
|
473
|
+
return best
|
|
474
|
+
for line in lines[:-1]: # the last element is "" or a torn line, which is skipped
|
|
475
|
+
# A killed run's torn record, or a crash's NULs, can sit inside, with records after it.
|
|
476
|
+
try:
|
|
477
|
+
d = json.loads(line)
|
|
478
|
+
except ValueError:
|
|
479
|
+
continue
|
|
480
|
+
at = _time(d.get("timestamp"))
|
|
481
|
+
if at is None:
|
|
482
|
+
continue
|
|
483
|
+
if d.get("type") == "api-request":
|
|
484
|
+
# A request carries the value the session is on, not a choice made at that moment,
|
|
485
|
+
# so it moves the time only where it differs from the value before it.
|
|
486
|
+
p = d.get("params") or {}
|
|
487
|
+
_chose(best, "--model", p["model"], at)
|
|
488
|
+
effort = (p.get("output_config") or {}).get("effort")
|
|
489
|
+
if effort in EFFORTS:
|
|
490
|
+
_chose(best, "--effort", effort, at)
|
|
491
|
+
continue
|
|
492
|
+
# A typed /model or /effort carries no origin (ran: 2.1.332); an inbox message carries
|
|
493
|
+
# "peer", a typed or pasted prompt "human", and neither is a command even if it quotes one.
|
|
494
|
+
if d.get("origin"):
|
|
495
|
+
continue
|
|
496
|
+
text = _text(d)
|
|
497
|
+
if c := COMMAND.search(text):
|
|
498
|
+
typed = ("--" + c.group(1), c.group(2).strip(), at)
|
|
499
|
+
continue
|
|
500
|
+
o = STDOUT.search(text)
|
|
501
|
+
if o and typed:
|
|
502
|
+
flag, arg, when = typed
|
|
503
|
+
typed = None
|
|
504
|
+
reply = o.group(1).strip()
|
|
505
|
+
if flag == "--effort" and (e := SET_EFFORT.match(reply)):
|
|
506
|
+
best[flag] = Choice(e.group(1), when, False, True)
|
|
507
|
+
elif flag == "--model" and arg and SET_MODEL.match(reply):
|
|
508
|
+
best[flag] = Choice(arg, when, False, True)
|
|
509
|
+
return best
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _text(d: dict[str, object]) -> str:
|
|
513
|
+
message = d.get("message")
|
|
514
|
+
c = (
|
|
515
|
+
d.get("content")
|
|
516
|
+
if d.get("type") == "system"
|
|
517
|
+
else (message.get("content") if isinstance(message, dict) else None)
|
|
518
|
+
)
|
|
519
|
+
return c if isinstance(c, str) else ""
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
def _time(s: object) -> datetime | None:
|
|
523
|
+
return datetime.fromisoformat(s) if isinstance(s, str) else None
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""What Claude Code's screen shows: which of the six `Screen` states a captured pane is in.
|
|
2
|
+
|
|
3
|
+
The shapes come from Claude Code 2.1.332 captured with `tmux capture-pane -p -e`.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
|
|
8
|
+
from workcrew.harness import Screen
|
|
9
|
+
|
|
10
|
+
_ESC = re.compile(r"\x1b\[[0-9;:?]*[A-Za-z]")
|
|
11
|
+
# A permission prompt's " Do you want to proceed?" takes one line from 25 columns and wraps
|
|
12
|
+
# below, unseen (2.1.332): nothing is typed into a narrower pane.
|
|
13
|
+
COLUMNS = 25
|
|
14
|
+
# Claude Code draws its rules as wide as the pane, down to 8 columns (2.1.332): every
|
|
15
|
+
# recorded screen reads the same with 8 as with 20, and a narrow pane only with 8.
|
|
16
|
+
_RULE = "─" * 8
|
|
17
|
+
# The box's top rule ends with the session's name, " name ─", with dashes before it where they
|
|
18
|
+
# fit and the name cut with "…" where it does not (2.1.332).
|
|
19
|
+
_NAMED = re.compile(r"─* \S.* ─")
|
|
20
|
+
# The box and a three-row status line take 6 rows; at 7 the top rule scrolls off (2.1.332).
|
|
21
|
+
ROWS = 8
|
|
22
|
+
# the box's top rule once a draft taller than the box has scrolled: "─── ↑ 1 more ───"
|
|
23
|
+
_SCROLLED = "─── ↑"
|
|
24
|
+
_DIM = "\x1b[2m" # the input box's placeholder is drawn dim; typed text is not
|
|
25
|
+
_MARK = "\u276f" # the prompt mark that starts the input box and a selected item
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def classify(text: str) -> Screen:
|
|
29
|
+
raw = text.splitlines()
|
|
30
|
+
plain = [_ESC.sub("", line).rstrip() for line in raw]
|
|
31
|
+
# The input box is the lowest two rules with the mark right under the first; earlier prompts
|
|
32
|
+
# in the transcript also start with the mark in column 0. A permission prompt hides the box
|
|
33
|
+
# and draws its own rule, so what lies below the lowest rule decides.
|
|
34
|
+
rules = _rules(plain)
|
|
35
|
+
lowest = plain[rules[-1] + 1 :] if rules else plain
|
|
36
|
+
if any("Do you want to proceed?" in line for line in lowest):
|
|
37
|
+
return "prompt"
|
|
38
|
+
if len(rules) > 1 and plain[rules[-2]].startswith(_SCROLLED):
|
|
39
|
+
return "draft"
|
|
40
|
+
box = len(rules) > 1 and plain[rules[-2] + 1].startswith(_MARK)
|
|
41
|
+
if box and _typed(raw[rules[-2] + 1 : rules[-1]]):
|
|
42
|
+
# A list under a box that holds typed text is its completion: Claude Code draws the
|
|
43
|
+
# matching slash commands under the box when there is room below it (2.1.332).
|
|
44
|
+
return "draft"
|
|
45
|
+
# Under a box with nothing typed in it lies only its footer. A selection there is a picker or
|
|
46
|
+
# dialog drawn below a box the transcript quotes, or one a resize left (claude-code#52660).
|
|
47
|
+
if not box or any(line.lstrip().startswith(_MARK) for line in lowest):
|
|
48
|
+
return _listed(plain)
|
|
49
|
+
if any("esc to interrupt" in line for line in plain):
|
|
50
|
+
return "busy"
|
|
51
|
+
return "empty"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _rules(plain: list[str]) -> list[int]:
|
|
55
|
+
"""The rules' lines. One with a name is only ever the top of a box: the mark right under it,
|
|
56
|
+
and as long as the next all-dash rule below, since both span the pane."""
|
|
57
|
+
dashed = [i for i, line in enumerate(plain) if line.startswith((_RULE, _SCROLLED))]
|
|
58
|
+
bottoms = [i for i in dashed if plain[i].startswith(_RULE)]
|
|
59
|
+
|
|
60
|
+
def top(i: int) -> bool:
|
|
61
|
+
below = next((j for j in bottoms if j > i + 1), None)
|
|
62
|
+
return (
|
|
63
|
+
plain[i + 1].startswith(_MARK)
|
|
64
|
+
and below is not None
|
|
65
|
+
and len(plain[below]) == len(plain[i])
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
named = [i for i, line in enumerate(plain[:-1]) if _NAMED.fullmatch(line) and top(i)]
|
|
69
|
+
return sorted(dashed + named)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _typed(box: list[str]) -> bool:
|
|
73
|
+
"""Whether the box's lines, from the mark down, hold text; a draft wraps or breaks onto the
|
|
74
|
+
lines below the mark."""
|
|
75
|
+
lines = [box[0].split(_MARK, 1)[1], *box[1:]]
|
|
76
|
+
return any(_ESC.sub("", s).strip() and not s.lstrip("\xa0 ").startswith(_DIM) for s in lines)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _listed(plain: list[str]) -> Screen:
|
|
80
|
+
"""A selection list without the input box: a slash command's picker; the trust question and
|
|
81
|
+
other dialogs end with "Enter to confirm"."""
|
|
82
|
+
selection = any(line.lstrip().startswith(_MARK) for line in plain)
|
|
83
|
+
confirm = any("Enter to confirm" in line for line in plain)
|
|
84
|
+
return "picker" if selection and not confirm else "dialog"
|