agent-command-tab 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.
Files changed (57) hide show
  1. agent_command_tab/__init__.py +4 -0
  2. agent_command_tab/agent_adapters/__init__.py +48 -0
  3. agent_command_tab/agent_adapters/base.py +162 -0
  4. agent_command_tab/agent_adapters/claude_code.py +120 -0
  5. agent_command_tab/agent_adapters/codex.py +102 -0
  6. agent_command_tab/agent_adapters/generic.py +22 -0
  7. agent_command_tab/agent_process_tree.py +557 -0
  8. agent_command_tab/agent_session_pausing.py +254 -0
  9. agent_command_tab/app_controller.py +947 -0
  10. agent_command_tab/claude_code_transcript_records.py +75 -0
  11. agent_command_tab/command_line.py +187 -0
  12. agent_command_tab/context_window_usage.py +230 -0
  13. agent_command_tab/dashboard_core_api.py +57 -0
  14. agent_command_tab/docked_window_frames_store.py +60 -0
  15. agent_command_tab/global_shortcut_key_filter.py +167 -0
  16. agent_command_tab/hook_event_forwarder.py +116 -0
  17. agent_command_tab/hook_event_tracking.py +129 -0
  18. agent_command_tab/hook_states_store.py +60 -0
  19. agent_command_tab/hooks_installer.py +300 -0
  20. agent_command_tab/installed_copy_paths.py +41 -0
  21. agent_command_tab/iterm2_actions.py +325 -0
  22. agent_command_tab/iterm2_connection_thread.py +2299 -0
  23. agent_command_tab/iterm2_snapshot_builder.py +403 -0
  24. agent_command_tab/list_sorting.py +117 -0
  25. agent_command_tab/messages_between_agent_sessions.py +78 -0
  26. agent_command_tab/monitor_assignment.py +109 -0
  27. agent_command_tab/pause_records_store.py +61 -0
  28. agent_command_tab/screen_readings.py +108 -0
  29. agent_command_tab/session_preview_computation.py +228 -0
  30. agent_command_tab/session_status_computation.py +235 -0
  31. agent_command_tab/settings_store.py +292 -0
  32. agent_command_tab/snapshot_data_classes.py +145 -0
  33. agent_command_tab/start_with_iterm2.py +138 -0
  34. agent_command_tab/tab_order_computation.py +26 -0
  35. agent_command_tab/user_interface/__init__.py +1 -0
  36. agent_command_tab/user_interface/agent_session_outline_view.py +2120 -0
  37. agent_command_tab/user_interface/agent_tool_icons.py +124 -0
  38. agent_command_tab/user_interface/app_icon.py +75 -0
  39. agent_command_tab/user_interface/control_helpers.py +38 -0
  40. agent_command_tab/user_interface/list_window.py +116 -0
  41. agent_command_tab/user_interface/menu_bar_status_item.py +193 -0
  42. agent_command_tab/user_interface/named_colors.py +58 -0
  43. agent_command_tab/user_interface/pointing_hand_button.py +42 -0
  44. agent_command_tab/user_interface/popover_container.py +461 -0
  45. agent_command_tab/user_interface/row_text_rendering.py +342 -0
  46. agent_command_tab/user_interface/screen_layout.py +91 -0
  47. agent_command_tab/user_interface/settings_window.py +530 -0
  48. agent_command_tab/user_interface/sidebar_panel.py +486 -0
  49. agent_command_tab/user_interface/sidebar_placement.py +105 -0
  50. agent_command_tab/user_interface/talk_to_each_other_alert.py +130 -0
  51. agent_command_tab/window_list_ordering.py +44 -0
  52. agent_command_tab-0.1.0.dist-info/METADATA +85 -0
  53. agent_command_tab-0.1.0.dist-info/RECORD +57 -0
  54. agent_command_tab-0.1.0.dist-info/WHEEL +5 -0
  55. agent_command_tab-0.1.0.dist-info/entry_points.txt +2 -0
  56. agent_command_tab-0.1.0.dist-info/licenses/LICENSE +21 -0
  57. agent_command_tab-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,557 @@
