@ethlete/agent-rules 0.1.0-next.51 → 0.1.0-next.53

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.
Files changed (61) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +16 -53
  3. package/content/hooks/away-mode.py +90 -7
  4. package/content/hooks/{background-design-commands.py → background-commands.py} +14 -65
  5. package/content/hooks/builder-idle-check.py +146 -15
  6. package/content/mods/plugins/codex-runs/.claude-plugin/plugin.json +1 -1
  7. package/content/mods/plugins/codex-runs/hooks/agent-runs.ts +310 -0
  8. package/content/mods/plugins/codex-runs/hooks/register.tsx +171 -12
  9. package/content/mods/plugins/codex-runs/types/index.d.ts +18 -0
  10. package/content/mods/plugins/e2e-progress/.claude-plugin/plugin.json +1 -1
  11. package/content/mods/plugins/status-line/.claude-plugin/plugin.json +1 -1
  12. package/content/mods/plugins/usage-line/.claude-plugin/plugin.json +1 -1
  13. package/content/mods/plugins/usage-line/hooks/rate-limits.ts +23 -0
  14. package/content/mods/plugins/usage-line/hooks/register.tsx +16 -0
  15. package/content/skills/agent-sessions/SKILL.md +1 -1
  16. package/content/skills/codex-subagent/SKILL.md +8 -2
  17. package/content/skills/codex-subagent/codex-agent.mjs +33 -2
  18. package/content/skills/design-exploration/SKILL.md +22 -104
  19. package/content/skills/design-exploration/reference-shots.md +1 -11
  20. package/content/skills/handoff/SKILL.md +2 -0
  21. package/content/skills/handoff/save.md +2 -0
  22. package/migrations/studio-claude-plugin.md +27 -0
  23. package/migrations.json +8 -0
  24. package/package.json +1 -1
  25. package/src/index.js +0 -6
  26. package/src/index.js.map +1 -1
  27. package/src/lib/config.d.ts +4 -7
  28. package/src/lib/config.js +12 -9
  29. package/src/lib/config.js.map +1 -1
  30. package/src/lib/filter.d.ts +1 -0
  31. package/src/lib/filter.js +3 -1
  32. package/src/lib/filter.js.map +1 -1
  33. package/src/lib/plan.js +6 -3
  34. package/src/lib/plan.js.map +1 -1
  35. package/src/lib/report-command.js +8 -2
  36. package/src/lib/report-command.js.map +1 -1
  37. package/src/lib/targets/hooks-shared.d.ts +5 -0
  38. package/src/lib/targets/hooks-shared.js +12 -10
  39. package/src/lib/targets/hooks-shared.js.map +1 -1
  40. package/src/lib/targets/mcp.d.ts +10 -1
  41. package/src/lib/targets/mcp.js +43 -1
  42. package/src/lib/targets/mcp.js.map +1 -1
  43. package/src/lib/timetrack.d.ts +0 -591
  44. package/src/lib/timetrack.js +3 -139
  45. package/src/lib/timetrack.js.map +1 -1
  46. package/content/hooks/design-live-check.py +0 -136
  47. package/content/skills/design-exploration/reference-check-and-notes.md +0 -101
  48. package/content/skills/design-exploration/reference-flows.md +0 -38
  49. package/content/skills/design-exploration/reference-inbox-and-mcp.md +0 -54
  50. package/content/skills/design-exploration/reference-order-and-design-system.md +0 -120
  51. package/content/skills/design-exploration/reference-products-and-sketches.md +0 -250
  52. package/content/skills/timetrack/SKILL.md +0 -324
  53. package/src/lib/peer-path.d.ts +0 -12
  54. package/src/lib/peer-path.js +0 -39
  55. package/src/lib/peer-path.js.map +0 -1
  56. package/src/lib/timetrack-command.d.ts +0 -11
  57. package/src/lib/timetrack-command.js +0 -1262
  58. package/src/lib/timetrack-command.js.map +0 -1
  59. package/src/lib/timetrack-snapshot.d.ts +0 -66
  60. package/src/lib/timetrack-snapshot.js +0 -146
  61. package/src/lib/timetrack-snapshot.js.map +0 -1
