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,75 @@
1
+ """Which records of a Claude Code transcript start a turn, the one rule for both readers of a
2
+ transcript's end: when the current turn began (context_window_usage) and the preview's last
3
+ prompt (session_preview_computation). Pure functions."""
4
+
5
+ import re
6
+
7
+ # The tags Claude Code wraps its own texts in user records with (seen in Claude Code 2.1
8
+ # transcripts): a local command's output and caveat, a "!" shell command and its output, and
9
+ # reminders. Its notes after an interrupt and its caveats start with plain words instead. Any
10
+ # other text is the user's, also one that starts with a tag (pasted content, HTML).
11
+ GENERATED_USER_TEXT_PATTERN = re.compile(
12
+ r"^(?:<(?:local-command-stdout|local-command-stderr|local-command-caveat|bash-input|bash-stdout|bash-stderr"
13
+ r"|system-reminder)>|\[Request interrupted|Caveat:)")
14
+ # A slash command or skill the user typed is written as "<command-message>…<command-name>/x</command-name>
15
+ # <command-args>…</command-args>".
16
+ COMMAND_NAME_PATTERN = re.compile(r"<command-name>(.*?)</command-name>", re.S)
17
+ COMMAND_ARGUMENTS_PATTERN = re.compile(r"<command-args>(.*?)</command-args>", re.S)
18
+ TURN_STARTING_NOTIFICATION_START = "<task-notification>" # a background task's notification starts a turn too
19
+ # So do another Claude Code session's message ("peer") and its "[Cross-session idle notice]"
20
+ # ("system"), meta records that Claude Code 2.1 writes with these turnOrigin values.
21
+ TURN_ORIGINS_OF_ANOTHER_SESSIONS_MESSAGE = frozenset({"peer", "system"})
22
+ RECORD_KINDS_THAT_START_A_TURN = frozenset({"prompt", "command", "notification"})
23
+
24
+
25
+ def list_message_blocks(record):
26
+ """Returns the content blocks of a record's message, as dicts (a plain-text content is one text block)."""
27
+ message = record.get("message")
28
+ content = message.get("content") if isinstance(message, dict) else None
29
+ blocks = content if isinstance(content, list) else [{"type": "text", "text": content}] if isinstance(content, str) else []
30
+ return [block for block in blocks if isinstance(block, dict)]
31
+
32
+
33
+ def join_text_blocks(blocks):
34
+ """Returns the text of a record's text blocks, one per line."""
35
+ return "\n".join(str(block.get("text") or "") for block in blocks if block.get("type") == "text")
36
+
37
+
38
+ def classify_user_record(record, blocks):
39
+ """Returns what a transcript record is, when looking for where the current turn began.
40
+
41
+ Args:
42
+ record: One decoded transcript record.
43
+ blocks: Its message blocks (list_message_blocks).
44
+
45
+ Returns:
46
+ "tool_result" for a tool's result; "prompt" for text the user typed; "command" for a
47
+ slash command or skill the user typed (describe_typed_command); "notification" for a
48
+ background task's notification, a message from another Claude Code session (its
49
+ SendMessage tool's) or a notice that one went idle (meta records with turnOrigin "peer"
50
+ and "system"; code review, 2026-10-28); or None for anything else: not a user record, a
51
+ subagent's record, another meta record (such as a skill's text, written in the middle
52
+ of a turn), the summary after /compact, Claude Code's own texts, or an empty record.
53
+ """
54
+ if record.get("type") != "user" or record.get("isSidechain") or record.get("isCompactSummary"):
55
+ return None
56
+ if record.get("turnOrigin") in TURN_ORIGINS_OF_ANOTHER_SESSIONS_MESSAGE:
57
+ return "notification"
58
+ if record.get("isMeta"):
59
+ return None
60
+ if any(block.get("type") == "tool_result" for block in blocks):
61
+ return "tool_result"
62
+ text = join_text_blocks(blocks).lstrip()
63
+ if COMMAND_NAME_PATTERN.search(text):
64
+ return "command"
65
+ if text.startswith(TURN_STARTING_NOTIFICATION_START):
66
+ return "notification"
67
+ if text and not GENERATED_USER_TEXT_PATTERN.match(text):
68
+ return "prompt"
69
+ return None
70
+
71
+
72
+ def describe_typed_command(text):
73
+ """Returns "/name arguments" for a typed slash command's record text."""
74
+ command_arguments_match = COMMAND_ARGUMENTS_PATTERN.search(text)
75
+ return f"{COMMAND_NAME_PATTERN.search(text).group(1)} {command_arguments_match.group(1) if command_arguments_match else ''}"
@@ -0,0 +1,187 @@
1
+ """Command line entry point: `agent-command-tab run | app | dump-snapshot | install-hooks | remove-hooks`."""
2
+
3
+ import argparse
4
+ import fcntl
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import sys
9
+ import threading
10
+ import time
11
+
12
+ from agent_command_tab import __version__
13
+
14
+ RECONNECT_EXIT_STATUS = 75
15
+ LONGEST_RESTART_DELAY_SECONDS = 30
16
+ SECONDS_TO_WAIT_FOR_AGENT_NAMES = 2
17
+ # Before it exits, the app waits at most this long for docked windows to get their room back
18
+ # (app_controller); after Ctrl+C the supervisor gives it that and more before killing it.
19
+ SECONDS_TO_WAIT_FOR_ROOM_BACK_BEFORE_EXITING = 3
20
+ SECONDS_TO_WAIT_FOR_THE_APP_AFTER_CTRL_C = SECONDS_TO_WAIT_FOR_ROOM_BACK_BEFORE_EXITING + 7
21
+ # Held by the running supervisor (take_the_running_lock), in the settings folder (settings_store.SETTINGS_FOLDER).
22
+ RUNNING_LOCK_FILE_PATH = os.path.expanduser("~/Library/Application Support/agent-command-tab/running.lock")
23
+
24
+
25
+ def dump_snapshot(verbose):
26
+ """Connects to iTerm2, prints the current snapshot as JSON, and exits (for tests and bug reports).
27
+
28
+ Waits a few seconds after the first snapshot, so that names from `claude agents --json`
29
+ (read in the background) are included.
30
+ """
31
+ from agent_command_tab.iterm2_connection_thread import Iterm2ConnectionThread
32
+ from agent_command_tab.pause_records_store import PAUSE_RECORDS_FILE_PATH, load_pause_records
33
+ from agent_command_tab.settings_store import build_core_settings, load_settings
34
+ from agent_command_tab.snapshot_data_classes import convert_snapshot_to_json_ready_dict
35
+ from agent_command_tab.user_interface.screen_layout import read_monitors_from_screens
36
+
37
+ first_snapshot_arrived = threading.Event()
38
+ received = {}
39
+
40
+ def publish_snapshot(snapshot):
41
+ received["snapshot"] = snapshot
42
+ first_snapshot_arrived.set()
43
+
44
+ def report_connection_lost(message):
45
+ received.setdefault("problem", message)
46
+ first_snapshot_arrived.set()
47
+
48
+ # The app's pause records, so paused sessions are listed, kept in memory only: this run
49
+ # never changes the app's file.
50
+ connection_thread = Iterm2ConnectionThread(
51
+ publish_snapshot, report_connection_lost, verbose,
52
+ pause_record_by_tab_and_agent_to_start_with=load_pause_records(PAUSE_RECORDS_FILE_PATH))
53
+ connection_thread.start()
54
+ # The app's settings, so the agent tools left out in Settings are left out here too.
55
+ connection_thread.send_core_settings(build_core_settings(load_settings()))
56
+ connection_thread.send_monitors(read_monitors_from_screens()) # the same monitor groups as the dropdown
57
+ if not first_snapshot_arrived.wait(timeout=30):
58
+ print("no snapshot within 30 seconds", file=sys.stderr)
59
+ return 1
60
+ if "snapshot" not in received:
61
+ print(received["problem"], file=sys.stderr)
62
+ return 1
63
+ time.sleep(SECONDS_TO_WAIT_FOR_AGENT_NAMES)
64
+ print(json.dumps(convert_snapshot_to_json_ready_dict(received["snapshot"]), indent=1))
65
+ return 0
66
+
67
+
68
+ def install_or_remove_hooks(install):
69
+ """Adds the app's hooks to Claude Code's and Codex's settings, or takes them out, and prints
70
+ which files changed (hooks_installer); returns the exit status."""
71
+ from agent_command_tab.hooks_installer import HOOK_EVENTS_BY_AGENT_TOOL_NAME, install_hooks, remove_hooks
72
+ exit_status = 0
73
+ for agent_tool_name in HOOK_EVENTS_BY_AGENT_TOOL_NAME:
74
+ try:
75
+ changed_file_paths = (install_hooks if install else remove_hooks)(agent_tool_name)
76
+ except (OSError, ValueError) as error:
77
+ print(f"{agent_tool_name}: {error}", file=sys.stderr)
78
+ exit_status = 1
79
+ continue
80
+ for file_path in changed_file_paths:
81
+ print(f"{agent_tool_name}: {'added to' if install else 'removed from'} {file_path}")
82
+ if not changed_file_paths:
83
+ print(f"{agent_tool_name}: nothing to change")
84
+ elif install:
85
+ print(f"{agent_tool_name}: sessions started from now on use them"
86
+ + ("; Codex asks you to approve them first (type /hooks in Codex)" if agent_tool_name == "Codex" else ""))
87
+ return exit_status
88
+
89
+
90
+ def run_app_process(verbose):
91
+ """Runs the menu bar app in this process; returns its exit status."""
92
+ from agent_command_tab.app_controller import run_menu_bar_app
93
+ return run_menu_bar_app(verbose)
94
+
95
+
96
+ def wait_for_app_process(process):
97
+ """Returns the app process's exit status.
98
+
99
+ Ctrl+C in the terminal reaches the app process too, which then gives docked windows their
100
+ room back (up to SECONDS_TO_WAIT_FOR_ROOM_BACK_BEFORE_EXITING) before exiting, so this waits
101
+ for that rather than killing it at once
102
+ (subprocess.call would kill it after a quarter of a second). It kills the app only if it
103
+ hasn't exited after SECONDS_TO_WAIT_FOR_THE_APP_AFTER_CTRL_C.
104
+ """
105
+ try:
106
+ return process.wait()
107
+ except KeyboardInterrupt:
108
+ try:
109
+ return process.wait(timeout=SECONDS_TO_WAIT_FOR_THE_APP_AFTER_CTRL_C)
110
+ except subprocess.TimeoutExpired:
111
+ process.kill()
112
+ return process.wait()
113
+
114
+
115
+ def take_the_running_lock(lock_file_path=RUNNING_LOCK_FILE_PATH):
116
+ """Returns the lock file, open, once this process holds its lock, or None while another process
117
+ holds it. macOS releases the lock when the process holding it ends, however it ends. The file
118
+ holds the process ID of the one holding it."""
119
+ os.makedirs(os.path.dirname(lock_file_path), exist_ok=True)
120
+ lock_file = open(lock_file_path, "a+")
121
+ try:
122
+ fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
123
+ except BlockingIOError:
124
+ lock_file.close()
125
+ return None
126
+ lock_file.seek(0)
127
+ lock_file.truncate()
128
+ lock_file.write(f"{os.getpid()}\n")
129
+ lock_file.flush()
130
+ return lock_file
131
+
132
+
133
+ def run_with_restarts(verbose):
134
+ """Starts the app process and restarts it, with a growing delay, whenever it exits to reconnect.
135
+
136
+ The `iterm2` package can't reconnect within one process, so the app
137
+ exits with RECONNECT_EXIT_STATUS when iTerm2's connection drops, and this supervisor starts
138
+ it again (1 s, doubling up to 30 s, reset after a run that lasted a minute).
139
+
140
+ Only one supervisor runs at a time (take_the_running_lock): another exits at once, so iTerm2
141
+ starting the app when it opens (start_with_iterm2) adds no second copy to one still waiting to
142
+ reconnect, and two copies never compete for the hook events (user request, 2026-10-28).
143
+ """
144
+ running_lock_file = take_the_running_lock() # held, open, until this supervisor returns
145
+ if running_lock_file is None:
146
+ with open(RUNNING_LOCK_FILE_PATH) as lock_file:
147
+ process_id_of_the_running_copy = lock_file.read().strip()
148
+ print(f"agent-command-tab: already running (process {process_id_of_the_running_copy or 'unknown'}); "
149
+ "to start it again, first choose Quit AgentCommandTab in its menu bar icon's menu")
150
+ return 0
151
+ restart_delay_seconds = 1
152
+ while True:
153
+ started_at = time.time()
154
+ command = [sys.executable, "-m", "agent_command_tab.command_line", "app"] + (["--verbose"] if verbose else [])
155
+ exit_status = wait_for_app_process(subprocess.Popen(command, env=os.environ))
156
+ if exit_status != RECONNECT_EXIT_STATUS:
157
+ return exit_status
158
+ if time.time() - started_at > 60:
159
+ restart_delay_seconds = 1
160
+ print(f"agent-command-tab: reconnecting in {restart_delay_seconds} s")
161
+ time.sleep(restart_delay_seconds)
162
+ restart_delay_seconds = min(restart_delay_seconds * 2, LONGEST_RESTART_DELAY_SECONDS)
163
+
164
+
165
+ def main(arguments=None):
166
+ """Parses the command line and runs the chosen command."""
167
+ parser = argparse.ArgumentParser(prog="agent-command-tab", description=__doc__)
168
+ parser.add_argument("command", choices=["run", "app", "dump-snapshot", "install-hooks", "remove-hooks"], nargs="?",
169
+ default="run",
170
+ help="run: the menu bar app, restarted when iTerm2's connection drops (default); "
171
+ "app: the menu bar app without restarts; dump-snapshot: print the current list as JSON; "
172
+ "install-hooks, remove-hooks: add the app's hooks to Claude Code's and Codex's settings, "
173
+ "or take them out")
174
+ parser.add_argument("--verbose", action="store_true", help="print diagnostics")
175
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
176
+ parsed_arguments = parser.parse_args(arguments)
177
+ if parsed_arguments.command == "dump-snapshot":
178
+ return dump_snapshot(parsed_arguments.verbose)
179
+ if parsed_arguments.command in ("install-hooks", "remove-hooks"):
180
+ return install_or_remove_hooks(parsed_arguments.command == "install-hooks")
181
+ if parsed_arguments.command == "app":
182
+ return run_app_process(parsed_arguments.verbose)
183
+ return run_with_restarts(parsed_arguments.verbose)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ sys.exit(main())
@@ -0,0 +1,230 @@
1
+ """How much of its context window each agent session uses, read from the end of its own
2
+ conversation file (user request, milestone 2: a tokens column, for example "425k").
3
+
4
+ - Claude Code writes a transcript, <config folder>/projects/<folder>/<session ID>.jsonl; the
5
+ latest reply's usage (input, cache-write and cache-read tokens) is the context in use, the
6
+ same number its status line shows as total_input_tokens.
7
+ - Codex writes ~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<ID>.jsonl with "token_count"
8
+ events whose last_token_usage.total_tokens is the context in use (find_codex_conversation_files).
9
+ - The context window's size, for the share in use (user request, 2026-10-26: "134k (13%)" in the
10
+ Tokens column): Codex reports it with its usage; for Claude Code it follows from the model the session
11
+ was started with, from its arguments, environment or settings (read_claude_code_model_setting).
12
+
13
+ Only the last BYTES_TO_READ_FROM_THE_END bytes are read, since transcripts reach tens of megabytes.
14
+ """
15
+
16
+ import datetime
17
+ import glob
18
+ import json
19
+ import os
20
+
21
+ from agent_command_tab.claude_code_transcript_records import (RECORD_KINDS_THAT_START_A_TURN, classify_user_record,
22
+ list_message_blocks)
23
+
24
+ BYTES_TO_READ_FROM_THE_END = 512 * 1024
25
+ CLAUDE_CODE_CONTEXT_WINDOW_TOKENS = 200_000
26
+ CLAUDE_CODE_1M_CONTEXT_WINDOW_TOKENS = 1_000_000
27
+
28
+
29
+ def read_last_lines(file_path, byte_count=BYTES_TO_READ_FROM_THE_END):
30
+ """Returns the file's last complete lines within its last byte_count bytes, newest first."""
31
+ try:
32
+ with open(file_path, "rb") as file:
33
+ file.seek(0, os.SEEK_END)
34
+ size = file.tell()
35
+ file.seek(max(0, size - byte_count))
36
+ text = file.read().decode(errors="replace")
37
+ except OSError:
38
+ return []
39
+ # Only "\n" ends a line: JSON leaves U+2028 and U+0085 inside strings, which splitlines() would split at.
40
+ lines = [line for line in text.split("\n") if line]
41
+ if size > byte_count:
42
+ lines = lines[1:] # the first line was cut
43
+ return list(reversed(lines))
44
+
45
+
46
+ def read_last_records(file_path):
47
+ """Yields the JSON objects of a conversation file's last complete lines (read_last_lines),
48
+ newest first, skipping lines that are not JSON objects."""
49
+ for line in read_last_lines(file_path):
50
+ try:
51
+ record = json.loads(line)
52
+ except ValueError:
53
+ continue
54
+ if isinstance(record, dict):
55
+ yield record
56
+
57
+
58
+ def read_context_tokens_from_claude_code_transcript(file_path):
59
+ """Returns the tokens in context after the latest reply in a Claude Code transcript, or after
60
+ the latest compaction (/compact, or an automatic one) when no reply came since, or None."""
61
+ for record in read_last_records(file_path):
62
+ if record.get("type") == "system" and record.get("subtype") == "compact_boundary" and not record.get("isSidechain"):
63
+ post_compaction_tokens = (record.get("compactMetadata") or {}).get("postTokens")
64
+ if isinstance(post_compaction_tokens, int):
65
+ return post_compaction_tokens
66
+ message = (record.get("message") or {}) if record.get("type") == "assistant" else {}
67
+ usage = message.get("usage")
68
+ if not isinstance(usage, dict) or message.get("model") == "<synthetic>":
69
+ continue # Claude Code writes errors (API errors, spend limits) as replies with all-zero usage
70
+ context_tokens = (usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0)
71
+ + usage.get("cache_read_input_tokens", 0))
72
+ if context_tokens:
73
+ return context_tokens
74
+ return None
75
+
76
+
77
+ def read_context_tokens_from_codex_conversation_file(file_path):
78
+ """Returns the tokens in context after the latest turn in a Codex conversation file, or None."""
79
+ for record in read_last_records(file_path):
80
+ payload = record.get("payload")
81
+ if isinstance(payload, dict) and payload.get("type") == "token_count":
82
+ last_token_usage = (payload.get("info") or {}).get("last_token_usage") or {}
83
+ if "total_tokens" in last_token_usage:
84
+ return last_token_usage["total_tokens"]
85
+ return None
86
+
87
+
88
+ def read_context_window_tokens_from_codex_conversation_file(file_path):
89
+ """Returns the size of the context window Codex reports with its latest turn's usage
90
+ (model_context_window, for example 258400), or None."""
91
+ for record in read_last_records(file_path):
92
+ payload = record.get("payload")
93
+ if isinstance(payload, dict) and payload.get("type") == "token_count":
94
+ model_context_window = (payload.get("info") or {}).get("model_context_window")
95
+ if isinstance(model_context_window, int) and model_context_window > 0:
96
+ return model_context_window
97
+ return None
98
+
99
+
100
+ def read_claude_code_model_setting(process_arguments, process_environment, config_folder):
101
+ """Returns the model a Claude Code session was started with, in the order Claude Code goes by:
102
+ its `--model` argument, else its ANTHROPIC_MODEL environment variable, else the "model" in its
103
+ config folder's settings.json (for example "opus[1m]"), else None. Its transcript names the
104
+ model without saying whether its context window is the 1M one."""
105
+ for index, argument in enumerate(process_arguments):
106
+ if argument == "--model" and index + 1 < len(process_arguments):
107
+ return process_arguments[index + 1]
108
+ if argument.startswith("--model="):
109
+ return argument.partition("=")[2]
110
+ if process_environment.get("ANTHROPIC_MODEL"):
111
+ return process_environment["ANTHROPIC_MODEL"]
112
+ try:
113
+ with open(os.path.join(config_folder or os.path.expanduser("~/.claude"), "settings.json")) as settings_file:
114
+ model = json.load(settings_file).get("model")
115
+ except (OSError, ValueError, AttributeError):
116
+ return None
117
+ return model if isinstance(model, str) else None
118
+
119
+
120
+ def choose_claude_code_context_window_tokens(model_setting, context_tokens):
121
+ """Returns the size of a Claude Code session's context window: 1M for a model chosen with the
122
+ "[1m]" suffix, or once the context holds more than 200k tokens (a 1M model chosen some other
123
+ way), else 200k."""
124
+ if (model_setting or "").lower().endswith("[1m]") or (context_tokens or 0) > CLAUDE_CODE_CONTEXT_WINDOW_TOKENS:
125
+ return CLAUDE_CODE_1M_CONTEXT_WINDOW_TOKENS
126
+ return CLAUDE_CODE_CONTEXT_WINDOW_TOKENS
127
+
128
+
129
+ def read_turn_started_at_from_claude_code_transcript(file_path):
130
+ """Returns when the current turn began: the newest record that starts a turn (a prompt, a
131
+ typed command or a background task's notification; claude_code_transcript_records), or
132
+ None if none is in the file's end."""
133
+ for record in read_last_records(file_path):
134
+ if (classify_user_record(record, list_message_blocks(record)) in RECORD_KINDS_THAT_START_A_TURN
135
+ and parse_iso_time(record.get("timestamp"))):
136
+ return parse_iso_time(record.get("timestamp"))
137
+ return None
138
+
139
+
140
+ def read_turn_started_at_from_codex_conversation_file(file_path):
141
+ """Returns when the current turn began (the newest "task_started" event), or None."""
142
+ for record in read_last_records(file_path):
143
+ payload = record.get("payload")
144
+ if isinstance(payload, dict) and payload.get("type") == "task_started" and parse_iso_time(record.get("timestamp")):
145
+ return parse_iso_time(record.get("timestamp"))
146
+ return None
147
+
148
+
149
+ def find_claude_code_transcript(claude_config_folders, claude_session_id):
150
+ """Returns the path of a Claude Code session's transcript, or None if it isn't found."""
151
+ for config_folder in claude_config_folders:
152
+ matches = glob.glob(os.path.join(glob.escape(config_folder), "projects", "*", glob.escape(claude_session_id) + ".jsonl"))
153
+ if matches:
154
+ return matches[0]
155
+ return None
156
+
157
+
158
+ def find_codex_conversation_files(codex_sessions_folder, agent_started_at, agent_working_folder, now,
159
+ agent_resumed_a_conversation=False):
160
+ """Returns the files that may be a Codex session's conversation, most recently written first;
161
+ empty before the first prompt (Codex writes the file then, and doesn't keep it open, so lsof
162
+ can't find it).
163
+
164
+ They are the rollout-*.jsonl files in the day folders (YYYY/MM/DD, local time) from the
165
+ agent's start to today whose first line, the session_meta header, is an interactive
166
+ session's (source "cli", not the auto-review helper's or `codex exec`'s), names the
167
+ agent's folder, and starts no earlier than the agent process. The first is the current
168
+ conversation (Codex's /new starts another). Two Codex sessions in one folder can't be
169
+ told apart (a known limit), so callers that must be sure check that there is only one.
170
+
171
+ `codex resume` goes on writing the earlier conversation's file, which stays in its own day
172
+ folder with its own header: for such a process, every day folder is searched, and a file
173
+ written since the process started fits whatever start its header names.
174
+
175
+ Args:
176
+ codex_sessions_folder: Codex's sessions folder ($CODEX_HOME/sessions).
177
+ agent_started_at: When the agent process started.
178
+ agent_working_folder: The agent process's current folder.
179
+ now: The current time.
180
+ agent_resumed_a_conversation: Whether the agent process was started with `codex resume`.
181
+ """
182
+ if agent_resumed_a_conversation:
183
+ paths = glob.glob(os.path.join(glob.escape(codex_sessions_folder), "*", "*", "*", "rollout-*.jsonl"))
184
+ else:
185
+ paths = []
186
+ day = datetime.date.fromtimestamp(agent_started_at)
187
+ while day <= datetime.date.fromtimestamp(now):
188
+ day_folder = os.path.join(codex_sessions_folder, f"{day.year:04d}", f"{day.month:02d}", f"{day.day:02d}")
189
+ paths += glob.glob(os.path.join(glob.escape(day_folder), "rollout-*.jsonl"))
190
+ day += datetime.timedelta(days=1)
191
+ candidates = []
192
+ for path in paths:
193
+ try:
194
+ modified_at = os.path.getmtime(path)
195
+ except OSError:
196
+ continue
197
+ if modified_at >= agent_started_at:
198
+ candidates.append((modified_at, path))
199
+ conversation_files = []
200
+ for _, path in sorted(candidates, reverse=True):
201
+ header = read_codex_session_header(path)
202
+ if (header.get("source") == "cli" and header.get("cwd") == agent_working_folder
203
+ and (agent_resumed_a_conversation or parse_iso_time(header.get("timestamp")) >= agent_started_at - 5)):
204
+ conversation_files.append(path)
205
+ return conversation_files
206
+
207
+
208
+ def read_codex_session_header(file_path):
209
+ """Returns the session_meta payload from a Codex conversation file's first line, or {}."""
210
+ try:
211
+ with open(file_path) as file:
212
+ record = json.loads(file.readline())
213
+ except (OSError, ValueError):
214
+ return {}
215
+ return record.get("payload") or {} if isinstance(record, dict) and record.get("type") == "session_meta" else {}
216
+
217
+
218
+ def parse_iso_time(text):
219
+ """Returns seconds since the epoch for "2026-10-19T02:14:42.315Z", or 0 if it can't be read."""
220
+ try:
221
+ return datetime.datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()
222
+ except (AttributeError, ValueError):
223
+ return 0
224
+
225
+
226
+ def format_token_count(token_count):
227
+ """Returns a short token count: "425k", or "1.2M" from 999,500 up (which "k" would round to "1000k")."""
228
+ if token_count >= 999_500:
229
+ return f"{token_count / 1_000_000:.1f}M"
230
+ return f"{round(token_count / 1000)}k"
@@ -0,0 +1,57 @@
1
+ """The boundary between the core and its views.
2
+
3
+ Every user action is an ActionRequest. The menu bar list builds requests exactly as a later
4
+ web page, phone app or second computer would, and the core runs them through one registry
5
+ that knows each action's safety flags.
6
+ """
7
+
8
+ import collections
9
+
10
+ ActionRequest = collections.namedtuple("ActionRequest", ["action", "target", "arguments"], defaults=[None])
11
+ ActionRequest.__doc__ = ("One user action. target is a dict with any of computer_id, window_id, tab_id and "
12
+ "session_id; arguments is a dict, for example {\"new_title\": \"Reviews\"}.")
13
+
14
+ ActionResult = collections.namedtuple("ActionResult", ["succeeded", "message"], defaults=[""])
15
+ ActionResult.__doc__ = "What an action did. message explains a failure in plain words."
16
+
17
+ ActionDefinition = collections.namedtuple(
18
+ "ActionDefinition", ["handler", "may_come_from_another_computer", "types_into_a_session"])
19
+ ActionDefinition.__doc__ = ("A registered action: an async handler taking an ActionRequest and returning an "
20
+ "ActionResult, plus the flags later network views are checked against.")
21
+
22
+
23
+ class ActionRegistry:
24
+ """Maps action names to their handlers and flags."""
25
+
26
+ def __init__(self):
27
+ self.action_definitions_by_name = {}
28
+
29
+ def register_action(self, action_name, handler, may_come_from_another_computer, types_into_a_session):
30
+ """Registers an action.
31
+
32
+ Args:
33
+ action_name: For example "rename_tab".
34
+ handler: async function(ActionRequest) -> ActionResult.
35
+ may_come_from_another_computer: False for moves, drags and list reordering.
36
+ types_into_a_session: True for actions that type into an agent's terminal.
37
+ """
38
+ self.action_definitions_by_name[action_name] = ActionDefinition(
39
+ handler, may_come_from_another_computer, types_into_a_session)
40
+
41
+ async def perform_action(self, action_request, request_comes_from_another_computer=False):
42
+ """Runs a request and returns its ActionResult; never raises.
43
+
44
+ Args:
45
+ action_request: An ActionRequest.
46
+ request_comes_from_another_computer: True for requests from a network view (not in
47
+ version 1); such requests run only for actions that allow it.
48
+ """
49
+ action_definition = self.action_definitions_by_name.get(action_request.action)
50
+ if action_definition is None:
51
+ return ActionResult(False, f"unknown action {action_request.action!r}")
52
+ if request_comes_from_another_computer and not action_definition.may_come_from_another_computer:
53
+ return ActionResult(False, f"{action_request.action} can only be done on this computer")
54
+ try:
55
+ return await action_definition.handler(action_request)
56
+ except Exception as error: # An action must never take down the core.
57
+ return ActionResult(False, f"{action_request.action} failed: {error}")
@@ -0,0 +1,60 @@
1
+ """The frames iTerm2 windows had before a docked sidebar narrowed them.
2
+
3
+ They are kept in a file next to the settings, so windows can still get their room back after
4
+ the dashboard restarts (a reconnect when iTerm2 quits, a crash, Ctrl+C). Pure functions apart
5
+ from the file reading and writing.
6
+ """
7
+
8
+ import json
9
+ import os
10
+
11
+ from agent_command_tab.monitor_assignment import frames_are_within_tolerance
12
+ from agent_command_tab.settings_store import SETTINGS_FOLDER, write_json_file_atomically
13
+
14
+ DOCKED_WINDOW_FRAMES_FILE_PATH = os.path.join(SETTINGS_FOLDER, "docked_window_frames.json")
15
+
16
+
17
+ def frame_is_valid(frame):
18
+ return (isinstance(frame, (list, tuple)) and len(frame) == 4
19
+ and all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in frame))
20
+
21
+
22
+ def load_docked_window_frames(file_path):
23
+ """Returns {window ID: (frame before docking, frame that was set)} from the file; {} when it
24
+ is missing or unreadable, and without records that don't have that shape."""
25
+ try:
26
+ with open(file_path) as file:
27
+ stored_records = json.load(file)
28
+ except (OSError, ValueError):
29
+ return {}
30
+ if not isinstance(stored_records, dict):
31
+ return {}
32
+ return {window_id: (tuple(frames[0]), tuple(frames[1])) for window_id, frames in stored_records.items()
33
+ if isinstance(frames, list) and len(frames) == 2 and all(map(frame_is_valid, frames))}
34
+
35
+
36
+ def save_docked_window_frames(file_path, frames_by_window_id):
37
+ write_json_file_atomically({window_id: [list(frames[0]), list(frames[1])]
38
+ for window_id, frames in frames_by_window_id.items()}, file_path)
39
+
40
+
41
+ def adopt_records_of_restored_windows(frames_by_window_id, current_frames_by_window_id, tolerance_points):
42
+ """Returns the records with each record whose window is gone moved to a live window that has
43
+ no record and still has the frame that was set: iTerm2 gives the windows it restores after
44
+ a restart new IDs.
45
+
46
+ Args:
47
+ frames_by_window_id: {window ID: (frame before docking, frame that was set)}.
48
+ current_frames_by_window_id: {window ID: current frame} of the live windows.
49
+ tolerance_points: How far a frame may differ and still count as the same.
50
+ """
51
+ records = dict(frames_by_window_id)
52
+ windows_without_records = [window_id for window_id in current_frames_by_window_id if window_id not in records]
53
+ for window_id in [window_id for window_id in records if window_id not in current_frames_by_window_id]:
54
+ frame_that_was_set = records[window_id][1]
55
+ matching_window_id = next((candidate for candidate in windows_without_records if frames_are_within_tolerance(
56
+ current_frames_by_window_id[candidate], frame_that_was_set, tolerance_points)), None)
57
+ if matching_window_id is not None:
58
+ records[matching_window_id] = records.pop(window_id)
59
+ windows_without_records.remove(matching_window_id)
60
+ return records