1
+ """Facts about an agent's processes, read from macOS's libproc and sysctl without starting a subprocess.
2
+
3
+ - The agent's current folder (iTerm2's `path` variable can be empty or stale).
4
+ - Whether a process still exists, and whether it is stopped (a paused agent session).
5
+ - The agent's descendant processes, to tell an agent that is waiting on a command it started
6
+ (a pipeline, a test run) from one that is thinking (and turns "stuck" when that lasts), and the
7
+ name that command was started as.
8
+ - The memory and CPU time the agent and all its descendants use (the Memory and CPU columns,
9
+ user request, 2026-10-19).
10
+ """
11
+
12
+ import collections
13
+ import ctypes
14
+ import os
15
+ import re
16
+
17
+ LIBPROC = ctypes.CDLL("/usr/lib/libproc.dylib")
18
+ LIBC = ctypes.CDLL("/usr/lib/libc.dylib")
19
+ CTL_KERN = 1
20
+ KERN_PROCARGS2 = 49 # sysctl that returns a process's argument count, executable path and arguments (what ps reads)
21
+ PROC_PIDTBSDINFO = 3 # proc_pidinfo flavor that returns struct proc_bsdinfo (refused for another user's process)
22
+ PROC_PIDT_SHORTBSDINFO = 13 # proc_pidinfo flavor that returns struct proc_bsdshortinfo, also for another user's process
23
+ STOPPED_PROCESS_STATUS = 4 # SSTOP in <sys/proc.h>, proc_bsdinfo's pbi_status of a stopped process
24
+ PROC_PIDVNODEPATHINFO = 9 # proc_pidinfo flavor that returns struct proc_vnodepathinfo
25
+ VNODE_INFO_SIZE = 152 # sizeof(struct vnode_info); the current folder's path follows it
26
+ MAXIMUM_PATH_LENGTH = 1024
27
+ MAXIMUM_CHILD_PROCESSES = 1024
28
+ # Shells and wrappers that agents run commands in: the command's name is the first process
29
+ # below them (python3 rather than the zsh that Claude Code runs it in).
30
+ SHELL_AND_WRAPPER_PROCESS_NAMES = frozenset({"bash", "zsh", "sh", "dash", "fish", "env", "login", "sandbox-exec", "timeout"})
31
+ # The names agent programs are started as. One started inside a tab's agent (a `claude -p` or
32
+ # `codex exec` run by its shell tool) fires the same user-level hooks, so it sets the tab's status too.
33
+ NAMES_OF_AGENT_PROGRAMS = frozenset({"claude", "codex"})
34
+ # A command counts as started in this turn even if it started this long before the dashboard
35
+ # noticed the turn begin.
36
+ SECONDS_OF_SLACK_AT_TURN_START = 2
37
+ # A command counts only once it has run this long, so hooks (iTerm2's cc-status runs on every
38
+ # tool call) and status line commands, which end within a second, never show as "running".
39
+ SECONDS_A_COMMAND_RUNS_BEFORE_IT_COUNTS = 2
40
+ # Claude Code's shell tool runs each command as `bash -c "source <its shell snapshot> ... && eval
41
+ # '<the command>' < /dev/null && pwd -P >| <a file>"`, a ' in the command written as '"'"', and
42
+ # without the `< /dev/null` for a command with a heredoc (code review, 2026-10-28).
43
+ CLAUDE_CODE_SHELL_TOOL_COMMAND = re.compile(r"""&& eval '((?:[^']|'"'"')*)'(?: < /dev/null)? && pwd -P >\| \S+\Z""", re.DOTALL)
44
+ # A Claude Code session's scratchpad folder, /private/tmp/claude-<user ID>/<project>/<session ID>/scratchpad,
45
+ # which a process row calls just "scratchpad" (user request, 2026-10-28), so the end of the command shows.
46
+ CLAUDE_CODE_SCRATCHPAD_PATH = re.compile(r"(?:/private)?/tmp/claude-\d+/[^/\s'\"]+/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}/scratchpad")
47
+ LAUNCHD_PROCESS_ID = 1 # adopts a process whose parent ended
48
+
49
+ RUSAGE_INFO_V2 = 2 # proc_pid_rusage flavor that returns struct rusage_info_v2
50
+
51
+ ProcessInfo = collections.namedtuple("ProcessInfo", ["process_id", "parent_process_id", "name", "started_at"])
52
+ ProcessInfo.__doc__ = "One process: its executable's name and when it started (seconds since the epoch)."
53
+
54
+
55
+ class ProcessBsdInfo(ctypes.Structure):
56
+ """struct proc_bsdinfo from <sys/proc_info.h>."""
57
+
58
+ _fields_ = [
59
+ ("pbi_flags", ctypes.c_uint32), ("pbi_status", ctypes.c_uint32), ("pbi_xstatus", ctypes.c_uint32),
60
+ ("pbi_pid", ctypes.c_uint32), ("pbi_ppid", ctypes.c_uint32), ("pbi_uid", ctypes.c_uint32),
61
+ ("pbi_gid", ctypes.c_uint32), ("pbi_ruid", ctypes.c_uint32), ("pbi_rgid", ctypes.c_uint32),
62
+ ("pbi_svuid", ctypes.c_uint32), ("pbi_svgid", ctypes.c_uint32), ("rfu_1", ctypes.c_uint32),
63
+ ("pbi_comm", ctypes.c_char * 16), ("pbi_name", ctypes.c_char * 32), ("pbi_nfiles", ctypes.c_uint32),
64
+ ("pbi_pgid", ctypes.c_uint32), ("pbi_pjobc", ctypes.c_uint32), ("e_tdev", ctypes.c_uint32),
65
+ ("e_tpgid", ctypes.c_uint32), ("pbi_nice", ctypes.c_int32), ("pbi_start_tvsec", ctypes.c_uint64),
66
+ ("pbi_start_tvusec", ctypes.c_uint64),
67
+ ]
68
+
69
+
70
+ class ProcessShortBsdInfo(ctypes.Structure):
71
+ """struct proc_bsdshortinfo from <sys/proc_info.h>."""
72
+
73
+ _fields_ = [
74
+ ("pbsi_pid", ctypes.c_uint32), ("pbsi_ppid", ctypes.c_uint32), ("pbsi_pgid", ctypes.c_uint32),
75
+ ("pbsi_status", ctypes.c_uint32), ("pbsi_comm", ctypes.c_char * 16), ("pbsi_flags", ctypes.c_uint32),
76
+ ("pbsi_uid", ctypes.c_uint32), ("pbsi_gid", ctypes.c_uint32), ("pbsi_ruid", ctypes.c_uint32),
77
+ ("pbsi_rgid", ctypes.c_uint32), ("pbsi_svuid", ctypes.c_uint32), ("pbsi_svgid", ctypes.c_uint32),
78
+ ("pbsi_rfu", ctypes.c_uint32),
79
+ ]
80
+
81
+
82
+ class ResourceUsageInfoV2(ctypes.Structure):
83
+ """struct rusage_info_v2 from <sys/resource.h>; the times are in mach absolute time units."""
84
+
85
+ _fields_ = [("ri_uuid", ctypes.c_uint8 * 16)] + [(field_name, ctypes.c_uint64) for field_name in (
86
+ "ri_user_time", "ri_system_time", "ri_pkg_idle_wkups", "ri_interrupt_wkups", "ri_pageins", "ri_wired_size",
87
+ "ri_resident_size", "ri_phys_footprint", "ri_proc_start_abstime", "ri_proc_exit_abstime", "ri_child_user_time",
88
+ "ri_child_system_time", "ri_child_pkg_idle_wkups", "ri_child_interrupt_wkups", "ri_child_pageins",
89
+ "ri_child_elapsed_abstime", "ri_diskio_bytesread", "ri_diskio_byteswritten")]
90
+
91
+
92
+ class MachTimebaseInfo(ctypes.Structure):
93
+ """struct mach_timebase_info: mach absolute time units times numer / denom are nanoseconds."""
94
+
95
+ _fields_ = [("numer", ctypes.c_uint32), ("denom", ctypes.c_uint32)]
96
+
97
+
98
+ def read_seconds_per_mach_time_unit():
99
+ """Returns how many seconds one mach absolute time unit is (1 ns on Intel, 1/24 µs on Apple silicon)."""
100
+ timebase = MachTimebaseInfo()
101
+ LIBC.mach_timebase_info(ctypes.byref(timebase))
102
+ return timebase.numer / timebase.denom / 1e9
103
+
104
+
105
+ SECONDS_PER_MACH_TIME_UNIT = read_seconds_per_mach_time_unit()
106
+
107
+
108
+ def read_process_resource_usage(process_id):
109
+ """Returns (memory in bytes, CPU time in seconds) for one process: its physical footprint,
110
+ the number Activity Monitor shows as Memory, and the user plus system time used by it and
111
+ by the children it has already waited for (so a finished command's CPU time stays counted
112
+ in its parent's); or None if it is gone or can't be read."""
113
+ usage = ResourceUsageInfoV2()
114
+ if LIBPROC.proc_pid_rusage(process_id, RUSAGE_INFO_V2, ctypes.byref(usage)) != 0:
115
+ return None
116
+ cpu_time = usage.ri_user_time + usage.ri_system_time + usage.ri_child_user_time + usage.ri_child_system_time
117
+ return usage.ri_phys_footprint, cpu_time * SECONDS_PER_MACH_TIME_UNIT
118
+
119
+
120
+ def read_process_tree_resource_usage(process_id):
121
+ """Returns (memory in bytes, CPU time in seconds) summed over a process and all its
122
+ descendants (an agent with the commands, servers and helpers it started), or None if the
123
+ process is gone. A descendant that ends while it is being read is left out; once its
124
+ parent has waited for it, its CPU time is counted in the parent's."""
125
+ own_usage = read_process_resource_usage(process_id)
126
+ if own_usage is None:
127
+ return None
128
+ # Every level: agents start launchers that start agents, which start shells and commands.
129
+ usages = [own_usage] + [read_process_resource_usage(process.process_id)
130
+ for process in list_descendant_processes(process_id, maximum_depth=None)]
131
+ usages = [usage for usage in usages if usage is not None]
132
+ return sum(memory for memory, _ in usages), sum(cpu_seconds for _, cpu_seconds in usages)
133
+
134
+
135
+ def compute_cpu_percent(previous_reading, reading):
136
+ """Returns the share of one CPU core used between two readings, in percent (200 means two
137
+ cores' worth), or None for the first reading. A descendant that left the tree in between
138
+ without its parent waiting for it takes its CPU time with it, so a drop counts as 0.
139
+
140
+ Args:
141
+ previous_reading: (CPU seconds, read at) from the last reading, or None.
142
+ reading: (CPU seconds, read at) now.
143
+ """
144
+ if previous_reading is None or reading[1] <= previous_reading[1]:
145
+ return None
146
+ return max(reading[0] - previous_reading[0], 0) / (reading[1] - previous_reading[1]) * 100
147
+
148
+
149
+ def read_process_current_folder(process_id):
150
+ """Returns a process's current folder, or "" if unknown."""
151
+ if not process_id:
152
+ return ""
153
+ buffer_size = 2 * (VNODE_INFO_SIZE + MAXIMUM_PATH_LENGTH) # current folder, then root folder
154
+ buffer = ctypes.create_string_buffer(buffer_size)
155
+ if LIBPROC.proc_pidinfo(process_id, PROC_PIDVNODEPATHINFO, ctypes.c_uint64(0), buffer, buffer_size) <= 0:
156
+ return ""
157
+ return buffer.raw[VNODE_INFO_SIZE:VNODE_INFO_SIZE + MAXIMUM_PATH_LENGTH].split(b"\0", 1)[0].decode(errors="replace")
158
+
159
+
160
+ def process_is_alive(process_id):
161
+ """Returns whether a process with this ID exists (one owned by another user counts as alive)."""
162
+ try:
163
+ os.kill(process_id, 0)
164
+ except ProcessLookupError:
165
+ return False
166
+ except PermissionError:
167
+ return True
168
+ return True
169
+
170
+
171
+ def read_process_bsd_info(process_id):
172
+ """Returns a process's ProcessBsdInfo, or None if it is gone."""
173
+ bsd_info = ProcessBsdInfo()
174
+ size = LIBPROC.proc_pidinfo(process_id, PROC_PIDTBSDINFO, ctypes.c_uint64(0), ctypes.byref(bsd_info),
175
+ ctypes.sizeof(bsd_info))
176
+ return bsd_info if size == ctypes.sizeof(bsd_info) else None
177
+
178
+
179
+ def read_process_info(process_id):
180
+ """Returns the ProcessInfo of a process, or None if it is gone or belongs to another user
181
+ (a command run with sudo; read_name_of_any_process still reads its name)."""
182
+ bsd_info = read_process_bsd_info(process_id)
183
+ if bsd_info is None:
184
+ return None
185
+ name = (bsd_info.pbi_name or bsd_info.pbi_comm).decode(errors="replace")
186
+ return ProcessInfo(process_id, bsd_info.pbi_ppid, name, bsd_info.pbi_start_tvsec + bsd_info.pbi_start_tvusec / 1e6)
187
+
188
+
189
+ def read_process_short_bsd_info(process_id):
190
+ """Returns a process's ProcessShortBsdInfo, also for a process of another user, or None if it is gone."""
191
+ short_bsd_info = ProcessShortBsdInfo()
192
+ size = LIBPROC.proc_pidinfo(process_id, PROC_PIDT_SHORTBSDINFO, ctypes.c_uint64(0), ctypes.byref(short_bsd_info),
193
+ ctypes.sizeof(short_bsd_info))
194
+ return short_bsd_info if size == ctypes.sizeof(short_bsd_info) else None
195
+
196
+
197
+ def read_name_of_any_process(process_id):
198
+ """Returns a process's executable name (at most 16 characters), also for a process of
199
+ another user, or "" if it is gone."""
200
+ short_bsd_info = read_process_short_bsd_info(process_id)
201
+ return short_bsd_info.pbsi_comm.decode(errors="replace") if short_bsd_info is not None else ""
202
+
203
+
204
+ def list_the_process_and_its_ancestor_ids(process_id):
205
+ """Returns process_id and the IDs of its parent, the parent's parent, and so on up to launchd."""
206
+ process_ids = []
207
+ while process_id > 0 and process_id not in process_ids:
208
+ process_ids.append(process_id)
209
+ short_bsd_info = read_process_short_bsd_info(process_id)
210
+ if short_bsd_info is None:
211
+ break
212
+ process_id = short_bsd_info.pbsi_ppid
213
+ return process_ids
214
+
215
+
216
+ def process_is_stopped(process_id):
217
+ """Returns whether a process exists and is stopped (by Ctrl+Z, SIGTSTP or SIGSTOP) until it gets a SIGCONT."""
218
+ bsd_info = read_process_bsd_info(process_id)
219
+ return bsd_info is not None and bsd_info.pbi_status == STOPPED_PROCESS_STATUS
220
+
221
+
222
+ def find_the_shell_running_the_agent(agent_process_id):
223
+ """Returns the ID of the shell that runs the agent as a job: the parent of the agent's job
224
+ leader (the process its group is named after), or None if the agent is gone."""
225
+ agent = read_process_bsd_info(agent_process_id)
226
+ if agent is None:
227
+ return None
228
+ job_leader = read_process_bsd_info(agent.pbi_pgid)
229
+ return job_leader.pbi_ppid if job_leader is not None else agent.pbi_ppid
230
+
231
+
232
+ def list_other_stopped_jobs_of_the_agents_shell(agent_process_id):
233
+ """Returns the IDs of the stopped processes that the shell running the agent
234
+ (find_the_shell_running_the_agent) started besides the agent's own job: other suspended
235
+ jobs, one of which a bare `fg` could bring back instead."""
236
+ agent = read_process_bsd_info(agent_process_id)
237
+ shell_process_id = find_the_shell_running_the_agent(agent_process_id)
238
+ if agent is None or shell_process_id is None:
239
+ return []
240
+ other_stopped_job_process_ids = []
241
+ for child_process_id in list_child_process_ids(shell_process_id):
242
+ child = read_process_bsd_info(child_process_id)
243
+ if child is not None and child.pbi_pgid != agent.pbi_pgid and child.pbi_status == STOPPED_PROCESS_STATUS:
244
+ other_stopped_job_process_ids.append(child_process_id)
245
+ return other_stopped_job_process_ids
246
+
247
+
248
+ def process_has_its_terminal(process_id):
249
+ """Returns whether the process's group is its terminal's foreground group, the one that gets
250
+ the keys, as the kernel has it right now (iTerm2's jobPid variable follows only after a while)."""
251
+ bsd_info = read_process_bsd_info(process_id)
252
+ return bsd_info is not None and bsd_info.e_tpgid != 0 and bsd_info.pbi_pgid == bsd_info.e_tpgid
253
+
254
+
255
+ def read_process_arguments_and_environment(process_id):
256
+ """Returns (the arguments the process was started with, the first being its program name as
257
+ typed, {name: value} of the environment it was started with), or ([], {}) if unknown."""
258
+ sysctl_name = (ctypes.c_int * 3)(CTL_KERN, KERN_PROCARGS2, process_id)
259
+ size = ctypes.c_size_t(0)
260
+ if LIBC.sysctl(sysctl_name, 3, None, ctypes.byref(size), None, ctypes.c_size_t(0)) != 0: # asks for the size
261
+ return [], {}
262
+ buffer = ctypes.create_string_buffer(size.value)
263
+ if LIBC.sysctl(sysctl_name, 3, buffer, ctypes.byref(size), None, ctypes.c_size_t(0)) != 0:
264
+ return [], {}
265
+ # The argument count (an int), the executable's path, NUL padding, the arguments, the
266
+ # environment, then an empty string before the kernel's own "name=value" strings.
267
+ argument_count = ctypes.c_int.from_buffer_copy(buffer.raw[:ctypes.sizeof(ctypes.c_int)]).value
268
+ _, _, arguments_and_environment = buffer.raw[ctypes.sizeof(ctypes.c_int):size.value].partition(b"\0")
269
+ words = [word.decode(errors="replace") for word in arguments_and_environment.lstrip(b"\0").split(b"\0")]
270
+ environment_words = words[argument_count:]
271
+ if "" in environment_words:
272
+ environment_words = environment_words[:environment_words.index("")]
273
+ return words[:argument_count], dict(word.partition("=")[::2] for word in environment_words)
274
+
275
+
276
+ def read_name_the_process_was_started_as(process_id):
277
+ """Returns the base name of the process's first argument, the program name as typed ("claude"
278
+ rather than its executable's name, the version number "2.1.303"), or "" if unknown."""
279
+ arguments = read_process_arguments_and_environment(process_id)[0]
280
+ return os.path.basename(arguments[0]) if arguments else ""
281
+
282
+
283
+ def list_child_process_ids(process_id):
284
+ buffer = (ctypes.c_int * MAXIMUM_CHILD_PROCESSES)()
285
+ count = LIBPROC.proc_listchildpids(process_id, buffer, ctypes.sizeof(buffer))
286
+ return [buffer[index] for index in range(max(count, 0)) if buffer[index] > 0]
287
+
288
+
289
+ def list_descendant_processes(process_id, maximum_depth=6):
290
+ """Returns the ProcessInfo of every process below process_id (children, their children, ...),
291
+ down to maximum_depth levels, or all of them for None. Each process is listed once, even if
292
+ a process ID is reused while the tree is read. Another user's processes are left out
293
+ (list_descendant_processes_and_other_users_process_ids)."""
294
+ return list_descendant_processes_and_other_users_process_ids(process_id, maximum_depth)[0]
295
+
296
+
297
+ def list_descendant_processes_and_other_users_process_ids(process_id, maximum_depth=6):
298
+ """Returns (list_descendant_processes's list, the IDs of the processes below process_id that
299
+ belong to another user, such as a command run with sudo, which can't be read and whose own
300
+ children aren't listed)."""
301
+ descendants = []
302
+ other_users_process_ids = []
303
+ listed_process_ids = {process_id}
304
+ parent_process_ids = [process_id]
305
+ depth = 0
306
+ while parent_process_ids and (maximum_depth is None or depth < maximum_depth):
307
+ depth += 1
308
+ next_parent_process_ids = []
309
+ for parent_process_id in parent_process_ids:
310
+ for child_process_id in list_child_process_ids(parent_process_id):
311
+ if child_process_id in listed_process_ids:
312
+ continue
313
+ listed_process_ids.add(child_process_id)
314
+ child = read_process_info(child_process_id)
315
+ if child is not None:
316
+ descendants.append(child)
317
+ next_parent_process_ids.append(child_process_id)
318
+ elif read_name_of_any_process(child_process_id): # not gone meanwhile
319
+ other_users_process_ids.append(child_process_id)
320
+ parent_process_ids = next_parent_process_ids
321
+ return descendants, other_users_process_ids
322
+
323
+
324
+ def list_child_processes_of_the_agent(agent_process_id, descendant_processes, now):
325
+ """Returns [(child, shown process)] for each process the agent started, oldest first (the sub
326
+ rows of an open tab row; user request, 2026-10-27). Codex's own program below its node
327
+ launcher is part of the agent, so the processes it started count instead. The shown process
328
+ is the child itself, or for a shell or wrapper the first process started below it (the agent's
329
+ shell tool runs `python3 ...` inside a `bash -c`), if one runs. As for the command the agent
330
+ waits on, a child counts only once it has run SECONDS_A_COMMAND_RUNS_BEFORE_IT_COUNTS, so the
331
+ hooks and status line commands that end within a second (iTerm2's cc-status) never show.
332
+
333
+ Args:
334
+ agent_process_id: The agent process (the tab's job).
335
+ descendant_processes: ProcessInfo of every process below it (list_descendant_processes).
336
+ now: The current time.
337
+ """
338
+ own_program_process_ids = {agent_process_id} | {
339
+ process.process_id for process in descendant_processes
340
+ if process.parent_process_id == agent_process_id and process.name in NAMES_OF_AGENT_PROGRAMS}
341
+ process_ids_by_parent_process_id = collections.defaultdict(list)
342
+ for process in descendant_processes:
343
+ process_ids_by_parent_process_id[process.parent_process_id].append(process.process_id)
344
+ process_by_id = {process.process_id: process for process in descendant_processes}
345
+
346
+ def find_first_process_run_below(shell):
347
+ below = []
348
+ parent_process_ids = [shell.process_id]
349
+ while parent_process_ids: # every level, so a shell inside a shell is looked through too
350
+ children = [process_by_id[process_id] for parent_process_id in parent_process_ids
351
+ for process_id in process_ids_by_parent_process_id[parent_process_id]]
352
+ below.extend(child for child in children if child.name not in SHELL_AND_WRAPPER_PROCESS_NAMES)
353
+ parent_process_ids = [child.process_id for child in children]
354
+ return min(below, key=lambda process: process.started_at, default=None)
355
+ children = sorted((process for process in descendant_processes if process.parent_process_id in own_program_process_ids
356
+ and process.process_id not in own_program_process_ids
357
+ and now - process.started_at >= SECONDS_A_COMMAND_RUNS_BEFORE_IT_COUNTS),
358
+ key=lambda process: process.started_at)
359
+ return [(child, (find_first_process_run_below(child) if child.name in SHELL_AND_WRAPPER_PROCESS_NAMES else None) or child)
360
+ for child in children]
361
+
362
+
363
+ def child_process_is_a_background_shell(child, shown_process, command_started_at, turn_is_under_way, turn_started_at):
364
+ """Whether one of list_child_processes_of_the_agent's children is a command the agent's shell
365
+ tool left running in the background: a shell or wrapper with a process running in it (not
366
+ Codex's terminal kept open between commands, nor a helper such as an MCP server, which the
367
+ agent starts itself), between turns, or during a turn when the command in it started before
368
+ the turn did. A command started in the turn under way may be the one the agent waits on (the
369
+ order the agent started them in doesn't tell), so it counts only once the turn ends (code
370
+ review, 2026-10-27).
371
+
372
+ Args:
373
+ child, shown_process: One of list_child_processes_of_the_agent's pairs.
374
+ command_started_at: When the command in the shell started: the shell's own start for a
375
+ Claude Code shell (a wait loop from an earlier turn starts a new sleep in this one),
376
+ else the shown process's (Codex runs a later turn's commands in a shell kept from an
377
+ earlier turn) (code review, 2026-10-28).
378
+ turn_is_under_way: Whether the agent is in a turn (working or asking).
379
+ turn_started_at: When that turn began, or None while not known (then no command counts).
380
+ """
381
+ if child.name not in SHELL_AND_WRAPPER_PROCESS_NAMES or shown_process is child:
382
+ return False
383
+ if not turn_is_under_way:
384
+ return True
385
+ return turn_started_at is not None and command_started_at < turn_started_at - SECONDS_OF_SLACK_AT_TURN_START
386
+
387
+
388
+ def build_command_text(arguments, executable_name):
389
+ """Returns how a sub row names a process: its program's base name and its arguments, on one
390
+ line ("python3 -m unittest"), or its executable's name when its arguments can't be read. A
391
+ Claude Code scratchpad folder in them is just "scratchpad" (CLAUDE_CODE_SCRATCHPAD_PATH)."""
392
+ if not arguments:
393
+ return executable_name
394
+ return shorten_scratchpad_paths(" ".join([os.path.basename(arguments[0])] + arguments[1:]).replace("\n", " "))
395
+
396
+
397
+ def shorten_scratchpad_paths(text):
398
+ return CLAUDE_CODE_SCRATCHPAD_PATH.sub("scratchpad", text)
399
+
400
+
401
+ def find_the_command_a_claude_code_shell_runs(arguments):
402
+ """Returns the command Claude Code's shell tool gave a `bash -c` (CLAUDE_CODE_SHELL_TOOL_COMMAND),
403
+ as the agent wrote it, or None for another process. A sub row names such a shell by it (user
404
+ request, 2026-10-28): a background wait loop then reads as the loop, not as the `sleep 30` it
405
+ runs at that moment."""
406
+ if len(arguments) != 3 or arguments[1] != "-c":
407
+ return None
408
+ match = CLAUDE_CODE_SHELL_TOOL_COMMAND.search(arguments[2])
409
+ return match.group(1).replace("'\"'\"'", "'") if match else None
410
+
411
+
412
+ def list_detached_processes(earliest_started_at):
413
+ """Returns [(ProcessInfo, arguments, current folder or None)] for this user's processes that
414
+ launchd adopted (their parent ended) and that started at or after earliest_started_at. A job an
415
+ agent started with `nohup ... &` or `setsid`, whose shell then ended, is one of them: no longer
416
+ below the agent, so list_descendant_processes misses it."""
417
+ detached_processes = []
418
+ for process_id in list_child_process_ids(LAUNCHD_PROCESS_ID):
419
+ process = read_process_info(process_id) # None for another user's process
420
+ if process is not None and process.started_at >= earliest_started_at:
421
+ detached_processes.append((process, read_process_arguments_and_environment(process_id)[0],
422
+ read_process_current_folder(process_id)))
423
+ return detached_processes
424
+
425
+
426
+ def choose_detached_processes_of_the_conversation(detached_processes, conversation_id, agent_started_at):
427
+ """Returns [(ProcessInfo, arguments)] for the detached processes (list_detached_processes) that
428
+ an agent's conversation started, oldest first (user request, 2026-10-28): started after the
429
+ agent, with the conversation's ID in their arguments or current folder, as every path in a
430
+ Claude Code session's scratchpad folder has it. A job run from elsewhere isn't found."""
431
+ return sorted(((process, arguments) for process, arguments, current_folder in detached_processes
432
+ if conversation_id and process.started_at >= agent_started_at
433
+ and (conversation_id in " ".join(arguments) or conversation_id in (current_folder or ""))),
434
+ key=lambda process_and_arguments: process_and_arguments[0].started_at)
435
+
436
+
437
+ def read_child_processes(agent_process_id, turn_is_under_way, turn_started_at, reads_resource_usage, now,
438
+ detached_processes_of_the_conversation=()):
439
+ """Returns [{"child": ProcessInfo, "command_text", "command_started_at", "is_background_shell",
440
+ "is_detached", "resource_usage": (memory in bytes, CPU seconds) of the child and the processes
441
+ below it, or None}] for each process the agent started (list_child_processes_of_the_agent),
442
+ then for each detached one (choose_detached_processes_of_the_conversation), which runs in the background.
443
+ A Claude Code shell is named by its command and dated by its own start; another child by the
444
+ command shown and that command's start (a shell Codex keeps between turns is older).
445
+
446
+ Args:
447
+ agent_process_id: The agent process.
448
+ turn_is_under_way, turn_started_at: See child_process_is_a_background_shell.
449
+ reads_resource_usage: Whether to read each child's memory and CPU time (else None).
450
+ now: The current time.
451
+ detached_processes_of_the_conversation: choose_detached_processes_of_the_conversation's list.
452
+ """
453
+ child_processes = []
454
+ for child, shown_process in list_child_processes_of_the_agent(agent_process_id, list_descendant_processes(agent_process_id), now):
455
+ claude_code_shell_command = find_the_command_a_claude_code_shell_runs(read_process_arguments_and_environment(child.process_id)[0])
456
+ command_started_at = child.started_at if claude_code_shell_command else shown_process.started_at
457
+ child_processes.append({
458
+ "child": child,
459
+ "command_text": (shorten_scratchpad_paths(" ".join(claude_code_shell_command.split())) if claude_code_shell_command
460
+ else build_command_text(read_process_arguments_and_environment(shown_process.process_id)[0],
461
+ shown_process.name)),
462
+ "command_started_at": command_started_at,
463
+ "is_background_shell": child_process_is_a_background_shell(child, shown_process, command_started_at,
464
+ turn_is_under_way, turn_started_at),
465
+ "is_detached": False,
466
+ "resource_usage": read_process_tree_resource_usage(child.process_id) if reads_resource_usage else None})
467
+ for process, arguments in detached_processes_of_the_conversation:
468
+ child_processes.append({
469
+ "child": process, "command_text": build_command_text(arguments, process.name), "command_started_at": process.started_at,
470
+ "is_background_shell": True, "is_detached": True,
471
+ "resource_usage": read_process_tree_resource_usage(process.process_id) if reads_resource_usage else None})
472
+ return sorted(child_processes, key=lambda child_process: child_process["child"].started_at) # oldest first, detached ones too
473
+
474
+
475
+ def choose_helper_process_ids(descendant_processes):
476
+ """Returns the IDs of the processes running below an agent between its turns (MCP servers, for
477
+ example), which choose_command_the_agent_is_waiting_on never takes for a command, nor anything
478
+ below them. Shells and wrappers (Codex keeps a terminal open between commands) and the agent's
479
+ own program (Codex's below its node launcher) are left out, since a later turn's commands run
480
+ below them."""
481
+ return frozenset(process.process_id for process in descendant_processes
482
+ if process.name not in SHELL_AND_WRAPPER_PROCESS_NAMES and process.name not in NAMES_OF_AGENT_PROGRAMS)
483
+
484
+
485
+ def an_agent_program_runs_through_a_shell_below(descendant_processes, read_started_as_name):
486
+ """Returns whether one of the processes (all below an agent) is an agent program
487
+ (NAMES_OF_AGENT_PROGRAMS) started through a shell or wrapper below the agent, as the agent's
488
+ shell tool starts a `claude -p` or `codex exec`. The agent's own parts aren't started through
489
+ one (Codex's program below its node launcher).
490
+
491
+ Args:
492
+ descendant_processes: ProcessInfo of every process below the agent process.
493
+ read_started_as_name: Returns the name a process was started as
494
+ (read_name_the_process_was_started_as); asked only about processes below a shell.
495
+ """
496
+ process_by_id = {process.process_id: process for process in descendant_processes}
497
+
498
+ def runs_below_a_shell(process):
499
+ visited_process_ids = {process.process_id} # a process ID reused while the tree was read can't loop
500
+ parent = process_by_id.get(process.parent_process_id)
501
+ while parent is not None and parent.process_id not in visited_process_ids:
502
+ if parent.name in SHELL_AND_WRAPPER_PROCESS_NAMES:
503
+ return True
504
+ visited_process_ids.add(parent.process_id)
505
+ parent = process_by_id.get(parent.parent_process_id)
506
+ return False
507
+ return any(runs_below_a_shell(process) and read_started_as_name(process.process_id) in NAMES_OF_AGENT_PROGRAMS
508
+ for process in descendant_processes)
509
+
510
+
511
+ def choose_command_the_agent_is_waiting_on(descendant_processes, turn_started_at, helper_process_names, now,
512
+ helper_process_ids=frozenset(), read_process_arguments=lambda process_id: []):
513
+ """Returns (the command's process, started at) for the command an agent started in this turn
514
+ and is still running, or None when it runs none (it is thinking or writing).
515
+
516
+ Not commands, and nor is anything below them: the tool's own helpers (Claude Code's
517
+ caffeinate, Codex's code mode host), processes that were already running while the session
518
+ was idle (MCP servers, from the second turn on), processes older than the turn, and Claude
519
+ Code shells older than the turn: each runs one command, so one from an earlier turn is a
520
+ command left in the background, and what it starts now (a wait loop's next `sleep 30`) isn't
521
+ this turn's (code review, 2026-10-28; Codex runs new commands in a terminal it keeps, so its
522
+ shells aren't told apart this way). A shell with nothing running in it doesn't count either,
523
+ nor does a command younger than SECONDS_A_COMMAND_RUNS_BEFORE_IT_COUNTS.
524
+
525
+ Args:
526
+ descendant_processes: ProcessInfo of every process below the agent process.
527
+ turn_started_at: When the agent's current turn began.
528
+ helper_process_names: Executable names of the agent tool's own helper processes.
529
+ now: The current time.
530
+ helper_process_ids: IDs of processes seen running while the session was idle.
531
+ read_process_arguments: Returns a process's arguments (read_process_arguments_and_environment's
532
+ first part); asked only about shells older than the turn.
533
+ """
534
+ excluded_process_ids = set(helper_process_ids) | {process.process_id for process in descendant_processes
535
+ if process.name in helper_process_names}
536
+ excluded_process_ids |= {process.process_id for process in descendant_processes
537
+ if process.name in SHELL_AND_WRAPPER_PROCESS_NAMES
538
+ and process.started_at < turn_started_at - SECONDS_OF_SLACK_AT_TURN_START
539
+ and find_the_command_a_claude_code_shell_runs(read_process_arguments(process.process_id))}
540
+ found_more = True
541
+ while found_more: # everything below an excluded process is excluded too
542
+ below_excluded = {process.process_id for process in descendant_processes
543
+ if process.parent_process_id in excluded_process_ids} - excluded_process_ids
544
+ excluded_process_ids |= below_excluded
545
+ found_more = bool(below_excluded)
546
+ parent_process_ids = {process.parent_process_id for process in descendant_processes}
547
+ started_in_this_turn = sorted(
548
+ (process for process in descendant_processes
549
+ if process.process_id not in excluded_process_ids
550
+ and process.started_at >= turn_started_at - SECONDS_OF_SLACK_AT_TURN_START
551
+ and not (process.name in SHELL_AND_WRAPPER_PROCESS_NAMES and process.process_id not in parent_process_ids)),
552
+ key=lambda process: process.started_at)
553
+ if not started_in_this_turn or now - started_in_this_turn[0].started_at < SECONDS_A_COMMAND_RUNS_BEFORE_IT_COUNTS:
554
+ return None
555
+ named_process = next((process for process in started_in_this_turn if process.name not in SHELL_AND_WRAPPER_PROCESS_NAMES),
556
+ started_in_this_turn[0])
557
+ return named_process, started_in_this_turn[0].started_at