@@ -9,7 +9,9 @@ rows without a wait reason, the stop is blocked and the reason names those rows,
9
9
  the turn goes on. The slot limit is `builderSlots` in the local config (default 4).
10
10
 
11
11
  Agents started before a `/clear` are read from the meta files in the session's `subagents/`
12
- directory (an unfinished meta whose launch is not in the transcript counts as running).
12
+ directory (an unfinished meta whose launch is not in the transcript counts as running; a finished one too while
13
+ its last notification says it is waiting on its own background work - a /clear starts a new
14
+ transcript file, so that notification is also looked up in the project's transcripts of the last day).
13
15
 
14
16
  Running work comes from the transcript: every background Bash, Monitor and
15
17
  async Agent start, minus every task-notification and every TaskStop for it. A
@@ -21,8 +23,11 @@ patterns, "wartet auf" or "Offen nur:" by default (case-insensitive). Table rows
21
23
  else are skipped. A session counts as a builder when it ran the `builder-agent` skill or
22
24
  `/handoff resume <role>-...` for a role in `roles` (default builder and coordinator).
23
25
 
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
+ A tmux agent session with a live Codex pane in this checkout counts as one slot, including
27
+ while Codex waits at its prompt. A builder starts these sessions outside the transcript.
28
+ While the newest Codex rate-limit sample (as `codex-limit` reads it from `$CODEX_HOME/sessions`) shows
29
+ 20% or less of the 5h window left, or an exhausted week, the builder builds one slice at a time: the
30
+ slot limit is 1. A row counts as taken when a running task's description or command names its ID.
26
31
 
27
32
  Fires at most once per idle stop chain: a stop that a Stop hook already
28
33
  continued (`stop_hook_active`) passes.
@@ -37,8 +42,10 @@ root, "../" allowed; format "table" for a QUEUE.md table or "checkbox" for `- [
37
42
  Fail-safe: any error exits 0 with no output.
38
43
  """
39
44
 
45
+ import glob
40
46
  import json
41
47
  import os
48
+ import time
42
49
  import re
43
50
  import subprocess
44
51
  import sys
@@ -49,6 +56,9 @@ LOCAL_CONFIG_FILE = "ethlete-agents.config.local.json"
49
56
  DEFAULT_QUEUES = [{"path": os.path.join("plans", "QUEUE.md"), "format": "table"}]
50
57
  QUEUE_OWNER = "Builder"
51
58
  DEFAULT_SLOTS = 4
59
+ CODEX_LOW_LEFT_PERCENT = 20
60
+ CODEX_SCAN_FILES = 12
61
+ EARLIER_TRANSCRIPT_WINDOW = 24 * 3600
52
62
  DEFAULT_WAIT_PATTERNS = ("wartet auf", "Offen nur:")
53
63
  DEFAULT_ROLES = ("builder", "coordinator")
54
64
  CHECKBOX_ROW = re.compile(r"^\s*[-*]\s+\[ \]\s+(.*)$")
@@ -110,6 +120,42 @@ def slot_limit(config):
110
120
  return DEFAULT_SLOTS
111
121
 
112
122
 
123
+ def codex_sample():
124
+ sessions = os.path.join(os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"), "sessions")
125
+ files = sorted(glob.glob(os.path.join(sessions, "**", "*.jsonl"), recursive=True), key=os.path.getmtime, reverse=True)
126
+ latest = None
127
+ for path in files[:CODEX_SCAN_FILES]:
128
+ with open(path, encoding="utf-8") as f:
129
+ for raw in f:
130
+ if '"rate_limits"' not in raw:
131
+ continue
132
+ try:
133
+ event = json.loads(raw)
134
+ except ValueError:
135
+ continue
136
+ limits = (event.get("payload") or {}).get("rate_limits") or {}
137
+ at = parse_time(event.get("timestamp"))
138
+ if limits.get("limit_id") == "codex" and limits.get("primary") and at and (not latest or at >= latest[0]):
139
+ latest = (at, limits)
140
+ return latest[1] if latest else None
141
+
142
+
143
+ def used_percent(window, now):
144
+ if not isinstance(window, dict) or window.get("resets_at", 0) <= now:
145
+ return 0
146
+ return window.get("used_percent", 0)
147
+
148
+
149
+ def codex_low(now):
150
+ limits = codex_sample()
151
+ if not limits:
152
+ return False
153
+ return (
154
+ 100 - used_percent(limits["primary"], now) <= CODEX_LOW_LEFT_PERCENT
155
+ or used_percent(limits.get("secondary"), now) >= 100
156
+ )
157
+
158
+
113
159
  def builder_idle_config(config):
114
160
  value = config.get("builderIdle")
115
161
  return value if isinstance(value, dict) else {}
@@ -160,14 +206,18 @@ def texts_of(content):
160
206
 
161
207
 
162
208
  def read_transcript(path, launch):
163
- state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "now": None}
209
+ state = {"launch": launch, "builder": False, "tool_uses": {}, "tasks": {}, "done": set(), "waiting": set(), "now": None}
164
210
  with open(path, encoding="utf-8") as f:
165
211
  for raw in f:
166
212
  if not any(hint in raw for hint in LINE_HINTS):
167
213
  continue
168
214
  for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
169
- if not WAITING_SUMMARY.search(chunk):
170
- state["done"].update(NOTIFICATION_IDS.findall(chunk))
215
+ ids = set(NOTIFICATION_IDS.findall(chunk))
216
+ if WAITING_SUMMARY.search(chunk):
217
+ state["waiting"] |= ids
218
+ else:
219
+ state["done"] |= ids
220
+ state["waiting"] -= ids
171
221
  try:
172
222
  line = json.loads(raw)
173
223
  except ValueError:
@@ -210,6 +260,7 @@ def read_user_line(state, line, content):
210
260
  "kind": "command",
211
261
  "tool_use_id": item.get("tool_use_id"),
212
262
  "label": tool_input.get("description") or tool_input.get("command", "")[:80],
263
+ "command": tool_input.get("command", ""),
213
264
  "watcher": is_watcher(tool_input.get("command", "")),
214
265
  "ends": started + timeout / 1000 if started and isinstance(timeout, (int, float)) else None,
215
266
  }
@@ -241,6 +292,44 @@ def read_assistant_line(state, content):
241
292
  state["done"].update(str(tool_input.get(key)) for key in ("task_id", "shell_id") if tool_input.get(key))
242
293
 
243
294
 
295
+ def waiting_in_earlier_transcripts(transcript_path, agent_ids):
296
+ """A /clear starts a new transcript file but keeps the subagents dir, so an agent's last notice can sit in an older one."""
297
+ directory = os.path.dirname(transcript_path)
298
+ try:
299
+ current_mtime = os.path.getmtime(transcript_path)
300
+ candidates = [
301
+ os.path.join(directory, name)
302
+ for name in os.listdir(directory)
303
+ if name.endswith(".jsonl") and os.path.join(directory, name) != transcript_path
304
+ ]
305
+ except OSError:
306
+ return set()
307
+ earlier = []
308
+ for path in candidates:
309
+ try:
310
+ mtime = os.path.getmtime(path)
311
+ except OSError:
312
+ continue
313
+ if current_mtime - EARLIER_TRANSCRIPT_WINDOW <= mtime <= current_mtime:
314
+ earlier.append((mtime, path))
315
+ waiting = set()
316
+ for _, path in sorted(earlier):
317
+ try:
318
+ with open(path, encoding="utf-8") as f:
319
+ for raw in f:
320
+ if "task-notification" not in raw or not any(agent_id in raw for agent_id in agent_ids):
321
+ continue
322
+ for chunk in NOTIFICATION.findall(raw.replace("\\n", "\n")):
323
+ ids = set(NOTIFICATION_IDS.findall(chunk)) & agent_ids
324
+ if WAITING_SUMMARY.search(chunk):
325
+ waiting |= ids
326
+ else:
327
+ waiting -= ids
328
+ except OSError:
329
+ continue
330
+ return waiting
331
+
332
+
244
333
  def read_earlier_agents(state, transcript_path):
245
334
  """Agents started before a /clear: their meta files sit in this session's subagents dir."""
246
335
  directory = os.path.join(os.path.splitext(transcript_path)[0], "subagents")
@@ -248,6 +337,22 @@ def read_earlier_agents(state, transcript_path):
248
337
  names = sorted(os.listdir(directory))
249
338
  except OSError:
250
339
  return
340
+ finished = set()
341
+ for name in names:
342
+ if not (name.startswith("agent-") and name.endswith(".meta.json")):
343
+ continue
344
+ agent_id = name[len("agent-") : -len(".meta.json")]
345
+ if agent_id in state["done"] or agent_id in state["waiting"]:
346
+ continue
347
+ try:
348
+ with open(os.path.join(directory, name), encoding="utf-8") as f:
349
+ meta = json.load(f)
350
+ except (OSError, ValueError):
351
+ continue
352
+ if isinstance(meta, dict) and meta.get("finished"):
353
+ finished.add(agent_id)
354
+ if finished:
355
+ state["waiting"] |= waiting_in_earlier_transcripts(transcript_path, finished)
251
356
  for name in names:
252
357
  if not (name.startswith("agent-") and name.endswith(".meta.json")):
253
358
  continue
@@ -258,7 +363,7 @@ def read_earlier_agents(state, transcript_path):
258
363
  except (OSError, ValueError):
259
364
  continue
260
365
  tool_use_id = meta.get("toolUseId") if isinstance(meta, dict) else None
261
- if not tool_use_id or meta.get("finished") or tool_use_id in state["tool_uses"] or agent_id in state["tasks"]:
366
+ if not tool_use_id or (meta.get("finished") and agent_id not in state["waiting"]) or tool_use_id in state["tool_uses"] or agent_id in state["tasks"]:
262
367
  continue
263
368
  state["tasks"][agent_id] = {
264
369
  "kind": "agent",
@@ -282,13 +387,31 @@ def running_tasks(state):
282
387
 
283
388
  def codex_runs(root):
284
389
  try:
285
- names = subprocess.run(
286
- ["tmux", "list-sessions", "-F", "#{session_name}"], capture_output=True, text=True, timeout=5
287
- ).stdout.split()
390
+ panes = subprocess.run(
391
+ [
392
+ "tmux", "list-panes", "-a", "-f", "#{==:#{pane_dead},0}",
393
+ "-F", "#{session_name}|#{pane_current_command}|#{pane_current_path}",
394
+ ],
395
+ capture_output=True, text=True, timeout=5, check=True,
396
+ ).stdout.splitlines()
288
397
  except (OSError, subprocess.SubprocessError):
289
398
  return []
290
399
  suffix = "@" + os.path.basename(os.path.normpath(root))
291
- return [name for name in names if name.startswith("codex-") and name.endswith(suffix)]
400
+ checkout = os.path.realpath(root)
401
+ sessions = {}
402
+ for pane in panes:
403
+ fields = pane.split("|", 2)
404
+ if len(fields) != 3:
405
+ continue
406
+ name, command, cwd = fields
407
+ if command != "codex" or not cwd or not name.endswith(suffix):
408
+ continue
409
+ agent = name.removesuffix(suffix)
410
+ if not agent or agent in ("claude", "mailbox-dispatch") or agent.startswith("claude-"):
411
+ continue
412
+ if os.path.commonpath((checkout, os.path.realpath(cwd))) == checkout:
413
+ sessions[name] = None
414
+ return list(sessions)
292
415
 
293
416
 
294
417
  def waits(text, patterns):
@@ -338,12 +461,19 @@ def open_builder_rows(root, sources, patterns):
338
461
  return rows
339
462
 
340
463
 
341
- def not_taken(rows, labels):
464
+ def names_row(row, text, flags=0):
465
+ return re.search(rf"(?<![A-Za-z0-9]){re.escape(row.split(' ')[0])}(?![A-Za-z0-9])", text, flags)
466
+
467
+
468
+ def not_taken(rows, labels, commands):
342
469
  return [
343
470
  row
344
471
  for row in rows
345
472
  if row.startswith("(")
346
- or not any(re.search(rf"(?<![A-Za-z0-9]){re.escape(row.split(' ')[0])}(?![A-Za-z0-9])", label) for label in labels)
473
+ or not (
474
+ any(names_row(row, label) for label in labels)
475
+ or any(names_row(row, command, re.I) for command in commands)
476
+ )
347
477
  ]
348
478
 
349
479
 
@@ -379,13 +509,14 @@ def main():
379
509
  running = running_tasks(state)
380
510
  codex = codex_runs(root)
381
511
  working = sum(1 for task in running if not task["watcher"]) + len(codex)
382
- slots = slot_limit(config)
512
+ slots = 1 if codex_low(time.time()) else slot_limit(config)
383
513
  if working >= slots:
384
514
  return
385
515
  sources = queue_sources(settings)
386
516
  patterns = string_list(settings.get("waitPatterns"), DEFAULT_WAIT_PATTERNS)
387
517
  watchers = [task["label"] for task in running] + codex
388
- rows = not_taken(open_builder_rows(root, sources, patterns), watchers)
518
+ commands = [task.get("command", "") for task in running]
519
+ rows = not_taken(open_builder_rows(root, sources, patterns), watchers, commands)
389
520
  if not rows:
390
521
  return
391
522
  print(json.dumps({"decision": "block", "reason": reason_for(rows, watchers, working, slots, sources, patterns)}))
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-runs",
3
- "version": "0.1.0-next.51",
3
+ "version": "0.1.0-next.53",
4
4
  "description": "Codex sessions in tmux with their state, duration, and recent output",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -0,0 +1,310 @@
1
+ export type TraceLine = { kind: 'command' | 'files' | 'message' | 'error'; text: string };
2
+
3
+ export type Trace = {
4
+ thread: string;
5
+ commands: number;
6
+ lastCommand: string;
7
+ files: string[];
8
+ lastMessage: string;
9
+ lines: TraceLine[];
10
+ errors: string[];
11
+ outputTokens: number | null;
12
+ isCompleted: boolean;
13
+ isFailed: boolean;
14
+ };
15
+
16
+ export type TraceReader = { trace: Trace; rest: string };
17
+
18
+ export type RunIndex = {
19
+ pid: number;
20
+ session: string;
21
+ cwd: string;
22
+ model: string;
23
+ effort: string;
24
+ sandbox: string;
25
+ prompt: string;
26
+ startedAt: number;
27
+ log: string;
28
+ endedAt?: number;
29
+ exitCode?: number | null;
30
+ failed?: boolean;
31
+ error?: string;
32
+ };
33
+
34
+ export type AgentRunState = 'running' | 'done' | 'failed';
35
+
36
+ export type AgentRun = {
37
+ id: string;
38
+ log: string;
39
+ session: string;
40
+ cwd: string;
41
+ label: string;
42
+ prompt: string;
43
+ startedAt: number;
44
+ endedAt: number | null;
45
+ state: AgentRunState;
46
+ error: string;
47
+ progress: string;
48
+ trace: TraceLine[];
49
+ };
50
+
51
+ const KEEP_LINES = 40;
52
+ const SHELL_WRAPPER = /^\S*\/(?:ba|z)?sh -l?c (["'])([\s\S]*)\1$/;
53
+
54
+ const clip = (text: string, max: number) => {
55
+ const line = text.replace(/\s+/g, ' ').trim();
56
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
57
+ };
58
+
59
+ export const commandOf = (command: string) => {
60
+ const inner = SHELL_WRAPPER.exec(command.trim())?.[2] ?? command;
61
+ return clip(inner.replace(/\\"/g, '"'), 160);
62
+ };
63
+
64
+ export const emptyTrace = (): Trace => ({
65
+ thread: '',
66
+ commands: 0,
67
+ lastCommand: '',
68
+ files: [],
69
+ lastMessage: '',
70
+ lines: [],
71
+ errors: [],
72
+ outputTokens: null,
73
+ isCompleted: false,
74
+ isFailed: false,
75
+ });
76
+
77
+ type Item = { type?: string; command?: string; text?: string; message?: string; changes?: unknown };
78
+ type TraceEvent = {
79
+ type?: string;
80
+ thread_id?: string;
81
+ item?: Item;
82
+ usage?: { output_tokens?: number };
83
+ error?: { message?: string };
84
+ message?: string;
85
+ };
86
+
87
+ function addLine(trace: Trace, line: TraceLine): Trace {
88
+ return { ...trace, lines: [...trace.lines, line].slice(-KEEP_LINES) };
89
+ }
90
+
91
+ function applyItem(trace: Trace, item: Item, isStarted: boolean): Trace {
92
+ if (item.type === 'command_execution') {
93
+ const command = commandOf(String(item.command ?? ''));
94
+ if (isStarted) return { ...trace, lastCommand: command };
95
+ return addLine(
96
+ { ...trace, commands: trace.commands + 1, lastCommand: command },
97
+ { kind: 'command', text: command },
98
+ );
99
+ }
100
+ if (isStarted) return trace;
101
+ if (item.type === 'agent_message' && item.text) {
102
+ return addLine({ ...trace, lastMessage: clip(item.text, 400) }, { kind: 'message', text: clip(item.text, 400) });
103
+ }
104
+ if (item.type === 'file_change' && Array.isArray(item.changes)) {
105
+ const paths = item.changes.map((change: { path?: string }) => String(change?.path ?? '')).filter(Boolean);
106
+ const files = [...trace.files.filter((file) => !paths.includes(file)), ...paths];
107
+ return addLine({ ...trace, files }, { kind: 'files', text: paths.join(', ') });
108
+ }
109
+ if (item.type === 'error') {
110
+ const message = clip(item.message ?? 'unknown error', 300);
111
+ return addLine({ ...trace, errors: [...trace.errors, message] }, { kind: 'error', text: message });
112
+ }
113
+ return trace;
114
+ }
115
+
116
+ function applyEvent(trace: Trace, event: TraceEvent): Trace {
117
+ switch (event.type) {
118
+ case 'thread.started':
119
+ return { ...trace, thread: event.thread_id ?? '' };
120
+ case 'item.started':
121
+ return event.item ? applyItem(trace, event.item, true) : trace;
122
+ case 'item.completed':
123
+ return event.item ? applyItem(trace, event.item, false) : trace;
124
+ case 'turn.completed':
125
+ return { ...trace, isCompleted: true, outputTokens: event.usage?.output_tokens ?? null };
126
+ case 'turn.failed': {
127
+ const message = clip(event.error?.message ?? 'the turn failed', 300);
128
+ return addLine(
129
+ { ...trace, isFailed: true, errors: [...trace.errors, message] },
130
+ { kind: 'error', text: message },
131
+ );
132
+ }
133
+ case 'error':
134
+ return addLine(trace, { kind: 'error', text: clip(event.message ?? 'unknown error', 300) });
135
+ default:
136
+ return trace;
137
+ }
138
+ }
139
+
140
+ export function feedTrace(reader: TraceReader, chunk: string): TraceReader {
141
+ const lines = `${reader.rest}${chunk}`.split('\n');
142
+ const rest = lines.pop() ?? '';
143
+ let trace = reader.trace;
144
+ for (const line of lines) {
145
+ if (!line.trim()) continue;
146
+ try {
147
+ trace = applyEvent(trace, JSON.parse(line) as TraceEvent);
148
+ } catch {
149
+ continue;
150
+ }
151
+ }
152
+ return { trace, rest };
153
+ }
154
+
155
+ export const parseTrace = (text: string) => feedTrace({ trace: emptyTrace(), rest: '' }, `${text}\n`).trace;
156
+
157
+ export function parseRunIndex(text: string): RunIndex | null {
158
+ try {
159
+ const value = JSON.parse(text) as Partial<RunIndex>;
160
+ if (typeof value.startedAt !== 'number' || typeof value.log !== 'string') return null;
161
+ return {
162
+ pid: Number(value.pid) || 0,
163
+ session: String(value.session ?? ''),
164
+ cwd: String(value.cwd ?? ''),
165
+ model: String(value.model ?? ''),
166
+ effort: String(value.effort ?? ''),
167
+ sandbox: String(value.sandbox ?? ''),
168
+ prompt: String(value.prompt ?? ''),
169
+ startedAt: value.startedAt,
170
+ log: value.log,
171
+ endedAt: typeof value.endedAt === 'number' ? value.endedAt : undefined,
172
+ exitCode: value.exitCode ?? null,
173
+ failed: value.failed === true,
174
+ error: String(value.error ?? ''),
175
+ };
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ export function stampTime(stamp: string) {
182
+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/.exec(stamp);
183
+ return match ? Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`) : NaN;
184
+ }
185
+
186
+ export function progressOf(trace: Trace) {
187
+ const parts = [`${trace.commands} cmd`];
188
+ if (trace.files.length > 0) parts.push(`${trace.files.length} files changed`);
189
+ const latest = trace.lines[trace.lines.length - 1];
190
+ if (latest?.kind === 'message') parts.push(`“${clip(latest.text, 100)}”`);
191
+ else if (trace.lastCommand) parts.push(`$ ${clip(trace.lastCommand, 100)}`);
192
+ return parts.join(' · ');
193
+ }
194
+
195
+ /** `isAlive` is `null` when the wrapper's liveness is unknown. */
196
+ export function agentRunOf({
197
+ id,
198
+ log,
199
+ index,
200
+ trace,
201
+ logChangedAt,
202
+ isAlive,
203
+ now,
204
+ }: {
205
+ id: string;
206
+ log: string;
207
+ index: RunIndex | null;
208
+ trace: Trace;
209
+ logChangedAt: number;
210
+ isAlive: boolean | null;
211
+ now: number;
212
+ }): AgentRun {
213
+ const ended = index?.endedAt ?? null;
214
+ const lost = ended === null && (index ? isAlive === false : now - logChangedAt > 10 * 60_000);
215
+ const state: AgentRunState =
216
+ ended !== null
217
+ ? index?.failed || trace.isFailed
218
+ ? 'failed'
219
+ : 'done'
220
+ : trace.isFailed || lost
221
+ ? 'failed'
222
+ : !index && trace.isCompleted
223
+ ? 'done'
224
+ : 'running';
225
+ const error =
226
+ state !== 'failed'
227
+ ? ''
228
+ : index?.error ||
229
+ trace.errors[trace.errors.length - 1] ||
230
+ (lost ? 'the wrapper stopped without an end mark' : 'failed');
231
+ const label = index
232
+ ? [index.model, index.effort, index.sandbox === 'workspace-write' ? 'write' : ''].filter(Boolean).join(' ')
233
+ : 'codex';
234
+ return {
235
+ id,
236
+ log,
237
+ session: index?.session ?? '',
238
+ cwd: index?.cwd ?? '',
239
+ label,
240
+ prompt: index?.prompt ?? '',
241
+ startedAt: index?.startedAt ?? stampTime(id),
242
+ endedAt: ended ?? (state === 'running' ? null : logChangedAt),
243
+ state,
244
+ error,
245
+ progress: progressOf(trace),
246
+ trace: trace.lines,
247
+ };
248
+ }
249
+
250
+ export function shortIdOf(id: string) {
251
+ const at = stampTime(id);
252
+ if (Number.isNaN(at)) return id.slice(11, 19).replace(/-/g, ':');
253
+ const date = new Date(at);
254
+ return [date.getHours(), date.getMinutes(), date.getSeconds()].map((part) => String(part).padStart(2, '0')).join(':');
255
+ }
256
+
257
+ export const isRunNamed = (run: { id: string }, name: string) =>
258
+ run.id === name || shortIdOf(run.id) === name.replace(/-/g, ':');
259
+
260
+ export function durationOf(run: { startedAt: number; endedAt: number | null }, now: number) {
261
+ const seconds = Math.max(0, Math.floor(((run.endedAt ?? now) - run.startedAt) / 1000));
262
+ const minutes = Math.floor(seconds / 60);
263
+ return minutes ? `${minutes}m${String(seconds % 60).padStart(2, '0')}s` : `${seconds}s`;
264
+ }
265
+
266
+ export function statusOf(runs: AgentRun[], now: number) {
267
+ const running = runs.filter((run) => run.state === 'running');
268
+ if (running.length === 0) return undefined;
269
+ const oldest = Math.min(...running.map((run) => run.startedAt));
270
+ return `Codex: ${running.length} running, ${Math.max(0, Math.floor((now - oldest) / 60_000))}m`;
271
+ }
272
+
273
+ export function finishNotices(previous: AgentRun[], next: AgentRun[], session: string, now: number) {
274
+ const wasRunning = new Set(previous.filter((run) => run.state === 'running').map((run) => run.id));
275
+ return next
276
+ .filter((run) => run.state !== 'running' && wasRunning.has(run.id) && run.session === session)
277
+ .map((run) =>
278
+ run.state === 'failed'
279
+ ? `Codex run failed after ${durationOf(run, now)}: ${clip(run.error, 120)}`
280
+ : `Codex run done in ${durationOf(run, now)}: ${clip(run.prompt || run.progress, 80)}`,
281
+ );
282
+ }
283
+
284
+ export const isCodexAgentCommand = (command: unknown) =>
285
+ typeof command === 'string' && /codex-agent\.mjs\b/.test(command) && !/(?:^|\s)(?:-h|--help)\b/.test(command);
286
+
287
+ export function claimRuns(
288
+ waiting: { toolUseId: string; at: number }[],
289
+ claimed: Record<string, string>,
290
+ runs: AgentRun[],
291
+ session: string,
292
+ ) {
293
+ const taken = new Set(Object.values(claimed));
294
+ const next = { ...claimed };
295
+ const free = runs
296
+ .filter((run) => run.session === session && !taken.has(run.id))
297
+ .sort((a, b) => a.startedAt - b.startedAt);
298
+ const still: typeof waiting = [];
299
+ for (const call of [...waiting].sort((a, b) => a.at - b.at)) {
300
+ const index = free.findIndex((run) => run.startedAt >= call.at - 5_000 && run.startedAt <= call.at + 120_000);
301
+ const run = free[index];
302
+ if (!run) {
303
+ still.push(call);
304
+ continue;
305
+ }
306
+ next[call.toolUseId] = run.id;
307
+ free.splice(index, 1);
308
+ }
309
+ return { claimed: next, waiting: still };
310
+ }