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,109 @@
1
+ """Which monitor each window is on. Frames are (x, y, width, height) in one shared coordinate system."""
2
+
3
+
4
+ def compute_overlap_area(first_frame, second_frame):
5
+ """Returns the area where two (x, y, width, height) rectangles overlap (0 when they don't)."""
6
+ overlap_width = min(first_frame[0] + first_frame[2], second_frame[0] + second_frame[2]) - max(first_frame[0], second_frame[0])
7
+ overlap_height = min(first_frame[1] + first_frame[3], second_frame[1] + second_frame[3]) - max(first_frame[1], second_frame[1])
8
+ return max(overlap_width, 0) * max(overlap_height, 0)
9
+
10
+
11
+ def frames_are_within_tolerance(first_frame, second_frame, tolerance_points):
12
+ """Returns whether two (x, y, width, height) frames differ by at most tolerance_points in each value."""
13
+ return all(abs(first - second) <= tolerance_points for first, second in zip(first_frame, second_frame))
14
+
15
+
16
+ def compute_squared_distance_between_centers(first_frame, second_frame):
17
+ """Returns the squared distance between the centers of two rectangles."""
18
+ delta_x = (first_frame[0] + first_frame[2] / 2) - (second_frame[0] + second_frame[2] / 2)
19
+ delta_y = (first_frame[1] + first_frame[3] / 2) - (second_frame[1] + second_frame[3] / 2)
20
+ return delta_x * delta_x + delta_y * delta_y
21
+
22
+
23
+ def compute_window_frame_on_another_monitor(window_frame, source_visible_frame, target_visible_frame):
24
+ """Returns the frame for a window moved to another monitor.
25
+
26
+ The window keeps its size if it fits in the target's usable area (otherwise it shrinks to
27
+ fit), and keeps its position relative to that area (for example centered stays centered).
28
+
29
+ Args:
30
+ window_frame: The window's (x, y, width, height).
31
+ source_visible_frame: The usable area of the monitor the window is on now.
32
+ target_visible_frame: The usable area of the monitor it moves to.
33
+
34
+ Returns:
35
+ An (x, y, width, height) tuple inside target_visible_frame.
36
+ """
37
+ target_x, target_y, target_width, target_height = target_visible_frame
38
+ width = min(window_frame[2], target_width)
39
+ height = min(window_frame[3], target_height)
40
+
41
+ def place_along_one_axis(window_start, window_length, source_start, source_length, target_start, target_length, new_length):
42
+ free_space_on_source = source_length - window_length
43
+ fraction = (window_start - source_start) / free_space_on_source if free_space_on_source > 0 else 0.5
44
+ fraction = min(max(fraction, 0.0), 1.0)
45
+ return target_start + fraction * (target_length - new_length)
46
+
47
+ x = place_along_one_axis(window_frame[0], window_frame[2], source_visible_frame[0], source_visible_frame[2],
48
+ target_x, target_width, width)
49
+ y = place_along_one_axis(window_frame[1], window_frame[3], source_visible_frame[1], source_visible_frame[3],
50
+ target_y, target_height, height)
51
+ return (x, y, width, height)
52
+
53
+
54
+ def compute_frame_clear_of_area(window_frame, reserved_area, sidebar_edge, monitor_visible_frame, smallest_width):
55
+ """Returns the window frame changed so it no longer reaches into a docked sidebar's area,
56
+ or None when it already doesn't.
57
+
58
+ The window is fitted into the rest of the monitor's usable area: it keeps whatever part
59
+ lies there, and if that is narrower than smallest_width, it gets that width (or the whole
60
+ rest, if smaller) on the side away from the sidebar. It never moves past the monitor's edge.
61
+
62
+ Args:
63
+ window_frame: The window's (x, y, width, height).
64
+ reserved_area: The sidebar's (x, y, width, height).
65
+ sidebar_edge: "right" or "left", the monitor edge the sidebar is docked to.
66
+ monitor_visible_frame: The usable area of the sidebar's monitor.
67
+ smallest_width: The narrowest a window is made.
68
+ """
69
+ if compute_overlap_area(window_frame, reserved_area) <= 0:
70
+ return None
71
+ x, y, width, height = window_frame
72
+ monitor_x, _, monitor_width, _ = monitor_visible_frame
73
+ area_x, _, area_width, _ = reserved_area
74
+ if sidebar_edge == "right":
75
+ usable_left, usable_right = monitor_x, area_x
76
+ else:
77
+ usable_left, usable_right = area_x + area_width, monitor_x + monitor_width
78
+ new_x = max(x, usable_left)
79
+ new_width = min(x + width, usable_right) - new_x
80
+ if new_width < smallest_width:
81
+ new_width = min(smallest_width, usable_right - usable_left)
82
+ new_x = usable_right - new_width if sidebar_edge == "right" else usable_left
83
+ return (new_x, y, new_width, height)
84
+
85
+
86
+ def assign_windows_to_monitors_by_largest_overlap(window_frames_by_window_id, monitor_frames):
87
+ """Returns {window_id: monitor index} putting each window on the monitor it overlaps most.
88
+
89
+ A window that overlaps no monitor (for example one left off-screen after a monitor was
90
+ unplugged) goes to the monitor whose center is nearest. Ties go to the earlier monitor.
91
+
92
+ Args:
93
+ window_frames_by_window_id: {window_id: (x, y, width, height)}.
94
+ monitor_frames: Monitor frames, in the order the monitor groups are listed.
95
+
96
+ Returns:
97
+ A dict; empty when there are no monitors.
98
+ """
99
+ if not monitor_frames:
100
+ return {}
101
+ monitor_index_by_window_id = {}
102
+ for window_id, window_frame in window_frames_by_window_id.items():
103
+ overlap_areas = [compute_overlap_area(window_frame, monitor_frame) for monitor_frame in monitor_frames]
104
+ if max(overlap_areas) > 0:
105
+ monitor_index_by_window_id[window_id] = overlap_areas.index(max(overlap_areas))
106
+ else:
107
+ distances = [compute_squared_distance_between_centers(window_frame, monitor_frame) for monitor_frame in monitor_frames]
108
+ monitor_index_by_window_id[window_id] = distances.index(min(distances))
109
+ return monitor_index_by_window_id
@@ -0,0 +1,61 @@
1
+ """The records of paused agent sessions (agent_session_pausing.PauseRecord), kept in a file next to the settings.
2
+
3
+ So the processes a pause stopped are still continued, and Resume still works, after the
4
+ dashboard restarts while sessions are paused (a reconnect when iTerm2's connection drops, a
5
+ quit, an upgrade). Pure functions apart from the file reading and writing.
6
+ """
7
+
8
+ import json
9
+ import os
10
+
11
+ from agent_command_tab.agent_session_pausing import PauseRecord
12
+ from agent_command_tab.settings_store import SETTINGS_FOLDER, write_json_file_atomically
13
+
14
+ PAUSE_RECORDS_FILE_PATH = os.path.join(SETTINGS_FOLDER, "paused_agent_sessions.json")
15
+
16
+
17
+ def is_process_record(value):
18
+ """Whether value is a stored (process ID, start time) pair."""
19
+ return (isinstance(value, list) and len(value) == 2 and isinstance(value[0], int) and not isinstance(value[0], bool)
20
+ and isinstance(value[1], (int, float)) and not isinstance(value[1], bool))
21
+
22
+
23
+ def build_pause_record_from_stored_value(value):
24
+ """Returns the PauseRecord a stored value describes, or None when it doesn't have that shape."""
25
+ if (not isinstance(value, dict) or not is_process_record(value.get("agent_process"))
26
+ or not isinstance(value.get("agent_tool_name"), str)):
27
+ return None
28
+ text_around_the_cursor = value.get("text_around_the_cursor")
29
+ if not (text_around_the_cursor is None or (isinstance(text_around_the_cursor, list) and len(text_around_the_cursor) == 2
30
+ and all(isinstance(text, str) for text in text_around_the_cursor))):
31
+ return None
32
+ stopped_processes = value.get("stopped_processes")
33
+ if not isinstance(stopped_processes, list) or not all(map(is_process_record, stopped_processes)):
34
+ return None
35
+ return PauseRecord(tuple(value["agent_process"]), value["agent_tool_name"],
36
+ tuple(text_around_the_cursor) if text_around_the_cursor else None,
37
+ [tuple(process) for process in stopped_processes])
38
+
39
+
40
+ def load_pause_records(file_path):
41
+ """Returns {(session ID, agent process ID): PauseRecord} from the file; {} when it is missing
42
+ or unreadable, and without records that don't have that shape."""
43
+ try:
44
+ with open(file_path) as file:
45
+ stored_records = json.load(file)
46
+ except (OSError, ValueError):
47
+ return {}
48
+ if not isinstance(stored_records, list):
49
+ return {}
50
+ pause_record_by_tab_and_agent = {}
51
+ for value in stored_records:
52
+ pause_record = build_pause_record_from_stored_value(value)
53
+ if pause_record is not None and isinstance(value.get("session_id"), str):
54
+ pause_record_by_tab_and_agent[(value["session_id"], pause_record.agent_process[0])] = pause_record
55
+ return pause_record_by_tab_and_agent
56
+
57
+
58
+ def save_pause_records(file_path, pause_record_by_tab_and_agent):
59
+ """Writes the records as a list, each with its tab's session ID."""
60
+ write_json_file_atomically([dict(pause_record._asdict(), session_id=session_id)
61
+ for (session_id, _), pause_record in pause_record_by_tab_and_agent.items()], file_path)
@@ -0,0 +1,108 @@
1
+ """What the dashboard reads from an agent's screen. Pure functions.
2
+
3
+ - Whether a permission dialog is showing: Claude Code reports nothing when the user answers a
4
+ permission prompt, and iTerm2's status stays "waiting" until the approved tool finishes
5
+ (Phase 0), so "asking" ends when the dialog is gone from the screen.
6
+ - A fingerprint of the screen with the lines that change while nothing happens masked out
7
+ (spinners, elapsed times, token counts, clocks), for "stuck" detection.
8
+ """
9
+
10
+ import hashlib
11
+ import re
12
+
13
+ LINES_IN_FINGERPRINT = 20
14
+ LONGEST_INPUT_AREA_LINES = 12 # a draft longer than this counts as not empty
15
+ # Cells an empty input box may hold besides faint text: blanks, iTerm2's empty cells, a
16
+ # no-break space, and Codex's braille-dot idle animation.
17
+ EMPTY_INPUT_CELL_PATTERN = re.compile(r"[ \x00 ⠀-⣿]")
18
+ # Changes in every redraw of any tool: clocks (also in status lines) and braille-dot animations.
19
+ COMMON_PROGRESS_NOISE_PATTERNS = [
20
+ re.compile(r"\d{1,2}:\d{2}(?::\d{2})?\s?(?:AM|PM)?"),
21
+ re.compile(r"[⠀-⣿]"),
22
+ ]
23
+
24
+
25
+ def clean_screen_line(line):
26
+ """Returns a screen line with iTerm2's empty cells (NUL characters) turned into spaces."""
27
+ return line.replace("\x00", " ")
28
+
29
+
30
+ def screen_shows_permission_dialog(screen_lines, permission_dialog_screen_patterns):
31
+ """Returns whether every pattern of the adapter's permission dialog appears in the last 30
32
+ non-blank lines (a fresh or cleared tab leaves blank rows below the dialog).
33
+
34
+ Args:
35
+ screen_lines: The visible screen's lines.
36
+ permission_dialog_screen_patterns: Compiled patterns that must all match some line.
37
+ """
38
+ bottom_lines = [line for line in map(clean_screen_line, screen_lines) if line.strip()][-30:]
39
+ return all(any(pattern.search(line) for line in bottom_lines) for pattern in permission_dialog_screen_patterns)
40
+
41
+
42
+ def read_typed_input_area_text(screen_lines_with_faint_flags, input_line_marker, input_area_end_pattern):
43
+ """Returns the text typed into the agent's input box, or None when the box can't be found on
44
+ screen.
45
+
46
+ The input line is the last line starting with the marker; the input area runs from it to
47
+ the line just below it that matches input_area_end_pattern (a multi-line draft continues on
48
+ the lines in between). Typed text is what follows the marker except faint cells (the tool's
49
+ placeholder or suggested prompt) and EMPTY_INPUT_CELL_PATTERN cells, with the area's lines
50
+ joined by newlines and empty lines at the start and end left out.
51
+
52
+ Args:
53
+ screen_lines_with_faint_flags: For each visible line, (text, faint_flags): its
54
+ characters and, for each, whether it is drawn faint.
55
+ input_line_marker: The character that starts the input line ("❯", "›").
56
+ input_area_end_pattern: Compiled pattern of the line just below the input area.
57
+ """
58
+ marker_line_indexes = [index for index, (text, _) in enumerate(screen_lines_with_faint_flags)
59
+ if text.lstrip(" \x00").startswith(input_line_marker)]
60
+ if not marker_line_indexes:
61
+ return None
62
+ input_line_index = marker_line_indexes[-1]
63
+ last_index_to_look_at = min(input_line_index + LONGEST_INPUT_AREA_LINES, len(screen_lines_with_faint_flags) - 1)
64
+ end_index = next((index for index in range(input_line_index + 1, last_index_to_look_at + 1)
65
+ if input_area_end_pattern.search(clean_screen_line(screen_lines_with_faint_flags[index][0]))), None)
66
+ if end_index is None:
67
+ return None
68
+ typed_lines = []
69
+ for index in range(input_line_index, end_index):
70
+ text, faint_flags = screen_lines_with_faint_flags[index]
71
+ first_input_position = text.index(input_line_marker) + 1 if index == input_line_index else 0
72
+ typed_lines.append("".join(
73
+ text[position] for position in range(first_input_position, len(text))
74
+ if not (position < len(faint_flags) and faint_flags[position]) and not EMPTY_INPUT_CELL_PATTERN.match(text[position])))
75
+ return "\n".join(typed_lines).strip("\n")
76
+
77
+
78
+ def input_area_is_empty(screen_lines_with_faint_flags, input_line_marker, input_area_end_pattern):
79
+ """Returns whether the agent's input box holds no typed text, so a command typed into it
80
+ can't join a draft (read_typed_input_area_text). Fails safe: False when the box can't be
81
+ found on screen."""
82
+ return read_typed_input_area_text(screen_lines_with_faint_flags, input_line_marker, input_area_end_pattern) == ""
83
+
84
+
85
+ def count_lines_matching(screen_lines, pattern):
86
+ """Returns how many screen lines match pattern (0 when pattern is None)."""
87
+ if pattern is None:
88
+ return 0
89
+ return sum(1 for line in screen_lines if pattern.search(clean_screen_line(line)))
90
+
91
+
92
+ def compute_screen_fingerprint(screen_lines, progress_noise_patterns):
93
+ """Returns a hash of the last non-blank lines with the adapter's progress noise removed.
94
+
95
+ Args:
96
+ screen_lines: The visible screen's lines.
97
+ progress_noise_patterns: Compiled patterns for text that changes without real progress.
98
+ """
99
+ patterns = list(progress_noise_patterns) + COMMON_PROGRESS_NOISE_PATTERNS
100
+ cleaned_lines = []
101
+ for line in screen_lines:
102
+ line = clean_screen_line(line)
103
+ for pattern in patterns:
104
+ line = pattern.sub(" ", line)
105
+ line = " ".join(line.split()) # removed noise and a blinking bullet also shift the spacing
106
+ if line:
107
+ cleaned_lines.append(line)
108
+ return hashlib.sha256("\n".join(cleaned_lines[-LINES_IN_FINGERPRINT:]).encode()).hexdigest()
@@ -0,0 +1,228 @@
1
+ """The one-line preview under each tab row (user request, 2026-10-19), read from the end of
2
+ the agent session's own conversation file, the same file the context size comes from
3
+ (context_window_usage).
4
+
5
+ In order of preference the preview shows what the agent asks permission for (the tool and its
6
+ main input, or the question it asks), the tool it is running, the start of what it said since
7
+ the last prompt, and the last prompt itself ("You: ...").
8
+ """
9
+
10
+ import json
11
+ import re
12
+
13
+ from agent_command_tab.claude_code_transcript_records import (classify_user_record, describe_typed_command,
14
+ join_text_blocks, list_message_blocks)
15
+ from agent_command_tab.context_window_usage import parse_iso_time, read_last_records
16
+
17
+ LONGEST_PREVIEW_TEXT = 300 # the row cuts it to its width anyway
18
+ TOOL_INPUT_KEYS_IN_PREFERENCE_ORDER = ("command", "file_path", "notebook_path", "path", "pattern", "url", "query",
19
+ "description", "prompt", "skill")
20
+ # A line holding only a time, such as "[10/19/2026 09:19:52 AM EDT]", which some users have every reply start with.
21
+ BRACKETED_TIME_LINE = re.compile(r"^\[[^\]]*\d{1,2}:\d{2}[^\]]*\]$")
22
+ MARKDOWN_LINE_START = re.compile(r"^(?:#+|>|[-*+]|\d+[.)])\s+")
23
+ # The command in a Codex "exec" tool call, whose input is JavaScript such as tools.exec_command({cmd:"ls -la"}).
24
+ CODEX_EXEC_COMMAND = re.compile(r'\bcmd\s*:\s*"((?:[^"\\]|\\.)*)"')
25
+
26
+
27
+ def make_one_line(text):
28
+ """Returns text as one line for a preview, unchanged otherwise (a command or a pattern such as
29
+ "**/*.py" must show as the agent asks to run it): runs of whitespace become one space, and the
30
+ result is cut to LONGEST_PREVIEW_TEXT."""
31
+ return " ".join(str(text).split())[:LONGEST_PREVIEW_TEXT]
32
+
33
+
34
+ def make_one_line_without_markdown(text):
35
+ """Returns a prompt or a message as one line for a preview (make_one_line): blank lines and
36
+ lines holding only a bracketed time are dropped first, and Markdown heading, quote and list
37
+ markers and bold markers are removed."""
38
+ kept_lines = []
39
+ for line in str(text).replace("**", "").split("\n"):
40
+ line = MARKDOWN_LINE_START.sub("", line.strip())
41
+ if line and not BRACKETED_TIME_LINE.match(line):
42
+ kept_lines.append(line)
43
+ return make_one_line(" ".join(kept_lines))
44
+
45
+
46
+ def describe_claude_code_tool_call(tool_name, tool_input):
47
+ """Returns "Bash: python3 -m unittest": the tool's name and its main input (the command, file,
48
+ pattern and so on), or the question an AskUserQuestion call asks."""
49
+ if not isinstance(tool_input, dict):
50
+ return tool_name
51
+ questions = tool_input.get("questions")
52
+ if tool_name == "AskUserQuestion" and isinstance(questions, list) and questions and isinstance(questions[0], dict):
53
+ return make_one_line_without_markdown(questions[0].get("question") or "") or tool_name
54
+ for key in TOOL_INPUT_KEYS_IN_PREFERENCE_ORDER:
55
+ if isinstance(tool_input.get(key), str) and tool_input[key].strip():
56
+ return f"{tool_name}: {make_one_line(tool_input[key])}"
57
+ return tool_name
58
+
59
+
60
+ def describe_codex_tool_call(payload):
61
+ """Returns "exec: ls -la" for a Codex function_call or custom_tool_call record's payload: the
62
+ tool's name and its command, or "" for a call without one (Codex polls a running command
63
+ with write_stdin and wait calls)."""
64
+ tool_name = payload.get("name") or "tool"
65
+ command = None
66
+ if payload.get("type") == "function_call":
67
+ try:
68
+ arguments = json.loads(payload.get("arguments") or "{}")
69
+ except ValueError:
70
+ arguments = {}
71
+ command = arguments.get("cmd") or arguments.get("command") if isinstance(arguments, dict) else None
72
+ if isinstance(command, list):
73
+ command = " ".join(str(part) for part in command)
74
+ else:
75
+ command_match = CODEX_EXEC_COMMAND.search(str(payload.get("input") or ""))
76
+ if command_match:
77
+ try:
78
+ command = json.loads(f'"{command_match.group(1)}"')
79
+ except ValueError:
80
+ command = command_match.group(1)
81
+ return f"{tool_name}: {make_one_line(command)}" if isinstance(command, str) and command.strip() else ""
82
+
83
+
84
+ def join_codex_item_texts(item):
85
+ """Returns the text of a Codex 0.163 UserMessage or AgentMessage item (its "text" or "Text" parts)."""
86
+ content = item.get("content")
87
+ return "\n".join(str(part.get("text") or "") for part in content if isinstance(part, dict)
88
+ and str(part.get("type")).lower() == "text") if isinstance(content, list) else ""
89
+
90
+
91
+ def build_preview_fields(last_prompt, message_since_prompt, open_tool_call, open_tool_name, open_tool_started_at):
92
+ """Returns the preview fields dict that the readers below return."""
93
+ return {"last_prompt": last_prompt, "message_since_prompt": message_since_prompt, "open_tool_call": open_tool_call,
94
+ "open_tool_name": open_tool_name, "open_tool_started_at": open_tool_started_at}
95
+
96
+
97
+ def read_record_time(record):
98
+ """Returns a conversation file record's "timestamp", which Claude Code and Codex both write in
99
+ ISO 8601 ("2026-10-28T11:12:04.784Z"), as seconds since 1970, or None without a readable one.
100
+ parse_iso_time reads the trailing "Z", which datetime.fromisoformat does only from Python 3.11
101
+ (code review, 2026-10-28)."""
102
+ return parse_iso_time(record.get("timestamp")) or None
103
+
104
+
105
+ def read_preview_fields_from_claude_code_transcript(file_path):
106
+ """Returns the preview fields from the end of a Claude Code transcript.
107
+
108
+ Records are read newest first, back to the last prompt. Each assistant record holds one
109
+ block (text, thinking or tool_use); a tool_use is open while no later user record holds its
110
+ tool_result and the agent has written no text since. Which user records start a turn is
111
+ claude_code_transcript_records.classify_user_record's rule: a slash command or skill the
112
+ user typed is a prompt ("/name arguments"); a background task's notification starts a turn
113
+ too, whose prompt is then the last one typed. When the prompt is older than the part read,
114
+ or a notification started the turn, the "last-prompt" record that Claude Code keeps near
115
+ the end supplies it.
116
+
117
+ Returns:
118
+ {"last_prompt": str, "message_since_prompt": str, "open_tool_call": str, "open_tool_name":
119
+ str, "open_tool_started_at": float or None}, the texts "" and the time None when not
120
+ found; texts are one line: prompts and messages without Markdown markers
121
+ (make_one_line_without_markdown), tool calls as the agent asks to run them (make_one_line).
122
+ open_tool_name and open_tool_started_at are the open call's tool and when its record was
123
+ written (read_record_time).
124
+ """
125
+ answered_tool_use_ids = set()
126
+ message_since_prompt = ""
127
+ open_tool_call = ""
128
+ open_tool_name = ""
129
+ open_tool_started_at = None
130
+ saved_last_prompt = ""
131
+ turn_started_with_a_notification = False # then only the prompt is still looked for
132
+ for record in read_last_records(file_path):
133
+ if record.get("isSidechain"):
134
+ continue
135
+ if record.get("type") == "last-prompt":
136
+ saved_last_prompt = saved_last_prompt or make_one_line_without_markdown(record.get("lastPrompt") or "")
137
+ if turn_started_with_a_notification:
138
+ break
139
+ continue
140
+ blocks = list_message_blocks(record)
141
+ user_record_kind = classify_user_record(record, blocks)
142
+ if user_record_kind == "tool_result":
143
+ answered_tool_use_ids |= {block.get("tool_use_id") for block in blocks if block.get("type") == "tool_result"}
144
+ elif user_record_kind == "command":
145
+ return build_preview_fields(make_one_line(describe_typed_command(join_text_blocks(blocks))), message_since_prompt,
146
+ open_tool_call, open_tool_name, open_tool_started_at)
147
+ elif user_record_kind == "prompt":
148
+ return build_preview_fields(make_one_line_without_markdown(join_text_blocks(blocks)), message_since_prompt,
149
+ open_tool_call, open_tool_name, open_tool_started_at)
150
+ elif user_record_kind == "notification":
151
+ turn_started_with_a_notification = True
152
+ if saved_last_prompt:
153
+ break
154
+ elif record.get("type") == "assistant" and not turn_started_with_a_notification:
155
+ for block in reversed(blocks):
156
+ if block.get("type") == "text" and not message_since_prompt and str(block.get("text") or "").strip():
157
+ message_since_prompt = make_one_line_without_markdown(block["text"])
158
+ elif (block.get("type") == "tool_use" and not open_tool_call and not message_since_prompt
159
+ and block.get("id") not in answered_tool_use_ids):
160
+ open_tool_name, open_tool_started_at = block.get("name") or "tool", read_record_time(record)
161
+ open_tool_call = describe_claude_code_tool_call(open_tool_name, block.get("input"))
162
+ return build_preview_fields(saved_last_prompt, message_since_prompt, open_tool_call, open_tool_name, open_tool_started_at)
163
+
164
+
165
+ def read_preview_fields_from_codex_conversation_file(file_path):
166
+ """Returns the preview fields from the end of a Codex conversation file (rollout-*.jsonl).
167
+
168
+ Records are read newest first, back to the last prompt: an "item_completed" event with a
169
+ UserMessage item (Codex 0.163) or a "user_message" event (earlier versions). What the agent
170
+ said comes from AgentMessage items or "agent_message" events. A function_call or
171
+ custom_tool_call with a command is open while no later output record has its call_id and
172
+ the agent has said nothing since.
173
+
174
+ Returns:
175
+ The fields read_preview_fields_from_claude_code_transcript returns. open_tool_call is the
176
+ newest open call with a command; open_tool_name and open_tool_started_at the newest open
177
+ call of any kind (also a call without a command, such as a wait on a command that runs).
178
+ """
179
+ answered_call_ids = set()
180
+ message_since_prompt = ""
181
+ open_tool_call = ""
182
+ open_tool_name = ""
183
+ open_tool_started_at = None
184
+ for record in read_last_records(file_path):
185
+ payload = record.get("payload")
186
+ if not isinstance(payload, dict):
187
+ continue
188
+ payload_type = payload.get("type")
189
+ if record.get("type") == "event_msg":
190
+ item = payload.get("item") if payload_type == "item_completed" and isinstance(payload.get("item"), dict) else {}
191
+ prompt_text = (str(payload.get("message") or "") if payload_type == "user_message"
192
+ else join_codex_item_texts(item) if item.get("type") == "UserMessage" else "")
193
+ if prompt_text.strip():
194
+ return build_preview_fields(make_one_line_without_markdown(prompt_text), message_since_prompt, open_tool_call,
195
+ open_tool_name, open_tool_started_at)
196
+ agent_text = (str(payload.get("message") or "") if payload_type == "agent_message"
197
+ else join_codex_item_texts(item) if item.get("type") == "AgentMessage" else "")
198
+ if agent_text.strip() and not message_since_prompt:
199
+ message_since_prompt = make_one_line_without_markdown(agent_text)
200
+ elif record.get("type") == "response_item":
201
+ if payload_type in ("function_call_output", "custom_tool_call_output"):
202
+ answered_call_ids.add(payload.get("call_id"))
203
+ elif (payload_type in ("function_call", "custom_tool_call") and not message_since_prompt
204
+ and payload.get("call_id") not in answered_call_ids):
205
+ if not open_tool_name:
206
+ open_tool_name, open_tool_started_at = payload.get("name") or "tool", read_record_time(record)
207
+ if not open_tool_call:
208
+ open_tool_call = describe_codex_tool_call(payload) # "" for a call without a command: look further
209
+ return build_preview_fields("", message_since_prompt, open_tool_call, open_tool_name, open_tool_started_at)
210
+
211
+
212
+ def choose_preview_text(state, preview_fields):
213
+ """Returns the preview line for an agent session in this state: the open tool call
214
+ while it works or asks (the tool asking permission, or the question), else what it said
215
+ since the last prompt, else the last prompt ("You: ..."), else "".
216
+
217
+ Args:
218
+ state: The session's state (session_status_computation.STATES_IN_URGENCY_ORDER).
219
+ preview_fields: From the adapter's read_preview_fields, or None before the file was read.
220
+ """
221
+ preview_fields = preview_fields or {}
222
+ if state in ("asking", "working", "stuck") and preview_fields.get("open_tool_call"):
223
+ return preview_fields["open_tool_call"]
224
+ if preview_fields.get("message_since_prompt"):
225
+ return preview_fields["message_since_prompt"]
226
+ if preview_fields.get("last_prompt"):
227
+ return "You: " + preview_fields["last_prompt"]
228
+ return ""