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,235 @@
1
+ """Agent session states, their urgency order, and how a session's state is worked out.
2
+
3
+ A state comes from iTerm2's `status` variable plus the core's readings of the session: whether
4
+ the permission dialog is still on screen, a screen fingerprint (for "stuck"), and the command
5
+ the agent runs (agent_process_tree). Hook events are added as a further source in phase 2.
6
+ """
7
+
8
+ # "paused": the agent process is stopped (Pause from the list, or Ctrl+Z) until it is resumed.
9
+ # "background": idle, but with background processes it started still running (user request,
10
+ # 2026-10-28; iterm2_snapshot_builder.session_has_background_work), so it isn't taken for idle.
11
+ STATES_IN_URGENCY_ORDER = ["asking", "error", "stuck", "working", "background", "done", "idle", "paused", "unknown", "exited"]
12
+ # Between turns: the agent waits at its prompt, so /compact and /clear can be typed into it.
13
+ STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT = frozenset({"idle", "done", "background"})
14
+ # During a turn, as iTerm2's status shows it: a permission prompt in between doesn't end the turn.
15
+ STATES_OF_A_TURN_UNDER_WAY = frozenset({"working", "asking"})
16
+
17
+ # A Claude Code session's own report in `claude agents --json`, for a tab for which iTerm2 has no
18
+ # status at all, neither its `status` variable nor what its tab bar shows (for example without
19
+ # iTerm2's Claude Code integration hooks; user request, 2026-10-21).
20
+ CLAUDE_AGENTS_STATUSES_TO_STATES = {"idle": "idle", "busy": "working", "waiting": "asking"}
21
+
22
+ ITERM2_STATUS_WORDS_TO_STATES = {
23
+ "idle": "idle",
24
+ "working": "working",
25
+ "waiting": "asking",
26
+ "done": "done",
27
+ "failed": "error",
28
+ "error": "error",
29
+ }
30
+
31
+
32
+ def map_iterm2_status_value_to_state(iterm2_status_value):
33
+ """Returns the state for a value of iTerm2's `status` variable, or None for no signal.
34
+
35
+ The variable is fed by OSC 7501 reports (fixed words) and OSC 21337 (free text such as
36
+ "Working"), so known words are matched case-insensitively and anything else is ignored.
37
+
38
+ Args:
39
+ iterm2_status_value: The variable's value, or None when unset.
40
+ """
41
+ if not iterm2_status_value:
42
+ return None
43
+ return ITERM2_STATUS_WORDS_TO_STATES.get(str(iterm2_status_value).strip().lower())
44
+
45
+
46
+ def update_permission_dialog_reading(screen_reading, dialog_is_showing, interrupted_line_count,
47
+ iterm2_status_change_time, now):
48
+ """Returns the screen reading updated with one permission dialog check of an asking session.
49
+
50
+ The dialog counts as answered once it was seen and then went away: approved, or denied when
51
+ a new "Interrupted" line appeared ("No" or Esc). A dialog never seen since the session
52
+ started asking (wording the adapter doesn't recognize, or not drawn yet) keeps the session
53
+ asking, unless a new "Interrupted" line shows that the turn ended (when
54
+ the match is ambiguous, the request stays open).
55
+
56
+ Args:
57
+ screen_reading: The session's reading so far; it is not changed.
58
+ dialog_is_showing: Whether this check found the adapter's permission dialog.
59
+ interrupted_line_count: How many of the adapter's "Interrupted" lines this check found.
60
+ iterm2_status_change_time: When iTerm2's status last changed; earlier checks belong to
61
+ an earlier prompt and are forgotten.
62
+ now: The time of this check.
63
+
64
+ Returns:
65
+ A new dict with "permission_dialog_is_showing", "permission_dialog_checked_at",
66
+ "interrupted_line_count_while_asking", and once answered "permission_dialog_gone_since"
67
+ and "turn_was_interrupted".
68
+ """
69
+ reading = dict(screen_reading)
70
+ if reading.get("permission_dialog_checked_at", 0) < iterm2_status_change_time: # a new prompt: forget the last one
71
+ for field_name in ("permission_dialog_is_showing", "permission_dialog_gone_since", "turn_was_interrupted"):
72
+ reading.pop(field_name, None)
73
+ reading["interrupted_line_count_while_asking"] = interrupted_line_count
74
+ if dialog_is_showing:
75
+ reading["interrupted_line_count_while_asking"] = interrupted_line_count
76
+ reading.pop("permission_dialog_gone_since", None) # shown again: asking again
77
+ reading["turn_was_interrupted"] = False
78
+ else:
79
+ turn_was_interrupted = interrupted_line_count > reading["interrupted_line_count_while_asking"]
80
+ if reading.get("permission_dialog_is_showing") or turn_was_interrupted:
81
+ reading.setdefault("permission_dialog_gone_since", now)
82
+ reading["turn_was_interrupted"] = turn_was_interrupted
83
+ reading["permission_dialog_is_showing"] = dialog_is_showing
84
+ reading["permission_dialog_checked_at"] = now
85
+ return reading
86
+
87
+
88
+ def permission_dialog_was_answered(state, iterm2_status_change_time, screen_reading):
89
+ """Returns whether an asking session's permission dialog was answered, by a screen check made
90
+ after the status last changed (see update_permission_dialog_reading)."""
91
+ screen_reading = screen_reading or {}
92
+ return (state == "asking" and screen_reading.get("permission_dialog_checked_at", 0) > iterm2_status_change_time
93
+ and not screen_reading.get("permission_dialog_is_showing")
94
+ and "permission_dialog_gone_since" in screen_reading)
95
+
96
+
97
+ def status_values_put_the_agent_in_the_same_state(first_status_value, second_status_value):
98
+ """Returns whether two iTerm2 status values give the same state, idle and done counting as
99
+ one (both wait at the prompt; whether a turn just ended is tracked apart)."""
100
+ def at_prompt_or_state(status_value):
101
+ state = map_iterm2_status_value_to_state(status_value)
102
+ return "at its prompt" if state in STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT else state
103
+ return at_prompt_or_state(first_status_value) == at_prompt_or_state(second_status_value)
104
+
105
+
106
+ def status_change_ends_a_turn(previous_state, new_state):
107
+ """Returns whether iTerm2's status changing from previous_state to new_state (as mapped by
108
+ map_iterm2_status_value_to_state) ends a turn: done, or idle after working or asking (Codex
109
+ reports only idle when its turn ends)."""
110
+ return new_state == "done" or (new_state == "idle" and previous_state in STATES_OF_A_TURN_UNDER_WAY)
111
+
112
+
113
+ def track_status_value(session_tracking, iterm2_status_value, now, screen_reading=None, ends_no_turn=False):
114
+ """Returns a session's tracking updated for its iTerm2 status value read now.
115
+
116
+ The tracking records when the value last changed, when the current turn started (working
117
+ after anything but working or asking: a permission prompt in between doesn't start a new
118
+ turn, unless it was answered No or Esc, which ended the turn) and when the last turn ended
119
+ (status_change_ends_a_turn). The turn's end is kept when the status changes again, so done
120
+ lasts until the tab is seen. A session first seen as done ended its turn by then.
121
+
122
+ Args:
123
+ session_tracking: The session's tracking so far, or None for a session seen for the
124
+ first time; it is not changed.
125
+ iterm2_status_value: iTerm2's `status` variable for the session's first pane.
126
+ now: The time of the reading.
127
+ screen_reading: The session's screen reading (compute_session_status_from_sources), or
128
+ None: a permission prompt that a check since it appeared found answered No or Esc
129
+ ended the turn, though iTerm2 still says waiting, so working next is the turn the
130
+ next prompt starts (code review, 2026-10-28).
131
+ ends_no_turn: Whether the value replaces one that may belong to no turn at all, so a
132
+ change from working to it records no turn end (Claude Code's own idle over a working
133
+ that iTerm2 set without a turn; code review, 2026-10-28).
134
+
135
+ Returns:
136
+ session_tracking itself when the value is unchanged, else a new dict with "status_value",
137
+ "status_change_time", "last_time_tab_was_seen", and once known "turn_started_at" and
138
+ "last_turn_ended_at".
139
+ """
140
+ new_state = map_iterm2_status_value_to_state(iterm2_status_value)
141
+ if session_tracking is None:
142
+ tracking = {"status_value": iterm2_status_value, "status_change_time": now, "last_time_tab_was_seen": None}
143
+ if status_change_ends_a_turn(None, new_state):
144
+ tracking["last_turn_ended_at"] = now
145
+ return tracking
146
+ if session_tracking["status_value"] == iterm2_status_value:
147
+ return session_tracking
148
+ previous_state = map_iterm2_status_value_to_state(session_tracking["status_value"])
149
+ tracking = dict(session_tracking, status_value=iterm2_status_value, status_change_time=now)
150
+ turn_was_interrupted = (permission_dialog_was_answered(previous_state, session_tracking["status_change_time"], screen_reading)
151
+ and bool(screen_reading.get("turn_was_interrupted")))
152
+ if new_state == "working" and (previous_state not in STATES_OF_A_TURN_UNDER_WAY or turn_was_interrupted):
153
+ tracking["turn_started_at"] = now
154
+ if status_change_ends_a_turn(previous_state, new_state) and not ends_no_turn:
155
+ tracking["last_turn_ended_at"] = now
156
+ return tracking
157
+
158
+
159
+ def compute_session_status_from_sources(iterm2_status_value, iterm2_status_change_time, last_turn_ended_at,
160
+ last_time_tab_was_seen, tab_is_seen_now, screen_reading, stuck_threshold_seconds,
161
+ now):
162
+ """Returns (state, reason) for one agent session.
163
+
164
+ - "asking" ends when a screen check made after the status changed no longer finds the
165
+ tool's permission dialog: Claude Code reports nothing when a prompt is answered, and
166
+ iTerm2's status stays "waiting" until the approved tool finishes (Phase 0).
167
+ - "stuck" is working with no screen change (progress noise masked) for the threshold while
168
+ running no command of its own: an agent waiting on a long command it started is working.
169
+ - "done" means the last turn ended after the tab was last seen (selected in the key iTerm2
170
+ window while iTerm2 was the active app), whether the status now says done or idle, so it
171
+ lasts until the tab is seen; a turn that ended while the tab was seen counts as idle.
172
+
173
+ Args:
174
+ iterm2_status_value: iTerm2's `status` variable for the session's first pane.
175
+ iterm2_status_change_time: When that value was first observed (seconds since the epoch).
176
+ last_turn_ended_at: When the status last changed in a way that ends a turn
177
+ (status_change_ends_a_turn), or None if it hasn't since the session was first seen;
178
+ track_status_value sets it for a session first seen as done.
179
+ last_time_tab_was_seen: When the tab was last seen, or None if never.
180
+ tab_is_seen_now: Whether the tab is being seen at this moment.
181
+ screen_reading: {"permission_dialog_is_showing": bool, "permission_dialog_checked_at":
182
+ float, "permission_dialog_gone_since": float, "turn_was_interrupted": bool,
183
+ "fingerprint_changed_at": float, "running_command": (name, started at) or None,
184
+ "command_last_seen_running_at": float} (any key may be missing), or None.
185
+ stuck_threshold_seconds: How long a working session may show no screen change.
186
+ now: The current time.
187
+
188
+ Returns:
189
+ A (state, reason) tuple; state is one of STATES_IN_URGENCY_ORDER.
190
+ """
191
+ state = map_iterm2_status_value_to_state(iterm2_status_value)
192
+ screen_reading = screen_reading or {}
193
+ if state is None:
194
+ return "unknown", "no status report"
195
+ working_since = iterm2_status_change_time
196
+ if permission_dialog_was_answered(state, iterm2_status_change_time, screen_reading):
197
+ if screen_reading.get("turn_was_interrupted"):
198
+ # "No" or Esc ends the turn; Claude Code waits for new instructions while iTerm2 still says waiting.
199
+ return "idle", "turn interrupted"
200
+ state = "working"
201
+ working_since = screen_reading["permission_dialog_gone_since"]
202
+ if state == "working":
203
+ if screen_reading.get("running_command"):
204
+ return "working", f"running {screen_reading['running_command'][0]}" # waiting on its command, never stuck
205
+ # Stuck means thinking with nothing new on screen, so the clock also restarts when a command ends.
206
+ quiet_since = max(screen_reading.get("fingerprint_changed_at", working_since), working_since,
207
+ screen_reading.get("command_last_seen_running_at", 0))
208
+ if now - quiet_since >= stuck_threshold_seconds:
209
+ return "stuck", f"thinking with no screen change for {max(1, round((now - quiet_since) / 60))} min"
210
+ return "working", ""
211
+ if state in STATES_OF_AN_AGENT_WAITING_AT_ITS_PROMPT and last_turn_ended_at is not None:
212
+ if tab_is_seen_now or (last_time_tab_was_seen is not None and last_time_tab_was_seen >= last_turn_ended_at):
213
+ return "idle", "turn finished and seen"
214
+ return "done", "turn finished"
215
+ return state, ""
216
+
217
+
218
+ def pick_most_urgent_state(states):
219
+ """Returns the most urgent of the given states, or "unknown" when there are none."""
220
+ ranked_states = [state for state in STATES_IN_URGENCY_ORDER if state in set(states)]
221
+ return ranked_states[0] if ranked_states else "unknown"
222
+
223
+
224
+ def split_agent_sessions_into_pausable_and_resumable(agent_session_entries):
225
+ """Returns (the agent sessions a pause would stop, the paused ones a resume would continue).
226
+ An agent suspended with Ctrl+Z by hand is in both, since a pause still stops the processes
227
+ below it; an agent whose process has exited is in neither."""
228
+ return ([entry for entry in agent_session_entries if entry.status != "exited"
229
+ and not (entry.status == "paused" and entry.is_paused_with_the_processes_below_it)],
230
+ [entry for entry in agent_session_entries if entry.status == "paused"])
231
+
232
+
233
+ def summarize_state_counts_in_urgency_order(states):
234
+ """Returns text such as "1 asking, 2 working" for a window's or hidden group's sessions."""
235
+ return ", ".join(f"{states.count(state)} {state}" for state in STATES_IN_URGENCY_ORDER if state in states)
@@ -0,0 +1,292 @@
1
+ """Settings, stored as JSON in ~/Library/Application Support/agent-command-tab/settings.json.
2
+
3
+ Settings are added here as the features that use them are built. Command paths are resolved
4
+ once, at first run, and saved, because an app started at login gets a minimal PATH, so the
5
+ folders programs are usually installed in are looked in too (USUAL_PROGRAM_FOLDERS).
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import pwd
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import tempfile
15
+
16
+ from agent_command_tab.list_sorting import LIST_SORT_ORDERS # the Sort pop-up's choices
17
+
18
+ SETTINGS_FOLDER = os.path.expanduser("~/Library/Application Support/agent-command-tab")
19
+ # The app's folder before it was renamed from llm-sidebar-dashboard to AgentCommandTab (2026-10-19).
20
+ SETTINGS_FOLDER_OF_THE_OLD_NAME = os.path.expanduser("~/Library/Application Support/llm-sidebar-dashboard")
21
+ SETTINGS_FILE_PATH = os.path.join(SETTINGS_FOLDER, "settings.json")
22
+ # Reading the shell's start-up files can take several seconds (7.7 for one .bash_profile, 2026-10-25)
23
+ SECONDS_TO_WAIT_FOR_THE_LOGIN_SHELL = 20
24
+ # The shells whose syntax the login shell check uses (`-i -l -c` and "$1"); fish, tcsh and csh take
25
+ # other syntax, so they aren't asked (code review, 2026-10-28).
26
+ LOGIN_SHELLS_THAT_CAN_BE_ASKED = frozenset({"bash", "zsh", "sh", "dash", "ksh"})
27
+ # Where programs such as claude and codex are usually installed (Homebrew on Apple silicon and on
28
+ # Intel, Claude Code's installer), which an app started at login has no PATH to: it
29
+ # gets launchd's /usr/bin:/bin:/usr/sbin:/sbin (code review, 2026-10-28).
30
+ USUAL_PROGRAM_FOLDERS = ("/opt/homebrew/bin", "/usr/local/bin", "~/.local/bin")
31
+ ENVIRONMENT_SETTING_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=") # "ANTHROPIC_MODEL=x claude"
32
+
33
+ # How the list is shown (user request, 2026-10-19): popup, the dropdown under the menu bar icon;
34
+ # sidebar, at the edge of the screen (then the icon slides it in); window, a regular window (then
35
+ # the menu bar icon brings it to the front). In the settings pop-up's order (window first until
36
+ # 2026-10-27, user request).
37
+ SHOW_AS_CHOICES = ["popup", "sidebar", "window"]
38
+ # The global shortcut that shows the list from any app (global_shortcut_key_filter; user request,
39
+ # 2026-10-19).
40
+ GLOBAL_SHORTCUT_CHOICES = ["shift_command_tab", "command_fn_tab", "off"]
41
+ # The app's look (user request, 2026-10-27): auto follows macOS's Light or Dark setting.
42
+ APPEARANCE_CHOICES = ["auto", "dark", "light"]
43
+ # The actions that ask "Are you sure?" with a "Remember my choice" checkbox: a Yes with it checked
44
+ # puts the action in actions_that_run_without_asking (user request, 2026-10-27).
45
+ ACTIONS_THAT_ASK_FOR_CONFIRMATION = ["clear", "kill", "close_window"]
46
+ # The windows whose frames ([x, y, width, height]) are saved, with their smallest sizes.
47
+ # The settings window is never narrower than the width its rows are laid out for.
48
+ SMALLEST_WINDOW_SIZES = {"list_window_frame": (250, 200), "settings_window_frame": (540, 240)}
49
+ SIDEBAR_EDGES = ["right", "left"]
50
+ # auto_hide: slides in when the pointer touches the edge; floating: always visible over windows;
51
+ # docked: always visible, and iTerm2 windows on that monitor are kept out of its area.
52
+ SIDEBAR_MODES = ["auto_hide", "floating", "docked"]
53
+ # A tab row's information columns that the settings can show or hide, in their left-to-right
54
+ # order (the tool icon column, right before state, shows by itself when two or more agent tools
55
+ # run). Memory and CPU usage count the agent and every process below it. The state and its
56
+ # duration come first, right after the name, and CPU before memory, since 2026-10-28 (user requests).
57
+ LIST_COLUMNS = ["state", "state_duration", "context_tokens", "created_time", "existence_duration", "cpu_usage", "memory_usage"]
58
+
59
+ DEFAULT_SETTINGS = {
60
+ "show_as": "popup",
61
+ "global_shortcut": "shift_command_tab",
62
+ "appearance": "auto",
63
+ "app_starts_with_iterm2": True, # through a script in iTerm2's AutoLaunch folder, added when the app starts (start_with_iterm2; user request, 2026-10-28)
64
+ # Never shown in the settings window (the user's choice): to be asked again, take an action out of this list in the file.
65
+ "actions_that_run_without_asking": [],
66
+ "list_window_frame": None, # [x, y, width, height] of the "Show as: Window" window, once it has been shown
67
+ "settings_window_frame": None, # the settings window's, once it has been moved or resized (user request, 2026-10-19)
68
+ "list_window_is_always_on_top": False,
69
+ "sidebar_mode": "auto_hide",
70
+ "sidebar_edge": "right", # of the menu-bar monitor
71
+ "sidebar_width": 400,
72
+ # The settings window's Harnesses section: a tool not included is left out of the list and of
73
+ # the menus that start new agent sessions (user request, 2026-10-19).
74
+ "agent_tools": [
75
+ {"agent_tool_name": "Claude Code", "launch_command": "claude", "is_included": True},
76
+ {"agent_tool_name": "Codex", "launch_command": "codex", "is_included": True},
77
+ ],
78
+ "list_sort_order": "manual",
79
+ "list_sort_order_is_reversed": False, # a second click on a sorted column's title (user request, 2026-10-26)
80
+ "shown_columns": ["context_tokens", "state", "state_duration"],
81
+ "idle_tabs_are_hidden": False, # the Hide Idle / Show Idle button at the top of the list (user request, 2026-10-21)
82
+ }
83
+
84
+
85
+ def is_valid_setting_value(name, value):
86
+ """Returns whether a stored value has the right shape for the setting (else the default is used)."""
87
+ default_value = DEFAULT_SETTINGS[name]
88
+ if name == "show_as":
89
+ return value in SHOW_AS_CHOICES
90
+ if name == "global_shortcut":
91
+ return value in GLOBAL_SHORTCUT_CHOICES
92
+ if name == "appearance":
93
+ return value in APPEARANCE_CHOICES
94
+ if name == "actions_that_run_without_asking":
95
+ return isinstance(value, list) and all(action_name in ACTIONS_THAT_ASK_FOR_CONFIRMATION for action_name in value)
96
+ if name in SMALLEST_WINDOW_SIZES:
97
+ smallest_width, smallest_height = SMALLEST_WINDOW_SIZES[name]
98
+ return value is None or (isinstance(value, list) and len(value) == 4
99
+ and all(isinstance(number, (int, float)) and not isinstance(number, bool) for number in value)
100
+ and value[2] >= smallest_width and value[3] >= smallest_height)
101
+ if name == "sidebar_edge":
102
+ return value in SIDEBAR_EDGES
103
+ if name == "sidebar_mode":
104
+ return value in SIDEBAR_MODES
105
+ if name == "list_sort_order":
106
+ return value in LIST_SORT_ORDERS
107
+ if name == "shown_columns":
108
+ return isinstance(value, list) and all(column_name in LIST_COLUMNS for column_name in value)
109
+ if name == "sidebar_width":
110
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and 200 <= value <= 1200
111
+ if name == "agent_tools":
112
+ return (isinstance(value, list) and value
113
+ and all(isinstance(tool, dict) and isinstance(tool.get("agent_tool_name"), str) and tool["agent_tool_name"]
114
+ and isinstance(tool.get("launch_command"), str) and tool["launch_command"].strip()
115
+ and isinstance(tool.get("is_included", True), bool)
116
+ for tool in value))
117
+ return isinstance(value, type(default_value))
118
+
119
+
120
+ def merge_settings_with_defaults(stored_settings):
121
+ """Returns the defaults overlaid with every valid stored value (invalid or unknown values are
122
+ dropped). A file from before "Show as" with the old sidebar checkbox on shows the sidebar."""
123
+ settings = json.loads(json.dumps(DEFAULT_SETTINGS)) # a deep copy
124
+ if isinstance(stored_settings, dict):
125
+ if "show_as" not in stored_settings and stored_settings.get("sidebar_is_on") is True:
126
+ settings["show_as"] = "sidebar"
127
+ for name, value in stored_settings.items():
128
+ if name in DEFAULT_SETTINGS and is_valid_setting_value(name, value):
129
+ settings[name] = value
130
+ # Files from before the Harnesses section have no "is_included": those tools are included.
131
+ settings["agent_tools"] = [dict({"is_included": True}, **agent_tool) for agent_tool in settings["agent_tools"]]
132
+ return settings
133
+
134
+
135
+ def list_included_agent_tool_names(settings):
136
+ """Returns the agent tools that the Harnesses section includes, in their settings order."""
137
+ return [agent_tool["agent_tool_name"] for agent_tool in settings["agent_tools"] if agent_tool["is_included"]]
138
+
139
+
140
+ def list_left_out_agent_tool_names(settings):
141
+ """Returns the agent tools that the Harnesses section leaves out of the list and the menus."""
142
+ return [agent_tool["agent_tool_name"] for agent_tool in settings["agent_tools"] if not agent_tool["is_included"]]
143
+
144
+
145
+ def replace_agent_tool_field(agent_tools, tool_index, field_name, value):
146
+ """Returns a copy of the agent_tools setting with one tool's field (such as "launch_command"
147
+ or "is_included") set to value; the settings it came from are not changed."""
148
+ return [dict(agent_tool, **{field_name: value}) if index == tool_index else dict(agent_tool)
149
+ for index, agent_tool in enumerate(agent_tools)]
150
+
151
+
152
+ def find_program_on_path_or_in_the_usual_folders(program_name):
153
+ """Returns the full path of a program found on PATH, else in USUAL_PROGRAM_FOLDERS, or None."""
154
+ return shutil.which(program_name) or shutil.which(
155
+ program_name, path=os.pathsep.join(os.path.expanduser(folder) for folder in USUAL_PROGRAM_FOLDERS))
156
+
157
+
158
+ def find_codex_command_path(settings, find_command_path=find_program_on_path_or_in_the_usual_folders):
159
+ """Returns the codex program that "Talk to Each Other" runs `codex queue` with: the first word
160
+ of the Codex tool's launch command (resolved to a full path at first run), looked up on PATH
161
+ and in the usual folders when it is a bare name, or None when it isn't found. A launch
162
+ command that starts with another program (a wrapper) gives the codex found that way."""
163
+ launch_command = next((agent_tool["launch_command"] for agent_tool in settings["agent_tools"]
164
+ if agent_tool["agent_tool_name"] == "Codex"), "")
165
+ first_word = os.path.expanduser((launch_command.split() or [""])[0]) # "~/bin/codex" too, as Settings accepts
166
+ if os.path.basename(first_word) != "codex":
167
+ first_word = "codex"
168
+ return first_word if os.path.isabs(first_word) else find_command_path(first_word)
169
+
170
+
171
+ def build_core_settings(settings, find_command_path=find_program_on_path_or_in_the_usual_folders):
172
+ """Returns the part of the settings that the core uses: the agent tools left out of the
173
+ list, whether memory and CPU use are read (only while one of their columns is shown or the
174
+ list is sorted by one of them), and the codex program for `codex queue`
175
+ (find_codex_command_path)."""
176
+ return {
177
+ "left_out_agent_tool_names": list_left_out_agent_tool_names(settings),
178
+ "resource_usage_is_read": bool({"memory_usage", "cpu_usage"} & {*settings["shown_columns"], settings["list_sort_order"]}),
179
+ "codex_command_path": find_codex_command_path(settings, find_command_path),
180
+ }
181
+
182
+
183
+ def load_settings(settings_file_path=SETTINGS_FILE_PATH):
184
+ """Returns the saved settings merged with the defaults; a missing or unreadable file gives the defaults."""
185
+ try:
186
+ with open(settings_file_path) as settings_file:
187
+ stored_settings = json.load(settings_file)
188
+ except FileNotFoundError:
189
+ stored_settings = {}
190
+ except (OSError, ValueError) as error:
191
+ print(f"settings file {settings_file_path} could not be read ({error}); using defaults")
192
+ stored_settings = {}
193
+ return merge_settings_with_defaults(stored_settings)
194
+
195
+
196
+ def write_json_file_atomically(data, file_path):
197
+ """Writes data as JSON to a temporary file that then replaces file_path, so a crash never leaves half a file."""
198
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
199
+ file_descriptor, temporary_path = tempfile.mkstemp(dir=os.path.dirname(file_path), suffix=".tmp")
200
+ with os.fdopen(file_descriptor, "w") as temporary_file:
201
+ json.dump(data, temporary_file, indent=1)
202
+ os.replace(temporary_path, file_path)
203
+
204
+
205
+ def save_settings(settings, settings_file_path=SETTINGS_FILE_PATH):
206
+ """Writes the settings atomically."""
207
+ write_json_file_atomically(settings, settings_file_path)
208
+
209
+
210
+ def resolve_launch_command_paths(settings, find_command_path=find_program_on_path_or_in_the_usual_folders):
211
+ """Returns settings whose bare launch commands ("claude") are replaced by full paths found on
212
+ PATH or in the usual folders.
213
+
214
+ Only the first word is resolved, and only when it is a bare name that is found, so a
215
+ command the user typed with a path or extra arguments is kept as written.
216
+ """
217
+ resolved_settings = dict(settings)
218
+ resolved_settings["agent_tools"] = []
219
+ for agent_tool in settings["agent_tools"]:
220
+ words = agent_tool["launch_command"].split(" ", 1)
221
+ if "/" not in words[0]:
222
+ full_path = find_command_path(words[0])
223
+ if full_path:
224
+ words[0] = full_path
225
+ resolved_settings["agent_tools"].append(dict(agent_tool, launch_command=" ".join(words)))
226
+ return resolved_settings
227
+
228
+
229
+ def ask_the_login_shell_whether_it_knows_command(command_name):
230
+ """Returns True if the user's login shell knows command_name as an alias, function, builtin or
231
+ program, False if it doesn't, and None if the shell couldn't be asked or didn't answer in time.
232
+ New agent sessions start by typing the launch command into that shell, so an alias such as
233
+ `yc` works there although it is on no PATH. Takes a moment (it reads the shell's start-up
234
+ files), so the settings window calls it off the main thread. A shell not in
235
+ LOGIN_SHELLS_THAT_CAN_BE_ASKED (fish, tcsh) isn't asked."""
236
+ shell = os.environ.get("SHELL") or pwd.getpwuid(os.getuid()).pw_shell or "/bin/zsh"
237
+ if os.path.basename(shell) not in LOGIN_SHELLS_THAT_CAN_BE_ASKED:
238
+ return None
239
+ try:
240
+ completed_process = subprocess.run(
241
+ [shell, "-i", "-l", "-c", 'command -v -- "$1" > /dev/null', shell, command_name],
242
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
243
+ timeout=SECONDS_TO_WAIT_FOR_THE_LOGIN_SHELL)
244
+ except (OSError, subprocess.TimeoutExpired):
245
+ return None
246
+ return completed_process.returncode == 0
247
+
248
+
249
+ def find_launch_command_problem(launch_command, find_command_path=find_program_on_path_or_in_the_usual_folders,
250
+ ask_the_login_shell=ask_the_login_shell_whether_it_knows_command):
251
+ """Returns "" when the launch command's program can be run, else a short explanation.
252
+
253
+ Leading NAME=value words (environment settings) are skipped. A path must be an executable
254
+ file; a bare name must be on PATH or known to the login shell (such as an alias). A program
255
+ written with a shell variable or quotes ("$HOME/bin/claude") can't be checked without running
256
+ the shell's expansion, and a name the login shell didn't answer about in time may well be an
257
+ alias, so both count as fine.
258
+ """
259
+ words = launch_command.split()
260
+ while words and ENVIRONMENT_SETTING_PATTERN.match(words[0]):
261
+ words = words[1:]
262
+ if not words:
263
+ return "No command"
264
+ if any(character in words[0] for character in "$`'\""):
265
+ return ""
266
+ first_word = os.path.expanduser(words[0])
267
+ if "/" in first_word:
268
+ if not os.path.isfile(first_word):
269
+ return f"{words[0]} doesn't exist"
270
+ if not os.access(first_word, os.X_OK):
271
+ return f"{words[0]} can't be run (it isn't executable)"
272
+ return ""
273
+ if find_command_path(first_word) or ask_the_login_shell(first_word) is not False:
274
+ return ""
275
+ return f"{first_word}: command not found (not on PATH, and not an alias or function in your shell)"
276
+
277
+
278
+ def move_the_settings_folder_of_the_old_name(old_folder=SETTINGS_FOLDER_OF_THE_OLD_NAME, new_folder=SETTINGS_FOLDER):
279
+ """Moves the folder the app kept its settings and docked window frames in under its old name
280
+ to the new one, once: only while the old one exists and the new one doesn't yet."""
281
+ if os.path.isdir(old_folder) and not os.path.exists(new_folder):
282
+ os.rename(old_folder, new_folder)
283
+
284
+
285
+ def load_settings_resolving_paths_at_first_run(settings_file_path=SETTINGS_FILE_PATH):
286
+ """Returns the settings; at first run (no file yet) resolves the launch commands' paths and saves them."""
287
+ is_first_run = not os.path.exists(settings_file_path)
288
+ settings = load_settings(settings_file_path)
289
+ if is_first_run:
290
+ settings = resolve_launch_command_paths(settings)
291
+ save_settings(settings, settings_file_path)
292
+ return settings