@ethlete/agent-rules 0.1.0-next.49 → 0.1.0-next.50
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.
- package/CHANGELOG.md +19 -0
- package/README.md +18 -1
- package/content/hooks/builder-idle-check.py +18 -2
- package/content/hooks/human-wait-check.py +167 -0
- package/content/mods/.claude-plugin/marketplace.json +10 -0
- package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +6 -0
- package/content/mods/plugins/codex-runs/hooks/hooks.json +1 -0
- package/content/mods/plugins/codex-runs/hooks/progress.ts +130 -0
- package/content/mods/plugins/codex-runs/hooks/register.tsx +103 -0
- package/content/mods/plugins/codex-runs/tsconfig.json +4 -0
- package/content/mods/plugins/codex-runs/types/index.d.ts +19 -0
- package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/e2e-progress/hooks/register.tsx +8 -1
- package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
- package/content/mods/plugins/status-line/hooks/line.ts +3 -2
- package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +6 -0
- package/content/mods/plugins/usage-line/hooks/codex.ts +52 -0
- package/content/mods/plugins/usage-line/hooks/format.ts +24 -0
- package/content/mods/plugins/usage-line/hooks/hooks.json +1 -0
- package/content/mods/plugins/usage-line/hooks/register.tsx +67 -0
- package/content/mods/plugins/usage-line/tsconfig.json +4 -0
- package/content/mods/plugins/usage-line/types/index.d.ts +5 -0
- package/content/rules/waiting-on-the-human.md +17 -0
- package/content/skills/agent-sessions/SKILL.md +3 -1
- package/content/skills/agent-sessions/agent-sessions.mjs +57 -19
- package/content/skills/codex-subagent/SKILL.md +8 -0
- package/content/skills/codex-subagent/codex-limit.mjs +106 -0
- package/package.json +1 -1
- package/src/lib/report-command.d.ts +1 -0
- package/src/lib/report-command.js +9 -5
- package/src/lib/report-command.js.map +1 -1
- package/src/lib/targets/claude-mods.js +1 -1
- package/src/lib/targets/claude-mods.js.map +1 -1
- package/src/lib/targets/hooks-shared.d.ts +2 -0
- package/src/lib/targets/hooks-shared.js +15 -6
- package/src/lib/targets/hooks-shared.js.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @ethlete/agent-rules
|
|
2
2
|
|
|
3
|
+
## 0.1.0-next.50
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- Add `codex-limit.mjs` to the codex-subagent skill: it prints the left share and reset time of the Codex 5h and weekly limit and exits non-zero when exhausted, so agents fall back to a Claude subagent.
|
|
8
|
+
- The usage-line mod shows the Codex 5h and weekly limit left, marked when exhausted.
|
|
9
|
+
|
|
10
|
+
### Patch Changes
|
|
11
|
+
|
|
12
|
+
- Fix the `codex-runs` and `e2e-progress` mods being refused at load: `atom` keys are now string literals and `$.fs` is no longer passed as a value.
|
|
13
|
+
- `ethlete-agents report` drops the running slice when its `slice-paths` entry is older than 2 hours.
|
|
14
|
+
- The `status-line` mod counts the rows of a queue table under a `# Warteschlange` heading of any level.
|
|
15
|
+
- The usage-line mod draws its usage as plain status line text instead of a pinned plugin notice.
|
|
16
|
+
- Use `agent-sessions restart --process --config <dir>` to switch a Claude session's saved config directory while resuming its handoff.
|
|
17
|
+
- `builder-idle-check` counts a Codex run in a `codex-<task>@<repo>` tmux session as a running subagent.
|
|
18
|
+
- Add a Claude Code pane for Codex run state, duration, and recent output filtered by launching session.
|
|
19
|
+
- `agent-sessions send` records the sender's tmux session, and every mailbox message names it.
|
|
20
|
+
- Add a usage-line Claude Code mod that shows the 5 hour and weekly usage with the reset time in the status line of every session.
|
|
21
|
+
|
|
3
22
|
## 0.1.0-next.49
|
|
4
23
|
|
|
5
24
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -382,6 +382,15 @@ Available hooks:
|
|
|
382
382
|
row waits when its `Stand` cell contains "wartet auf" or "Offen nur:". It fires once per
|
|
383
383
|
idle stop chain (`stop_hook_active` passes).
|
|
384
384
|
|
|
385
|
+
- **`human-wait-check`** (Claude Code only) - a `Stop` hook for builder and coordinator sessions
|
|
386
|
+
(the roles of `builder-idle-check`). When a turn ends with a question to the human (a line ending
|
|
387
|
+
in `?`) or a `! <command>` for the human to run, while fewer subagents and background commands run
|
|
388
|
+
than `builderSlots`, and free work is listed - open rows in the `builderIdle` queues (default
|
|
389
|
+
`plans/QUEUE.md`) or the `## Next steps` of the handoff the session resumed
|
|
390
|
+
(`.claude/handoffs/<name>.md`) - it blocks the stop once and names that work, so the session starts
|
|
391
|
+
an independent slice before it waits. With no queue and no handoff it stays silent. Enabling it also
|
|
392
|
+
emits `builder-idle-check.py`, which it imports, without registering that hook.
|
|
393
|
+
|
|
385
394
|
- **`away-mode`** (Claude Code only) - switches an interactive session into "user is away" mode
|
|
386
395
|
on its own. Opt in with `"awayMode": { "skills": ["my-skill"], "thresholdMinutes": 15 }` in the
|
|
387
396
|
config (the local config overrides it); a session is tracked once a prompt starts with
|
|
@@ -400,19 +409,27 @@ Hooks can be turned off per machine - see the local config below.
|
|
|
400
409
|
package ships (`yarn agents:sync` writes the marketplace and `enabledPlugins` into
|
|
401
410
|
`.claude/settings.json`). A mod runs code in every session of the repo, so none is on by default.
|
|
402
411
|
|
|
412
|
+
- **`codex-runs`** - open the live tmux run list with `/codex-runs` and show a run's last captured lines with
|
|
413
|
+
`/codex-runs <name>`. `agent-sessions run <name> codex` records the launching Claude session ID.
|
|
414
|
+
For a direct tmux launch, pass `-e "ETHLETE_CODEX_OWNER=$CLAUDE_CODE_SESSION_ID"` to `tmux new-session`.
|
|
415
|
+
Runs without an owner appear in Claude sessions in the same checkout. The pane keeps observed runs and
|
|
416
|
+
their last captured output for an hour after they end.
|
|
403
417
|
- **`e2e-progress`** - live Playwright run progress as a status line entry and a pane.
|
|
404
418
|
- **`status-line`** - a band above the prompt, always visible: `▶ <running slice> · 42 min · 14 offen · ❓2`.
|
|
405
419
|
The slice comes from the git `slice-paths` file (`kein Slice` once it is older than 2 h), the queue
|
|
406
420
|
count from the `### Warteschlange` list of the `report.planFiles` markdown files, `❓N` from the
|
|
407
421
|
`-` lines of `<git common dir>/ethlete/open-questions.md`, and `⛔ CI rot` when the latest `gh run`
|
|
408
422
|
of the branch failed (checked every 2 minutes). A field whose source is missing is left out.
|
|
423
|
+
- **`usage-line`** - a status line entry in every session: `5h 36% bis 01:40 · Woche 42%`. The reset time is left
|
|
424
|
+
out when the window reports none. The Codex 5h and weekly limit left follows it (`⛔ codex 5h 0% (02:55) · wk 72%`,
|
|
425
|
+
read from `~/.codex/sessions`, the reset time shown only for an exhausted window).
|
|
409
426
|
|
|
410
427
|
## Progress report
|
|
411
428
|
|
|
412
429
|
`ethlete-agents report [today|yesterday|week | --since <date> [--until <date>]]` prints a fixed
|
|
413
430
|
markdown table of the period: one line per row with a feature, fix or other non-docs commit (short
|
|
414
431
|
sha, result), the parked rows, and a figures line (commit counts, reverts, red CI runs via `gh`,
|
|
415
|
-
subagent starts per model, the running slice). Without config it works from the git log alone.
|
|
432
|
+
subagent starts per model, the running slice unless its entry is older than 2 h). Without config it works from the git log alone.
|
|
416
433
|
Opt in to short names and the parked section with
|
|
417
434
|
`"report": { "planFiles": ["plans/STATUS.md", "plans/queue.md", "plans/rows.md"] }`: repo-relative paths
|
|
418
435
|
of markdown files holding `| <id> | <short name> | <what> | <state> | <what is missing> | <who> |` rows
|
|
@@ -21,6 +21,9 @@ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows
|
|
|
21
21
|
else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
|
|
22
22
|
`/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
|
|
23
23
|
|
|
24
|
+
A Codex run in a tmux session named `codex-<task>@<repo directory name>` counts as a running
|
|
25
|
+
subagent too: a builder starts them outside the transcript.
|
|
26
|
+
|
|
24
27
|
Fires at most once per idle stop chain: a stop that a Stop hook already
|
|
25
28
|
continued (`stop_hook_active`) passes.
|
|
26
29
|
|
|
@@ -37,6 +40,7 @@ Fail-safe: any error exits 0 with no output.
|
|
|
37
40
|
import json
|
|
38
41
|
import os
|
|
39
42
|
import re
|
|
43
|
+
import subprocess
|
|
40
44
|
import sys
|
|
41
45
|
from datetime import datetime
|
|
42
46
|
|
|
@@ -276,6 +280,17 @@ def running_tasks(state):
|
|
|
276
280
|
]
|
|
277
281
|
|
|
278
282
|
|
|
283
|
+
def codex_runs(root):
|
|
284
|
+
try:
|
|
285
|
+
names = subprocess.run(
|
|
286
|
+
["tmux", "list-sessions", "-F", "#{session_name}"], capture_output=True, text=True, timeout=5
|
|
287
|
+
).stdout.split()
|
|
288
|
+
except (OSError, subprocess.SubprocessError):
|
|
289
|
+
return []
|
|
290
|
+
suffix = "@" + os.path.basename(os.path.normpath(root))
|
|
291
|
+
return [name for name in names if name.startswith("codex-") and name.endswith(suffix)]
|
|
292
|
+
|
|
293
|
+
|
|
279
294
|
def waits(text, patterns):
|
|
280
295
|
lowered = text.lower()
|
|
281
296
|
return any(pattern.lower() in lowered for pattern in patterns)
|
|
@@ -353,7 +368,8 @@ def main():
|
|
|
353
368
|
return
|
|
354
369
|
read_earlier_agents(state, transcript_path)
|
|
355
370
|
running = running_tasks(state)
|
|
356
|
-
|
|
371
|
+
codex = codex_runs(root)
|
|
372
|
+
working = sum(1 for task in running if not task["watcher"]) + len(codex)
|
|
357
373
|
slots = slot_limit(config)
|
|
358
374
|
if working >= slots:
|
|
359
375
|
return
|
|
@@ -362,7 +378,7 @@ def main():
|
|
|
362
378
|
rows = open_builder_rows(root, sources, patterns)
|
|
363
379
|
if not rows:
|
|
364
380
|
return
|
|
365
|
-
watchers = [task["label"] for task in running]
|
|
381
|
+
watchers = [task["label"] for task in running] + codex
|
|
366
382
|
print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
|
|
367
383
|
except Exception:
|
|
368
384
|
return
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stop hook: a coordinator that asks the human starts the next independent slice first.
|
|
3
|
+
|
|
4
|
+
When a builder or coordinator session ends a turn with a question to the human (a line
|
|
5
|
+
ending in "?") or a `! <command>` for the human to run, while fewer subagents and background
|
|
6
|
+
commands run than the slot limit and free work is listed, the stop is blocked once. The
|
|
7
|
+
reason names the free work, so the turn goes on with a slice that does not need the answer.
|
|
8
|
+
|
|
9
|
+
Free work comes from two places, both read at runtime:
|
|
10
|
+
- the queues of the `builder-idle-check` hook (`builderIdle.queues` in the local config,
|
|
11
|
+
default `plans/QUEUE.md`): open rows without a wait pattern;
|
|
12
|
+
- the `## Next steps` list of the handoff the session resumed (`/handoff resume <name>` reads
|
|
13
|
+
`.claude/handoffs/<name>.md`).
|
|
14
|
+
With neither, the stop passes.
|
|
15
|
+
|
|
16
|
+
Session roles, the slot limit, wait patterns and running work are read exactly as the
|
|
17
|
+
`builder-idle-check` hook reads them; this script imports that file from its own directory.
|
|
18
|
+
Per-machine: {"disableHooks": ["human-wait-check"]} in ethlete-agents.config.local.json.
|
|
19
|
+
|
|
20
|
+
Fires at most once per stop chain: a stop that a Stop hook already continued
|
|
21
|
+
(`stop_hook_active`) passes. Fail-safe: any error exits 0 with no output.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import importlib.util
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
|
|
30
|
+
HOOK_NAME = "human-wait-check"
|
|
31
|
+
HANDOFF_DIR = os.path.join(".claude", "handoffs")
|
|
32
|
+
RESUME_ARGS = re.compile(r"<command-args>\s*resume\s+([\w.@-]+)")
|
|
33
|
+
NEXT_STEPS = re.compile(r"^#{2,3}\s+(?:next steps|nächste schritte)\b", re.I)
|
|
34
|
+
LIST_ITEM = re.compile(r"^(?:\d+[.)]|[-*])\s+(.*)$")
|
|
35
|
+
FENCE = re.compile(r"^\s*(?:```|~~~)")
|
|
36
|
+
HUMAN_COMMAND_LINE = re.compile(r"^\s*!\s+\S")
|
|
37
|
+
HUMAN_COMMAND_INLINE = re.compile(r"`!\s+[^`]+`")
|
|
38
|
+
TRAILING_MARKUP = " \t*_~`)\"'»“”]"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def load_idle_check():
|
|
42
|
+
sys.dont_write_bytecode = True
|
|
43
|
+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "builder-idle-check.py")
|
|
44
|
+
spec = importlib.util.spec_from_file_location("ethlete_builder_idle_check", path)
|
|
45
|
+
module = importlib.util.module_from_spec(spec)
|
|
46
|
+
spec.loader.exec_module(module)
|
|
47
|
+
return module
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def last_assistant_text(path):
|
|
51
|
+
text = None
|
|
52
|
+
resumed = None
|
|
53
|
+
with open(path, encoding="utf-8") as f:
|
|
54
|
+
for raw in f:
|
|
55
|
+
try:
|
|
56
|
+
line = json.loads(raw)
|
|
57
|
+
except ValueError:
|
|
58
|
+
continue
|
|
59
|
+
if not isinstance(line, dict) or line.get("isSidechain"):
|
|
60
|
+
continue
|
|
61
|
+
content = (line.get("message") or {}).get("content")
|
|
62
|
+
if line.get("type") == "user":
|
|
63
|
+
for chunk in content if isinstance(content, list) else [content]:
|
|
64
|
+
value = chunk.get("text") if isinstance(chunk, dict) else chunk
|
|
65
|
+
match = RESUME_ARGS.search(value) if isinstance(value, str) else None
|
|
66
|
+
if match:
|
|
67
|
+
resumed = match.group(1)
|
|
68
|
+
elif line.get("type") == "assistant" and isinstance(content, list):
|
|
69
|
+
texts = [item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text"]
|
|
70
|
+
if any(part.strip() for part in texts):
|
|
71
|
+
text = "\n".join(texts)
|
|
72
|
+
elif any(isinstance(item, dict) and item.get("type") == "tool_use" for item in content):
|
|
73
|
+
text = None
|
|
74
|
+
return text, resumed
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def asks_human(text):
|
|
78
|
+
in_fence = False
|
|
79
|
+
for line in text.splitlines():
|
|
80
|
+
if FENCE.match(line):
|
|
81
|
+
in_fence = not in_fence
|
|
82
|
+
continue
|
|
83
|
+
if HUMAN_COMMAND_LINE.match(line):
|
|
84
|
+
return True
|
|
85
|
+
if in_fence:
|
|
86
|
+
continue
|
|
87
|
+
if HUMAN_COMMAND_INLINE.search(line) or line.rstrip(TRAILING_MARKUP).endswith("?"):
|
|
88
|
+
return True
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def next_steps(root, resumed):
|
|
93
|
+
if not resumed:
|
|
94
|
+
return []
|
|
95
|
+
try:
|
|
96
|
+
with open(os.path.join(root, HANDOFF_DIR, f"{resumed}.md"), encoding="utf-8") as f:
|
|
97
|
+
lines = f.read().splitlines()
|
|
98
|
+
except OSError:
|
|
99
|
+
return []
|
|
100
|
+
steps = []
|
|
101
|
+
inside = False
|
|
102
|
+
for line in lines:
|
|
103
|
+
if line.startswith("#"):
|
|
104
|
+
inside = bool(NEXT_STEPS.match(line))
|
|
105
|
+
continue
|
|
106
|
+
match = LIST_ITEM.match(line) if inside else None
|
|
107
|
+
if match:
|
|
108
|
+
steps.append(match.group(1).strip()[:80])
|
|
109
|
+
return steps
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def reason_for(rows, steps, working, slots, resumed):
|
|
113
|
+
work = []
|
|
114
|
+
if rows:
|
|
115
|
+
work.append(f"open queue rows: {', '.join(rows)}")
|
|
116
|
+
if steps:
|
|
117
|
+
listed = "; ".join(f"{index}. {step}" for index, step in enumerate(steps, 1))
|
|
118
|
+
work.append(f"Next steps in {HANDOFF_DIR}/{resumed}.md: {listed}")
|
|
119
|
+
return (
|
|
120
|
+
f"[{HOOK_NAME} hook] This turn ends with a question or a `!` command for the human while {working} of {slots} "
|
|
121
|
+
f"slots are in use and free work is listed - {' | '.join(work)}. "
|
|
122
|
+
"Do not wait idle on the human: start the next slice that does not need the answer now (or a subagent on it), "
|
|
123
|
+
"then end the turn with the question again. If every listed item needs the answer, say which item waits on what. "
|
|
124
|
+
"If the human has allowed this action before, propose a permission rule for it in the settings (only the human "
|
|
125
|
+
"edits settings) instead of asking again. This hook fires once per stop."
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def main():
|
|
130
|
+
try:
|
|
131
|
+
data = json.load(sys.stdin)
|
|
132
|
+
if not isinstance(data, dict) or data.get("stop_hook_active"):
|
|
133
|
+
return
|
|
134
|
+
transcript_path = data.get("transcript_path")
|
|
135
|
+
if not isinstance(transcript_path, str):
|
|
136
|
+
return
|
|
137
|
+
idle = load_idle_check()
|
|
138
|
+
root = idle.repo_root(data)
|
|
139
|
+
config = idle.read_local_config(root)
|
|
140
|
+
disabled = config.get("disableHooks")
|
|
141
|
+
if disabled is True or (isinstance(disabled, list) and HOOK_NAME in disabled):
|
|
142
|
+
return
|
|
143
|
+
text, resumed = last_assistant_text(transcript_path)
|
|
144
|
+
if not text or not asks_human(text):
|
|
145
|
+
return
|
|
146
|
+
settings = idle.builder_idle_config(config)
|
|
147
|
+
roles = idle.string_list(settings.get("roles"), idle.DEFAULT_ROLES)
|
|
148
|
+
state = idle.read_transcript(transcript_path, idle.role_launch(roles))
|
|
149
|
+
if not state["builder"]:
|
|
150
|
+
return
|
|
151
|
+
idle.read_earlier_agents(state, transcript_path)
|
|
152
|
+
working = sum(1 for task in idle.running_tasks(state) if not task["watcher"]) + len(idle.codex_runs(root))
|
|
153
|
+
slots = idle.slot_limit(config)
|
|
154
|
+
if working >= slots:
|
|
155
|
+
return
|
|
156
|
+
patterns = idle.string_list(settings.get("waitPatterns"), idle.DEFAULT_WAIT_PATTERNS)
|
|
157
|
+
rows = idle.open_builder_rows(root, idle.queue_sources(settings), patterns)
|
|
158
|
+
steps = next_steps(root, resumed)
|
|
159
|
+
if not rows and not steps:
|
|
160
|
+
return
|
|
161
|
+
print(json.dumps({"decision": "block", "reason": reason_for(rows, steps, working, slots, resumed)}))
|
|
162
|
+
except Exception:
|
|
163
|
+
return
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
main()
|
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
"name": "ethlete",
|
|
3
3
|
"owner": { "name": "ethlete" },
|
|
4
4
|
"plugins": [
|
|
5
|
+
{
|
|
6
|
+
"name": "codex-runs",
|
|
7
|
+
"source": "./plugins/codex-runs",
|
|
8
|
+
"description": "Codex sessions in tmux with their state, duration, and recent output"
|
|
9
|
+
},
|
|
5
10
|
{
|
|
6
11
|
"name": "e2e-progress",
|
|
7
12
|
"source": "./plugins/e2e-progress",
|
|
@@ -11,6 +16,11 @@
|
|
|
11
16
|
"name": "status-line",
|
|
12
17
|
"source": "./plugins/status-line",
|
|
13
18
|
"description": "Always-visible band with the running task, its duration, the open queue, open questions and a CI blocked mark"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"name": "usage-line",
|
|
22
|
+
"source": "./plugins/usage-line",
|
|
23
|
+
"description": "Status line entry with the 5 hour and weekly usage, the reset time of the 5 hour window and the Codex limit"
|
|
14
24
|
}
|
|
15
25
|
]
|
|
16
26
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{ "modules": ["./register.tsx"] }
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
const SEPARATOR = '\t';
|
|
2
|
+
const PANE_FORMAT = [
|
|
3
|
+
'session_id',
|
|
4
|
+
'session_name',
|
|
5
|
+
'session_created',
|
|
6
|
+
'session_path',
|
|
7
|
+
'pane_id',
|
|
8
|
+
'pane_dead',
|
|
9
|
+
'pane_dead_time',
|
|
10
|
+
'pane_current_command',
|
|
11
|
+
'ETHLETE_CODEX_OWNER',
|
|
12
|
+
]
|
|
13
|
+
.map((field) => `#{${field}}`)
|
|
14
|
+
.join(SEPARATOR);
|
|
15
|
+
|
|
16
|
+
const KEEP_ENDED_MS = 60 * 60_000;
|
|
17
|
+
const TAIL_LINES = 12;
|
|
18
|
+
const CODEX_NAME = /^codex(?:-|@|$)/;
|
|
19
|
+
const INPUT_HINT = /\b(?:to submit (?:answer|all)|to confirm|to approve|to select)\b/i;
|
|
20
|
+
const WORKING_HINT = /\([^)]*\b(?:esc|ctrl\+c) to interrupt\)/i;
|
|
21
|
+
const PROMPT = /^\s*›(?:\s|$)/;
|
|
22
|
+
|
|
23
|
+
type TmuxResult = { stdout: string; stderr: string; exitCode: number | null };
|
|
24
|
+
type Tmux = (args: string[]) => Promise<TmuxResult>;
|
|
25
|
+
type Scope = { sessionId: string; root: string };
|
|
26
|
+
type Pane = {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
paneId: string;
|
|
30
|
+
cwd: string;
|
|
31
|
+
owner: string;
|
|
32
|
+
startedAt: number;
|
|
33
|
+
dead: boolean;
|
|
34
|
+
endedAt: number | null;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type CodexRun = Omit<Pane, 'dead' | 'paneId'> & {
|
|
38
|
+
state: 'running' | 'waiting for input' | 'ended';
|
|
39
|
+
tail: string[];
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const visibleTo = ({ owner, cwd }: { owner: string; cwd: string }, { sessionId, root }: Scope) =>
|
|
43
|
+
owner !== '' ? owner === sessionId : cwd === root || cwd.startsWith(`${root.replace(/\/$/, '')}/`);
|
|
44
|
+
|
|
45
|
+
function codexPanes(stdout: string): Pane[] {
|
|
46
|
+
const panes = new Map<string, { pane: Pane; rank: number }>();
|
|
47
|
+
for (const line of stdout.split('\n')) {
|
|
48
|
+
const [session, name, created, cwd, paneId, dead, ended, command, owner = ''] = line.split(SEPARATOR);
|
|
49
|
+
const startedAt = Number(created) * 1000;
|
|
50
|
+
if (!session || !name || !cwd || !paneId || !startedAt || !Number.isFinite(startedAt)) continue;
|
|
51
|
+
if (command !== 'codex' && !CODEX_NAME.test(name) && owner === '') continue;
|
|
52
|
+
const id = `${session}:${created}`;
|
|
53
|
+
const rank = dead === '1' ? 0 : command === 'codex' ? 2 : 1;
|
|
54
|
+
if ((panes.get(id)?.rank ?? -1) >= rank) continue;
|
|
55
|
+
panes.set(id, {
|
|
56
|
+
rank,
|
|
57
|
+
pane: {
|
|
58
|
+
id,
|
|
59
|
+
name,
|
|
60
|
+
paneId,
|
|
61
|
+
cwd,
|
|
62
|
+
owner,
|
|
63
|
+
startedAt,
|
|
64
|
+
dead: dead === '1',
|
|
65
|
+
endedAt: ended ? Number(ended) * 1000 || null : null,
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
return [...panes.values()].map(({ pane }) => pane);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function stateOf(lines: string[]): CodexRun['state'] {
|
|
73
|
+
const footer = lines.slice(-8);
|
|
74
|
+
if (footer.some((line) => !PROMPT.test(line) && INPUT_HINT.test(line))) return 'waiting for input';
|
|
75
|
+
if (footer.some((line) => !PROMPT.test(line) && WORKING_HINT.test(line))) return 'running';
|
|
76
|
+
return footer.some((line) => PROMPT.test(line)) ? 'waiting for input' : 'running';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function discoverRuns({
|
|
80
|
+
tmux,
|
|
81
|
+
scope,
|
|
82
|
+
previous,
|
|
83
|
+
now,
|
|
84
|
+
}: {
|
|
85
|
+
tmux: Tmux;
|
|
86
|
+
scope: Scope;
|
|
87
|
+
previous: CodexRun[];
|
|
88
|
+
now: number;
|
|
89
|
+
}): Promise<CodexRun[]> {
|
|
90
|
+
const result = await tmux(['list-panes', '-a', '-F', PANE_FORMAT]);
|
|
91
|
+
const oldRuns = previous.filter(
|
|
92
|
+
(run) => visibleTo(run, scope) && (run.endedAt === null || now - run.endedAt < KEEP_ENDED_MS),
|
|
93
|
+
);
|
|
94
|
+
if (result.exitCode !== 0 && !/no server running|no such file or directory/i.test(result.stderr)) return oldRuns;
|
|
95
|
+
|
|
96
|
+
const panes = codexPanes(result.stdout);
|
|
97
|
+
const present = new Set(panes.map((pane) => pane.id));
|
|
98
|
+
const oldById = new Map(oldRuns.map((run) => [run.id, run]));
|
|
99
|
+
const current = await Promise.all(
|
|
100
|
+
panes
|
|
101
|
+
.filter((pane) => visibleTo(pane, scope))
|
|
102
|
+
.map(async ({ paneId, dead, ...pane }): Promise<CodexRun> => {
|
|
103
|
+
const capture = await tmux(['capture-pane', '-p', '-t', paneId, '-S', '-20']);
|
|
104
|
+
const old = oldById.get(pane.id);
|
|
105
|
+
const lines = capture.stdout
|
|
106
|
+
.trimEnd()
|
|
107
|
+
.split('\n')
|
|
108
|
+
.filter((line) => line.trim() !== '');
|
|
109
|
+
return {
|
|
110
|
+
...pane,
|
|
111
|
+
endedAt: dead ? (pane.endedAt ?? old?.endedAt ?? now) : null,
|
|
112
|
+
state: dead ? 'ended' : stateOf(capture.exitCode === 0 ? lines : (old?.tail ?? [])),
|
|
113
|
+
tail: capture.exitCode === 0 ? lines.slice(-TAIL_LINES) : (old?.tail ?? []),
|
|
114
|
+
};
|
|
115
|
+
}),
|
|
116
|
+
);
|
|
117
|
+
const ended = oldRuns
|
|
118
|
+
.filter((run) => !present.has(run.id))
|
|
119
|
+
.map((run): CodexRun => ({ ...run, state: 'ended', endedAt: run.endedAt ?? now }));
|
|
120
|
+
return [...current, ...ended]
|
|
121
|
+
.filter((run) => run.endedAt === null || now - run.endedAt < KEEP_ENDED_MS)
|
|
122
|
+
.sort((a, b) => b.startedAt - a.startedAt || a.name.localeCompare(b.name));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function durationOf(run: CodexRun, now: number): string {
|
|
126
|
+
const seconds = Math.max(0, Math.floor(((run.endedAt ?? now) - run.startedAt) / 1000));
|
|
127
|
+
const hours = Math.floor(seconds / 3600);
|
|
128
|
+
const minutes = Math.floor((seconds % 3600) / 60);
|
|
129
|
+
return hours ? `${hours}h ${minutes}m` : minutes ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
|
|
130
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { atom, read, update } from 'claude-code';
|
|
2
|
+
import type { EngineInterface, Register, Timer } from 'claude-code';
|
|
3
|
+
|
|
4
|
+
import { discoverRuns, durationOf } from './progress';
|
|
5
|
+
|
|
6
|
+
const PANE = 'codex-runs';
|
|
7
|
+
const POLL_MS = 5000;
|
|
8
|
+
const PROCESS_TIMEOUT_MS = 2000;
|
|
9
|
+
const runs = atom({ plugin: 'codex-runs', key: 'runs' } as const, []);
|
|
10
|
+
const selected = atom({ plugin: 'codex-runs', key: 'selected' } as const, null);
|
|
11
|
+
|
|
12
|
+
let timer: Timer | undefined;
|
|
13
|
+
let pending: Promise<void> | undefined;
|
|
14
|
+
|
|
15
|
+
async function refresh($: EngineInterface) {
|
|
16
|
+
const [sessionId, root, now, previous] = await Promise.all([
|
|
17
|
+
$.session.id(),
|
|
18
|
+
$.session.root(),
|
|
19
|
+
$.clock.now(),
|
|
20
|
+
read($, runs),
|
|
21
|
+
]);
|
|
22
|
+
const checkout = await $.process
|
|
23
|
+
.run(['git', 'rev-parse', '--show-toplevel'], { cwd: root, timeoutMs: PROCESS_TIMEOUT_MS })
|
|
24
|
+
.catch(() => null);
|
|
25
|
+
const next = await discoverRuns({
|
|
26
|
+
tmux: (args) =>
|
|
27
|
+
$.process
|
|
28
|
+
.run(['tmux', ...args], { timeoutMs: PROCESS_TIMEOUT_MS })
|
|
29
|
+
.catch(() => ({ exitCode: null, stdout: '', stderr: '' })),
|
|
30
|
+
scope: { sessionId, root: checkout?.exitCode === 0 ? checkout.stdout.trimEnd() : root },
|
|
31
|
+
previous,
|
|
32
|
+
now,
|
|
33
|
+
});
|
|
34
|
+
if ((await $.session.id()) === sessionId) await update($, runs, () => next);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function poll($: EngineInterface) {
|
|
38
|
+
pending ??= refresh($)
|
|
39
|
+
.catch(() => undefined)
|
|
40
|
+
.finally(() => {
|
|
41
|
+
pending = undefined;
|
|
42
|
+
});
|
|
43
|
+
return pending;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function runsForSession($: EngineInterface) {
|
|
47
|
+
const [sessionId, shown] = await Promise.all([$.session.id(), read($, runs)]);
|
|
48
|
+
return shown.filter((run) => !run.owner || run.owner === sessionId);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const register: Register = (on) => {
|
|
52
|
+
on('session.start', async ($, e, next) => {
|
|
53
|
+
await $.command.register({
|
|
54
|
+
name: PANE,
|
|
55
|
+
description: 'List Codex runs. Pass a run name to show its last output lines.',
|
|
56
|
+
});
|
|
57
|
+
timer?.cancel();
|
|
58
|
+
timer = $.clock.every(POLL_MS, () => poll($));
|
|
59
|
+
await poll($);
|
|
60
|
+
return next(e);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
on('command.run', { command: PANE }, async ($, e) => {
|
|
64
|
+
await poll($);
|
|
65
|
+
const name = e.args.trim();
|
|
66
|
+
const run = name
|
|
67
|
+
? (await runsForSession($)).find((run) => run.name === name || run.name.startsWith(`${name}@`))
|
|
68
|
+
: undefined;
|
|
69
|
+
if (name && !run) return { text: `No visible Codex run named ${name}.` };
|
|
70
|
+
|
|
71
|
+
await update($, selected, () => run?.id ?? null);
|
|
72
|
+
await $.ui.open({ id: PANE, title: 'Codex runs' });
|
|
73
|
+
return { text: run ? `Showing recent output for ${run.name}.` : 'Codex runs pane opened.' };
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
|
|
77
|
+
const { Box, Text } = $.ui.resolve(e);
|
|
78
|
+
const [shown, selectedId, now] = await Promise.all([runsForSession($), read($, selected), $.clock.now()]);
|
|
79
|
+
if (shown.length === 0) return <Text dimColor>No Codex runs found.</Text>;
|
|
80
|
+
|
|
81
|
+
const run = shown.find((run) => run.id === selectedId);
|
|
82
|
+
return (
|
|
83
|
+
<Box flexDirection="column">
|
|
84
|
+
{shown.map((run) => (
|
|
85
|
+
<Text key={run.id} wrap="truncate-end">
|
|
86
|
+
{run.name} · {run.state} · {durationOf(run, now)}
|
|
87
|
+
</Text>
|
|
88
|
+
))}
|
|
89
|
+
{run && (
|
|
90
|
+
<Box flexDirection="column" marginTop={1}>
|
|
91
|
+
<Text bold>{run.name} output</Text>
|
|
92
|
+
{run.tail.length === 0 && <Text dimColor>No captured output.</Text>}
|
|
93
|
+
{run.tail.map((line, index) => (
|
|
94
|
+
<Text key={String(index)} wrap="truncate-end">
|
|
95
|
+
{line}
|
|
96
|
+
</Text>
|
|
97
|
+
))}
|
|
98
|
+
</Box>
|
|
99
|
+
)}
|
|
100
|
+
</Box>
|
|
101
|
+
);
|
|
102
|
+
});
|
|
103
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export type CodexRun = {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
cwd: string;
|
|
5
|
+
owner: string;
|
|
6
|
+
startedAt: number;
|
|
7
|
+
endedAt: number | null;
|
|
8
|
+
state: 'running' | 'waiting for input' | 'ended';
|
|
9
|
+
tail: string[];
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
declare module 'claude-code' {
|
|
13
|
+
interface PluginState {
|
|
14
|
+
'codex-runs': {
|
|
15
|
+
runs: CodexRun[];
|
|
16
|
+
selected: string | null;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -300,7 +300,14 @@ async function tick($: EngineInterface) {
|
|
|
300
300
|
const stat = await $.fs.stat(root, { resolve: true }).catch(() => undefined);
|
|
301
301
|
const projectRoot = stat?.realPath ?? root;
|
|
302
302
|
const known = new Set(next.map((p) => p.path));
|
|
303
|
-
for (const run of await registryRuns(
|
|
303
|
+
for (const run of await registryRuns(
|
|
304
|
+
{
|
|
305
|
+
list: (path) => $.fs.list(path),
|
|
306
|
+
read: (path) => $.fs.read(path),
|
|
307
|
+
stat: (path) => $.fs.stat(path),
|
|
308
|
+
},
|
|
309
|
+
{ nowMs, projectRoot },
|
|
310
|
+
)) {
|
|
304
311
|
if (known.has(run.entry.log)) continue;
|
|
305
312
|
next.push(await progressOfRegistryRun($, run, last.get(run.entry.log), nowMs));
|
|
306
313
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
const STALE_MS = 2 * 60 * 60 * 1000;
|
|
2
|
-
const QUEUE_HEADING =
|
|
2
|
+
const QUEUE_HEADING = /^#{1,6} Warteschlange(, Rest)?\s*$/;
|
|
3
3
|
const HEADING = /^#{1,6} /;
|
|
4
4
|
const QUEUE_ITEM = /^\d+\. \*\*(?:.+ \()?[A-Z]\d+b?\)?\*\*/;
|
|
5
|
+
const QUEUE_ROW = /^\| [A-Z]\d+b? \|/;
|
|
5
6
|
|
|
6
7
|
export type StatusFields = {
|
|
7
8
|
task?: string;
|
|
@@ -33,7 +34,7 @@ export const queueCount = (text: string) => {
|
|
|
33
34
|
let isInQueue = false;
|
|
34
35
|
for (const line of text.split('\n')) {
|
|
35
36
|
if (HEADING.test(line)) isInQueue = QUEUE_HEADING.test(line);
|
|
36
|
-
else if (isInQueue && QUEUE_ITEM.test(line)) count++;
|
|
37
|
+
else if (isInQueue && (QUEUE_ITEM.test(line) || QUEUE_ROW.test(line))) count++;
|
|
37
38
|
}
|
|
38
39
|
return count;
|
|
39
40
|
};
|