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,300 @@
1
+ """The app's own hooks in Claude Code's and Codex's settings:
2
+ installing, removing and checking them (user request, 2026-10-27).
3
+
4
+ Each hook runs hook_event_forwarder.py, which sends the event to the app. The events tell the
5
+ app when an agent's session ended normally (so a crash leaves an "exited" row), and
6
+ Claude Code's background shells and agents (the lights after a tab's name). The entries
7
+ are the app's by their command, which names hook_event_forwarder.py, so installing again
8
+ replaces them and removing takes out only them. Each file the installer changes is copied first
9
+ to <file>.agent-command-tab-backup.
10
+
11
+ - Claude Code: settings.json in each config folder in use (claude_code.list_claude_config_folders,
12
+ so a Claude Code started with CLAUDE_CONFIG_DIR=~/.claude_work gets them too). A session
13
+ reads its hooks when it starts, so only sessions started afterwards report.
14
+ - Codex: hooks.json in its home folder. Codex runs a new hook only once the user approves it in
15
+ its /hooks screen, which records the approval in config.toml under
16
+ [hooks.state."<hooks.json path>:<event>:<group>:<hook>"], with a hash of
17
+ the hook as it was then, so a changed hook needs approving again (compute_codex_approval_hash).
18
+ """
19
+
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import re
24
+ import shlex
25
+ import shutil
26
+ import tempfile
27
+
28
+ from agent_command_tab.agent_adapters.claude_code import list_claude_config_folders
29
+ from agent_command_tab.installed_copy_paths import find_python_of_this_copy, replace_homebrew_version_folder_with_its_stable_link
30
+
31
+ FORWARDER_FILE_NAME = "hook_event_forwarder.py"
32
+ FORWARDER_FILE_PATH = replace_homebrew_version_folder_with_its_stable_link(
33
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), FORWARDER_FILE_NAME))
34
+ SECONDS_A_HOOK_MAY_RUN = 10
35
+ BACKUP_FILE_SUFFIX = ".agent-command-tab-backup"
36
+ # The events each agent tool's hooks report, each with the tools a PreToolUse or PostToolUse
37
+ # entry is limited to (Claude Code's background shells and agents start from Bash and Agent tool
38
+ # calls; Task is the Agent tool's older name), so other tool calls start no forwarder. Claude
39
+ # Code's prompts and turn ends tell when a turn ended while iTerm2's status still says working, as
40
+ # its Claude Code integration keeps it while a background task runs, and the main agent's tool
41
+ # calls after a Stop that another Stop hook blocked tell that the turn goes on, from the start of
42
+ # its first command (PreToolUse; code review, 2026-10-28;
43
+ # hook_event_tracking.find_when_the_hooks_ended_the_turn).
44
+ HOOK_EVENTS_BY_AGENT_TOOL_NAME = {
45
+ "Claude Code": [("SessionStart", None), ("UserPromptSubmit", None), ("Stop", None), ("SubagentStop", None),
46
+ ("SessionEnd", None), ("PreToolUse", "Bash|Agent|Task"), ("PostToolUse", "Bash|Agent|Task")],
47
+ "Codex": [("SessionStart", None), ("Stop", None), ("SessionEnd", None)],
48
+ }
49
+ # Codex's /hooks screen shows a hook's statusMessage as its name, "Unnamed hook" without one, and
50
+ # its status line shows it while the hook runs (user request, 2026-10-27). Claude Code's hooks have
51
+ # no names (its statusMessage is only spinner text), so its entries go without.
52
+ HOOK_NAMES_BY_AGENT_TOOL_NAME = {"Codex": "Report to AgentCommandTab"}
53
+ CODEX_SESSION_END_LONGEST_TIMEOUT = 3 # seconds: Codex lowers a longer SessionEnd hook timeout to this
54
+ HOOKS_ARE_INSTALLED = "installed"
55
+ HOOKS_ARE_MISSING = "missing"
56
+ HOOKS_AWAIT_APPROVAL = "needs approval" # Codex: in hooks.json, not yet approved in its /hooks screen
57
+
58
+
59
+ def build_forwarder_command(agent_tool_name, python_path=None, forwarder_path=FORWARDER_FILE_PATH):
60
+ """Returns the hook command: this Python (python_path, or the one running), isolated (-I) and
61
+ without site packages (-S), running the forwarder. The running Python is named by a path that
62
+ survives upgrades (installed_copy_paths.find_python_of_this_copy: a venv's bin/python), and a
63
+ Python in a Homebrew version folder by its stable opt/ path, as FORWARDER_FILE_PATH is, so the
64
+ hooks keep working after `brew upgrade` or a venv made again with a newer Python."""
65
+ python_path = replace_homebrew_version_folder_with_its_stable_link(python_path) if python_path else find_python_of_this_copy()
66
+ parts = (python_path, "-I", "-S", forwarder_path, agent_tool_name)
67
+ return " ".join(shlex.quote(part) for part in parts)
68
+
69
+
70
+ def hook_group_is_the_apps(hook_group):
71
+ """Whether a hooks entry ({"matcher": ..., "hooks": [{"type": "command", "command": ...}]}) runs the forwarder."""
72
+ return isinstance(hook_group, dict) and isinstance(hook_group.get("hooks"), list) and any(
73
+ isinstance(hook, dict) and FORWARDER_FILE_NAME in str(hook.get("command", "")) for hook in hook_group["hooks"])
74
+
75
+
76
+ def remove_the_apps_hooks(settings):
77
+ """Returns the settings without the app's hook entries; an event left without entries is
78
+ left out, and so is "hooks" when only the app's entries were in it."""
79
+ hooks = settings.get("hooks")
80
+ if not isinstance(hooks, dict):
81
+ return dict(settings)
82
+ kept_hooks = {}
83
+ for event_name, hook_groups in hooks.items():
84
+ if not isinstance(hook_groups, list):
85
+ kept_hooks[event_name] = hook_groups
86
+ continue
87
+ kept_hook_groups = [hook_group for hook_group in hook_groups if not hook_group_is_the_apps(hook_group)]
88
+ if kept_hook_groups or not hook_groups:
89
+ kept_hooks[event_name] = kept_hook_groups
90
+ if not kept_hooks and hooks:
91
+ return {name: value for name, value in settings.items() if name != "hooks"}
92
+ return dict(settings, hooks=kept_hooks)
93
+
94
+
95
+ def build_the_apps_hook_group(command, matcher, hook_name=None):
96
+ hook = {"type": "command", "command": command, "async": True, "timeout": SECONDS_A_HOOK_MAY_RUN}
97
+ return dict({"matcher": matcher} if matcher else {},
98
+ hooks=[dict(hook, statusMessage=hook_name) if hook_name else hook])
99
+
100
+
101
+ def add_the_apps_hooks(settings, command, events, hook_name=None):
102
+ """Returns the settings with one entry of the app's per event, after the user's own, in place
103
+ of any the app added before (with another command, other events or another name).
104
+
105
+ Args:
106
+ settings: The settings file's contents.
107
+ command: build_forwarder_command's command.
108
+ events: [(event name, matcher or None)], from HOOK_EVENTS_BY_AGENT_TOOL_NAME.
109
+ hook_name: From HOOK_NAMES_BY_AGENT_TOOL_NAME, or None for unnamed entries.
110
+ """
111
+ settings = remove_the_apps_hooks(settings)
112
+ hooks = dict(settings.get("hooks") or {})
113
+ for event_name, matcher in events:
114
+ hooks[event_name] = list(hooks.get(event_name) or []) + [build_the_apps_hook_group(command, matcher, hook_name)]
115
+ return dict(settings, hooks=hooks)
116
+
117
+
118
+ def normalize_forwarder_command(command):
119
+ """Returns a hook command's words with its program as the file it leads to, so the venv's
120
+ python, python3 and python3.11 (links to one program) give the same command; None for a
121
+ command that can't be split. The forwarder runs without site packages (-S), so which of
122
+ those links started it makes no difference."""
123
+ try:
124
+ words = shlex.split(command)
125
+ except ValueError:
126
+ return None
127
+ return [os.path.realpath(words[0])] + words[1:] if words else None
128
+
129
+
130
+ def hook_group_is_the_same_as(hook_group, expected_hook_group):
131
+ """Whether a hooks entry is the one add_the_apps_hooks adds (expected_hook_group), its command
132
+ perhaps naming the same Python by another link (normalize_forwarder_command): the app's entry
133
+ point runs as python3.11, `python -m agent_command_tab.command_line` as python."""
134
+ if not (isinstance(hook_group, dict) and isinstance(hook_group.get("hooks"), list) and len(hook_group["hooks"]) == 1
135
+ and isinstance(hook_group["hooks"][0], dict)):
136
+ return False
137
+ hook, expected_hook = hook_group["hooks"][0], expected_hook_group["hooks"][0]
138
+ return (dict(hook_group, hooks=None) == dict(expected_hook_group, hooks=None)
139
+ and dict(hook, command=None) == dict(expected_hook, command=None)
140
+ and normalize_forwarder_command(str(hook.get("command", ""))) == normalize_forwarder_command(expected_hook["command"]))
141
+
142
+
143
+ def list_positions_of_the_apps_hooks(settings, command, events, hook_name=None):
144
+ """Returns [(event name, entry index, hook index)] of the app's hook for each event, or None
145
+ unless every event has the entry add_the_apps_hooks adds (hook_group_is_the_same_as)."""
146
+ hooks = settings.get("hooks") if isinstance(settings.get("hooks"), dict) else {}
147
+ positions = []
148
+ for event_name, matcher in events:
149
+ hook_groups = hooks.get(event_name) if isinstance(hooks.get(event_name), list) else []
150
+ group_indexes = [index for index, hook_group in enumerate(hook_groups)
151
+ if hook_group_is_the_same_as(hook_group, build_the_apps_hook_group(command, matcher, hook_name))]
152
+ if not group_indexes:
153
+ return None
154
+ positions.append((event_name, group_indexes[0], 0))
155
+ return positions
156
+
157
+
158
+ def convert_event_name_to_codex_hook_state_name(event_name):
159
+ """Returns the name Codex's config.toml gives an event in its hook approvals ("SessionEnd" -> "session_end")."""
160
+ return re.sub(r"(?<!^)(?=[A-Z])", "_", event_name).lower()
161
+
162
+
163
+ def compute_codex_approval_hash(event_name, hook_group):
164
+ """Returns the trusted_hash Codex records in config.toml when the user approves the hook in an
165
+ entry of the app's (hook_hash in Codex's codex-rs/hooks/src/engine/discovery.rs): SHA-256 of
166
+ the event's name and the entry, as JSON with sorted keys and no spaces. Of the changes Codex
167
+ makes to an entry before hashing it, only one touches the app's: a SessionEnd hook's timeout
168
+ is lowered to CODEX_SESSION_END_LONGEST_TIMEOUT."""
169
+ hook = dict(hook_group["hooks"][0])
170
+ if event_name == "SessionEnd":
171
+ hook["timeout"] = min(hook["timeout"], CODEX_SESSION_END_LONGEST_TIMEOUT)
172
+ identity = dict(hook_group, event_name=convert_event_name_to_codex_hook_state_name(event_name), hooks=[hook])
173
+ return "sha256:" + hashlib.sha256(
174
+ json.dumps(identity, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()
175
+
176
+
177
+ def codex_has_approved_the_hooks(config_text, hooks_file_path, settings, positions):
178
+ """Whether Codex's config.toml records an approval of the hook at each position
179
+ (list_positions_of_the_apps_hooks) as it is in the settings now. An approval of an earlier
180
+ version, such as one without its name, doesn't count: Codex skips the changed hook until the
181
+ user approves it again."""
182
+ for event_name, group_index, hook_index in positions:
183
+ state_name = f"{hooks_file_path}:{convert_event_name_to_codex_hook_state_name(event_name)}:{group_index}:{hook_index}"
184
+ state_section = re.search(rf'^\[hooks\.state\."{re.escape(state_name)}"\]$(.*?)(?=^\[|\Z)', config_text,
185
+ re.MULTILINE | re.DOTALL)
186
+ trusted_hash_line = f'trusted_hash = "{compute_codex_approval_hash(event_name, settings["hooks"][event_name][group_index])}"'
187
+ if state_section is None or trusted_hash_line not in state_section.group(1):
188
+ return False
189
+ return True
190
+
191
+
192
+ def find_codex_home_folder():
193
+ return os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
194
+
195
+
196
+ def list_settings_file_paths(agent_tool_name):
197
+ """Returns the files that hold the agent tool's hooks, in folders that exist (a tool that
198
+ isn't installed has none)."""
199
+ if agent_tool_name == "Claude Code":
200
+ folders = [folder or os.path.expanduser("~/.claude") for folder in list_claude_config_folders()]
201
+ return [os.path.join(folder, "settings.json") for folder in folders if os.path.isdir(folder)]
202
+ codex_home_folder = find_codex_home_folder()
203
+ return [os.path.join(codex_home_folder, "hooks.json")] if os.path.isdir(codex_home_folder) else []
204
+
205
+
206
+ def read_settings_file(file_path):
207
+ """Returns a settings file's contents ({} when it doesn't exist yet).
208
+
209
+ Raises:
210
+ ValueError: It isn't a JSON object, so changing it could lose the user's settings.
211
+ """
212
+ if not os.path.exists(file_path):
213
+ return {}
214
+ with open(file_path) as settings_file:
215
+ settings = json.load(settings_file)
216
+ if not isinstance(settings, dict):
217
+ raise ValueError(f"{file_path} doesn't hold a JSON object")
218
+ return settings
219
+
220
+
221
+ def write_settings_file(settings, file_path):
222
+ """Copies the file to its backup, then replaces it at once with the new contents, keeping its
223
+ permissions. A symlink (a dotfiles manager's) stays: the file it points to is the one replaced."""
224
+ file_path = os.path.realpath(file_path)
225
+ mode = 0o644
226
+ if os.path.exists(file_path):
227
+ shutil.copy2(file_path, file_path + BACKUP_FILE_SUFFIX)
228
+ mode = os.stat(file_path).st_mode & 0o777
229
+ file_descriptor, temporary_path = tempfile.mkstemp(dir=os.path.dirname(file_path), suffix=".tmp")
230
+ with os.fdopen(file_descriptor, "w") as temporary_file:
231
+ json.dump(settings, temporary_file, indent=2, ensure_ascii=False)
232
+ temporary_file.write("\n")
233
+ os.chmod(temporary_path, mode)
234
+ os.replace(temporary_path, file_path)
235
+
236
+
237
+ def install_hooks(agent_tool_name):
238
+ """Adds the app's hooks to the agent tool's settings files; returns the files changed. A file
239
+ that has them already (perhaps naming the same Python by another link) is left as it is, so
240
+ Codex's approval of them stays.
241
+
242
+ Raises:
243
+ OSError, ValueError: A file couldn't be read or written; files changed before it stay changed.
244
+ """
245
+ command = build_forwarder_command(agent_tool_name)
246
+ events = HOOK_EVENTS_BY_AGENT_TOOL_NAME[agent_tool_name]
247
+ hook_name = HOOK_NAMES_BY_AGENT_TOOL_NAME.get(agent_tool_name)
248
+ changed_file_paths = []
249
+ for file_path in list_settings_file_paths(agent_tool_name):
250
+ settings = read_settings_file(file_path)
251
+ if list_positions_of_the_apps_hooks(settings, command, events, hook_name) is not None:
252
+ continue
253
+ new_settings = add_the_apps_hooks(settings, command, events, hook_name)
254
+ if new_settings != settings:
255
+ write_settings_file(new_settings, file_path)
256
+ changed_file_paths.append(file_path)
257
+ return changed_file_paths
258
+
259
+
260
+ def remove_hooks(agent_tool_name):
261
+ """Takes the app's hooks out of the agent tool's settings files; returns the files changed."""
262
+ changed_file_paths = []
263
+ for file_path in list_settings_file_paths(agent_tool_name):
264
+ settings = read_settings_file(file_path)
265
+ new_settings = remove_the_apps_hooks(settings)
266
+ if new_settings != settings:
267
+ write_settings_file(new_settings, file_path)
268
+ changed_file_paths.append(file_path)
269
+ return changed_file_paths
270
+
271
+
272
+ def check_hooks(agent_tool_name):
273
+ """Returns HOOKS_ARE_INSTALLED when every settings file of the agent tool has the app's
274
+ hooks with this app's command (and, for Codex, they are approved), HOOKS_AWAIT_APPROVAL for
275
+ Codex hooks not yet approved, and HOOKS_ARE_MISSING otherwise (also when no file can be read)."""
276
+ command = build_forwarder_command(agent_tool_name)
277
+ events = HOOK_EVENTS_BY_AGENT_TOOL_NAME[agent_tool_name]
278
+ file_paths = list_settings_file_paths(agent_tool_name)
279
+ settings_and_positions_by_file_path = {}
280
+ for file_path in file_paths:
281
+ try:
282
+ settings = read_settings_file(file_path)
283
+ except (OSError, ValueError):
284
+ return HOOKS_ARE_MISSING
285
+ positions = list_positions_of_the_apps_hooks(settings, command, events, HOOK_NAMES_BY_AGENT_TOOL_NAME.get(agent_tool_name))
286
+ if positions is None:
287
+ return HOOKS_ARE_MISSING
288
+ settings_and_positions_by_file_path[file_path] = (settings, positions)
289
+ if not file_paths:
290
+ return HOOKS_ARE_MISSING
291
+ if agent_tool_name == "Codex":
292
+ try:
293
+ with open(os.path.join(find_codex_home_folder(), "config.toml")) as config_file:
294
+ config_text = config_file.read()
295
+ except OSError:
296
+ config_text = ""
297
+ if not all(codex_has_approved_the_hooks(config_text, file_path, settings, positions)
298
+ for file_path, (settings, positions) in settings_and_positions_by_file_path.items()):
299
+ return HOOKS_AWAIT_APPROVAL
300
+ return HOOKS_ARE_INSTALLED
@@ -0,0 +1,41 @@
1
+ """Paths to this installed copy of the app that other programs keep and run later (the hooks in Claude
2
+ Code's and Codex's settings, the script in iTerm2's AutoLaunch folder that starts the app), chosen to
3
+ survive upgrades."""
4
+
5
+ import os
6
+ import re
7
+ import sys
8
+
9
+ # A Homebrew install's files are in a folder named after its version (<prefix>/Cellar/<name>/<version>),
10
+ # which `brew upgrade` deletes; <prefix>/opt/<name> always leads to the installed version.
11
+ HOMEBREW_VERSION_FOLDER_PATTERN = re.compile(r"^(.*)/Cellar/([^/]+)/[^/]+/(.*)$")
12
+
13
+
14
+ def replace_homebrew_version_folder_with_its_stable_link(path, path_exists=os.path.exists):
15
+ """Returns path with a Homebrew version folder (<prefix>/Cellar/<name>/<version>/) replaced by
16
+ <prefix>/opt/<name>/, so that a hook or AutoLaunch script naming it keeps working after an upgrade
17
+ (user request, 2026-10-28). Other paths, and one whose opt/ counterpart doesn't exist, are
18
+ returned as they are."""
19
+ match = HOMEBREW_VERSION_FOLDER_PATTERN.match(path)
20
+ if not match:
21
+ return path
22
+ stable_path = f"{match.group(1)}/opt/{match.group(2)}/{match.group(3)}"
23
+ return stable_path if path_exists(stable_path) else path
24
+
25
+
26
+ def find_python_of_this_copy(executable_path=None, prefix=None, base_prefix=None, path_exists=os.path.exists):
27
+ """Returns the Python running the app, by a path that survives upgrades: in a virtual environment
28
+ (pip, pipx, Homebrew), its bin/python, which every one has whatever Python version made it (a
29
+ venv made again with Python 3.13 has no bin/python3.11, which the hooks named until 2026-10-28,
30
+ user request); otherwise sys.executable. Either way, a Homebrew version folder becomes its opt/
31
+ link (replace_homebrew_version_folder_with_its_stable_link).
32
+
33
+ Args:
34
+ executable_path, prefix, base_prefix: sys.executable, sys.prefix and sys.base_prefix when None.
35
+ path_exists: os.path.exists, or a stand-in for tests.
36
+ """
37
+ executable_path = executable_path or sys.executable
38
+ prefix = prefix or sys.prefix
39
+ if prefix != (base_prefix or sys.base_prefix) and path_exists(os.path.join(prefix, "bin", "python")):
40
+ executable_path = os.path.join(prefix, "bin", "python")
41
+ return replace_homebrew_version_folder_with_its_stable_link(executable_path, path_exists)
@@ -0,0 +1,325 @@
1
+ """Actions that change iTerm2: focus, rename, tab moves, new agent sessions, typed slash commands
2
+ and pasted messages.
3
+
4
+ Each function takes the connection's iterm2.App and returns an ActionResult. After any action
5
+ the core re-reads iTerm2 and publishes a new snapshot; the views never guess the result.
6
+ """
7
+
8
+ import asyncio
9
+ import os
10
+
11
+ import iterm2
12
+
13
+ from agent_command_tab.dashboard_core_api import ActionResult
14
+ from agent_command_tab.monitor_assignment import (assign_windows_to_monitors_by_largest_overlap,
15
+ compute_window_frame_on_another_monitor)
16
+ from agent_command_tab.screen_readings import count_lines_matching, input_area_is_empty, read_typed_input_area_text
17
+ from agent_command_tab.tab_order_computation import compute_full_tab_order_after_move
18
+
19
+ SECONDS_FOR_FULL_SCREEN_ANIMATION = 1.0
20
+ SECONDS_BEFORE_CHECKING_THAT_A_COMMAND_WAS_SUBMITTED = 0.5 # the box empties within a redraw of the Enter
21
+ # A bracketed paste: the agent takes the text between these as one paste, newlines included,
22
+ # rather than as typed keys (where a newline would be Enter).
23
+ BRACKETED_PASTE_START = "\x1b[200~"
24
+ BRACKETED_PASTE_END = "\x1b[201~"
25
+ SECONDS_BETWEEN_A_PASTE_AND_ITS_ENTER = 0.5 # the pause of the live check (2026-10-21)
26
+
27
+
28
+ def escape_text_for_iterm2_interpolated_string(text):
29
+ """Returns text with backslashes doubled, since iTerm2 reads titles as interpolated strings
30
+ (where a backslash starts an expression such as \\(session.name))."""
31
+ return text.replace("\\", "\\\\")
32
+
33
+
34
+ async def focus_agent_session(app, session_id):
35
+ """Brings the session's window and tab to the front, without raising iTerm2's other windows.
36
+
37
+ Args:
38
+ app: The iterm2.App.
39
+ session_id: The tab's first session.
40
+ """
41
+ session = app.get_session_by_id(session_id)
42
+ if session is None:
43
+ return ActionResult(False, "that tab no longer exists")
44
+ await session.async_activate(select_tab=True, order_window_front=True)
45
+ await app.async_activate(raise_all_windows=False)
46
+ return ActionResult(True)
47
+
48
+
49
+ async def focus_window(app, window_id):
50
+ """Brings a window to the front with the tab it already shows (which may run no agent),
51
+ without raising iTerm2's other windows."""
52
+ window = app.get_window_by_id(window_id)
53
+ if window is None:
54
+ return ActionResult(False, "that window no longer exists")
55
+ await window.async_activate()
56
+ await app.async_activate(raise_all_windows=False)
57
+ return ActionResult(True)
58
+
59
+
60
+ async def put_back_tabs_and_window_after_peek(app, selected_tab_id_by_window_id, window_id_to_bring_back):
61
+ """Undoes a peek (pressing and holding a tab row): each window gets back the tab it had
62
+ selected, and, when iTerm2 was in front before, its front window comes back to the front.
63
+
64
+ Args:
65
+ app: The iterm2.App.
66
+ selected_tab_id_by_window_id: {window ID: selected tab ID} from before the peek.
67
+ window_id_to_bring_back: The window that was in front before, or None when another app was.
68
+ """
69
+ for window in app.terminal_windows:
70
+ tab_id_before = selected_tab_id_by_window_id.get(window.window_id)
71
+ if tab_id_before and window.current_tab is not None and window.current_tab.tab_id != tab_id_before:
72
+ tab_before = app.get_tab_by_id(tab_id_before)
73
+ if tab_before is not None:
74
+ await tab_before.async_select(order_window_front=False)
75
+ window_to_bring_back = app.get_window_by_id(window_id_to_bring_back) if window_id_to_bring_back else None
76
+ if window_to_bring_back is not None:
77
+ await window_to_bring_back.async_activate()
78
+ return ActionResult(True)
79
+
80
+
81
+ async def rename_tab(app, tab_id, new_title):
82
+ """Sets a tab's title as iTerm2's Edit Tab Title does; an empty title restores the default name."""
83
+ tab = app.get_tab_by_id(tab_id)
84
+ if tab is None:
85
+ return ActionResult(False, "that tab no longer exists")
86
+ await tab.async_set_title(escape_text_for_iterm2_interpolated_string(new_title.strip()))
87
+ return ActionResult(True)
88
+
89
+
90
+ async def rename_window(app, window_id, new_title):
91
+ """Sets a window's title as iTerm2's Edit Window Title does; an empty title restores the default name."""
92
+ window = app.get_window_by_id(window_id)
93
+ if window is None:
94
+ return ActionResult(False, "that window no longer exists")
95
+ await window.async_set_title(escape_text_for_iterm2_interpolated_string(new_title.strip()))
96
+ return ActionResult(True)
97
+
98
+
99
+ async def close_window(app, window_id):
100
+ """Closes a window and ends the programs in its tabs. The dashboard has already asked the
101
+ user, so iTerm2 is told not to ask again."""
102
+ window = app.get_window_by_id(window_id)
103
+ if window is None:
104
+ return ActionResult(False, "that window no longer exists")
105
+ await window.async_close(force=True)
106
+ return ActionResult(True)
107
+
108
+
109
+ async def move_tab_to_window_position(app, tab_id, target_window_id, drop_before_tab_id):
110
+ """Moves a tab within its window or into another window, keeping its program running.
111
+
112
+ Args:
113
+ app: The iterm2.App.
114
+ tab_id: The dragged tab.
115
+ target_window_id: The window it was dropped into (its own window for a reorder).
116
+ drop_before_tab_id: The listed tab it was dropped before, or None for after the last tab.
117
+ """
118
+ tab = app.get_tab_by_id(tab_id)
119
+ target_window = app.get_window_by_id(target_window_id)
120
+ if tab is None or target_window is None:
121
+ return ActionResult(False, "that tab or window no longer exists")
122
+ tabs_by_tab_id = {target_tab.tab_id: target_tab for target_tab in target_window.tabs}
123
+ tabs_by_tab_id[tab_id] = tab
124
+ new_tab_order = compute_full_tab_order_after_move([target_tab.tab_id for target_tab in target_window.tabs],
125
+ tab_id, drop_before_tab_id)
126
+ await target_window.async_set_tabs([tabs_by_tab_id[ordered_tab_id] for ordered_tab_id in new_tab_order])
127
+ return ActionResult(True)
128
+
129
+
130
+ async def move_window_to_monitor(app, window_id, monitors, target_monitor_id):
131
+ """Moves a window to another monitor, keeping its size if it fits and its relative position.
132
+
133
+ A full-screen window can't simply get a new frame, so it leaves full screen, moves, and
134
+ enters full screen again on the target monitor (not yet tried on a real
135
+ second monitor).
136
+
137
+ Args:
138
+ app: The iterm2.App.
139
+ window_id: The window to move.
140
+ monitors: Monitor dicts with "monitor_id" and "visible_frame" (see DashboardCore.set_monitors).
141
+ target_monitor_id: The monitor to move it to.
142
+ """
143
+ window = app.get_window_by_id(window_id)
144
+ target_monitor = next((monitor for monitor in monitors if monitor["monitor_id"] == target_monitor_id), None)
145
+ if window is None or target_monitor is None:
146
+ return ActionResult(False, "that window or monitor no longer exists")
147
+ was_full_screen = await window.async_get_fullscreen()
148
+ if was_full_screen:
149
+ await window.async_set_fullscreen(False)
150
+ await asyncio.sleep(SECONDS_FOR_FULL_SCREEN_ANIMATION)
151
+ frame = await window.async_get_frame()
152
+ window_frame = (frame.origin.x, frame.origin.y, frame.size.width, frame.size.height)
153
+ source_index = assign_windows_to_monitors_by_largest_overlap(
154
+ {window_id: window_frame}, [monitor["frame"] for monitor in monitors])[window_id]
155
+ new_frame = compute_window_frame_on_another_monitor(window_frame, monitors[source_index]["visible_frame"],
156
+ target_monitor["visible_frame"])
157
+ await window.async_set_frame(iterm2.Frame(iterm2.Point(new_frame[0], new_frame[1]), iterm2.Size(new_frame[2], new_frame[3])))
158
+ if was_full_screen:
159
+ await asyncio.sleep(SECONDS_FOR_FULL_SCREEN_ANIMATION)
160
+ await window.async_set_fullscreen(True)
161
+ return ActionResult(True)
162
+
163
+
164
+ def build_new_agent_session_profile(folder, launch_command):
165
+ """Returns profile customizations that start launch_command in folder.
166
+
167
+ iTerm2's "send text at start" profile setting ("Initial Text", Phase 0) types the command
168
+ once the shell is ready, so the tab keeps a normal shell and stays open if the agent exits.
169
+ """
170
+ profile = iterm2.LocalWriteOnlyProfile({"Initial Text": launch_command})
171
+ profile.set_initial_directory_mode(iterm2.InitialWorkingDirectory.INITIAL_WORKING_DIRECTORY_CUSTOM)
172
+ profile.set_custom_directory(folder)
173
+ return profile
174
+
175
+
176
+ async def start_agent_session(connection, app, window_id, folder, launch_command, tab_index=None):
177
+ """Opens a new tab in a window (or a new window when window_id is None) running an agent tool.
178
+
179
+ Args:
180
+ connection: The iTerm2 connection.
181
+ app: The iterm2.App.
182
+ window_id: The window for the new tab, or None for a new window.
183
+ folder: The folder the agent starts in ("~" is expanded).
184
+ launch_command: The shell command that starts the agent tool, for example "claude".
185
+ tab_index: Where the new tab goes among the window's tabs; None puts it last.
186
+ """
187
+ folder = os.path.expanduser(folder)
188
+ if not os.path.isdir(folder):
189
+ return ActionResult(False, f"the folder {folder} doesn't exist")
190
+ if not launch_command.strip():
191
+ return ActionResult(False, "the agent tool has no launch command (see Settings)")
192
+ profile = build_new_agent_session_profile(folder, launch_command)
193
+ if window_id is None:
194
+ await iterm2.Window.async_create(connection, profile_customizations=profile)
195
+ return ActionResult(True)
196
+ window = app.get_window_by_id(window_id)
197
+ if window is None:
198
+ return ActionResult(False, "that window no longer exists")
199
+ await window.async_create_tab(profile_customizations=profile, index=tab_index)
200
+ return ActionResult(True)
201
+
202
+
203
+ async def duplicate_agent_session(connection, app, tab_id, folder, launch_command_for_the_copy):
204
+ """Opens a tab right after tab_id, in its window, running launch_command_for_the_copy in folder
205
+ (like Chrome's Duplicate; the core builds the command that continues a copy of the conversation)."""
206
+ window = app.get_window_for_tab(tab_id)
207
+ if window is None:
208
+ return ActionResult(False, "that tab no longer exists")
209
+ tab_index = [tab.tab_id for tab in window.tabs].index(tab_id)
210
+ return await start_agent_session(connection, app, window.window_id, folder, launch_command_for_the_copy, tab_index + 1)
211
+
212
+
213
+ async def move_tab_to_new_window(app, tab_id):
214
+ """Moves a tab into a new window of its own (iTerm2 refuses this for a window's only tab)."""
215
+ tab = app.get_tab_by_id(tab_id)
216
+ if tab is None:
217
+ return ActionResult(False, "that tab no longer exists")
218
+ window = app.get_window_for_tab(tab_id)
219
+ if window is not None and len(window.tabs) < 2:
220
+ return ActionResult(False, "the tab is already its window's only tab")
221
+ await tab.async_move_to_window()
222
+ return ActionResult(True)
223
+
224
+
225
+ async def read_screen_lines_with_faint_flags(session):
226
+ """Returns the session's visible lines as (text, faint_flags), for screen_readings.input_area_is_empty."""
227
+ contents = await session.async_get_screen_contents()
228
+ screen_lines_with_faint_flags = []
229
+ for index in range(contents.number_of_lines):
230
+ line = contents.line(index)
231
+ screen_lines_with_faint_flags.append(
232
+ (line.string, [bool(style is not None and style.faint) for style in map(line.style_at, range(len(line.string)))]))
233
+ return screen_lines_with_faint_flags
234
+
235
+
236
+ async def type_slash_command(app, session_id, command, adapter, agent_is_in_the_middle_of_a_turn=False):
237
+ """Types a slash command into the agent's empty input box, then Enter after the adapter's
238
+ pause. Types nothing when the box
239
+ holds unsent text or can't be found on screen, since the command would join the draft.
240
+ Reports a failure, without retrying, when the command is still in the box a moment after Enter.
241
+
242
+ Args:
243
+ app: The iterm2.App.
244
+ session_id: The tab's first session.
245
+ command: One of the adapter's slash_commands, for example "/compact".
246
+ adapter: The session's agent tool adapter (its input line marker, input area end and pause).
247
+ agent_is_in_the_middle_of_a_turn: Whether the agent is busy (Claude Code queues a command
248
+ typed then). Enter then goes only while the command is still in the box, since the
249
+ agent may open a permission prompt meanwhile, which would take the Enter as its answer;
250
+ otherwise a failure is reported. Not checked for an agent at its prompt, which opens
251
+ no prompt on its own: in a live check on 2026-10-22, Codex's input box couldn't be found
252
+ on screen right after the command was typed (its slash-command menu was open).
253
+
254
+ Returns:
255
+ None when nothing was typed because the box holds unsent text or can't be found on screen,
256
+ or when the agent refused the command because a turn is under way (Codex, whose turn can
257
+ look over on screen while answer text streams); the caller may try again later. Otherwise
258
+ an ActionResult.
259
+ """
260
+ session = app.get_session_by_id(session_id)
261
+ if session is None:
262
+ return ActionResult(False, "that tab no longer exists")
263
+ if command not in adapter.slash_commands:
264
+ return ActionResult(False, f"{command} can't be sent to {adapter.agent_tool_name or 'this agent'}")
265
+ screen_lines_before_typing = await read_screen_lines_with_faint_flags(session)
266
+ if not input_area_is_empty(screen_lines_before_typing, adapter.input_line_marker, adapter.input_area_end_pattern):
267
+ return None
268
+ await session.async_send_text(command, suppress_broadcast=True)
269
+ await asyncio.sleep(adapter.seconds_before_enter)
270
+ if agent_is_in_the_middle_of_a_turn:
271
+ typed_text = read_typed_input_area_text(await read_screen_lines_with_faint_flags(session), adapter.input_line_marker,
272
+ adapter.input_area_end_pattern)
273
+ if typed_text is None or command not in typed_text:
274
+ return ActionResult(False, f"{command} wasn't submitted: the tab's input box changed before Enter")
275
+ await session.async_send_text("\r", suppress_broadcast=True)
276
+ await asyncio.sleep(SECONDS_BEFORE_CHECKING_THAT_A_COMMAND_WAS_SUBMITTED)
277
+ try:
278
+ screen_lines_after_enter = await read_screen_lines_with_faint_flags(session)
279
+ except iterm2.RPCException:
280
+ return ActionResult(True) # the tab closed meanwhile
281
+ refusal_pattern = adapter.slash_command_refused_during_a_turn_pattern
282
+ if count_lines_matching([text for text, _ in screen_lines_after_enter], refusal_pattern) > count_lines_matching(
283
+ [text for text, _ in screen_lines_before_typing], refusal_pattern):
284
+ return None
285
+ typed_text = read_typed_input_area_text(screen_lines_after_enter, adapter.input_line_marker, adapter.input_area_end_pattern)
286
+ # A box that is off screen (the tool redrawing) can't be checked; the command was sent.
287
+ if typed_text is not None and command in typed_text:
288
+ return ActionResult(False, f"{command} may not have been submitted: it is still in the tab's input box")
289
+ return ActionResult(True)
290
+
291
+
292
+ async def paste_message_into_empty_input_box(app, session_id, message, adapter):
293
+ """Pastes a message of one or more lines into the agent's empty input box as one bracketed
294
+ paste, then presses Enter ("Talk to Each Other"; checked live with Claude Code 2.1.306 on
295
+ 2026-10-21: a three-line message was submitted as one prompt). Reports a failure, without
296
+ retrying, when the box isn't empty a moment after Enter.
297
+
298
+ Args:
299
+ app: The iterm2.App.
300
+ session_id: The tab's first session.
301
+ message: The text to submit.
302
+ adapter: The session's agent tool adapter (its input line marker and input area end).
303
+
304
+ Returns:
305
+ None when nothing was pasted because the box holds unsent text or can't be found on
306
+ screen (the caller may try again later), otherwise an ActionResult.
307
+ """
308
+ session = app.get_session_by_id(session_id)
309
+ if session is None:
310
+ return ActionResult(False, "that tab no longer exists")
311
+ if not input_area_is_empty(await read_screen_lines_with_faint_flags(session), adapter.input_line_marker,
312
+ adapter.input_area_end_pattern):
313
+ return None
314
+ await session.async_send_text(BRACKETED_PASTE_START + message + BRACKETED_PASTE_END, suppress_broadcast=True)
315
+ await asyncio.sleep(SECONDS_BETWEEN_A_PASTE_AND_ITS_ENTER)
316
+ await session.async_send_text("\r", suppress_broadcast=True)
317
+ await asyncio.sleep(SECONDS_BEFORE_CHECKING_THAT_A_COMMAND_WAS_SUBMITTED)
318
+ try:
319
+ typed_text = read_typed_input_area_text(await read_screen_lines_with_faint_flags(session), adapter.input_line_marker,
320
+ adapter.input_area_end_pattern)
321
+ except iterm2.RPCException:
322
+ return ActionResult(True) # the tab closed meanwhile
323
+ if typed_text: # None: the box is off screen (the tool redrawing), so it can't be checked
324
+ return ActionResult(False, "the message may not have been submitted: the tab's input box isn't empty after Enter")
325
+ return ActionResult(True)