cc-ghostty 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.
@@ -0,0 +1,163 @@
1
+ import argparse
2
+ import os
3
+ import re
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from datetime import datetime
9
+
10
+ from cc_ghostty import claude, registry, sessions
11
+
12
+ OK, WARN, FAIL = "ok", "warn", "FAIL"
13
+ MACOS_MIN_VERSION = (1, 3)
14
+
15
+
16
+ @dataclass
17
+ class Check:
18
+ status: str
19
+ label: str
20
+ detail: str = ""
21
+
22
+
23
+ def _run(argv: list[str]) -> str | None:
24
+ try:
25
+ done = subprocess.run(argv, capture_output=True, text=True, timeout=10)
26
+ except (OSError, subprocess.TimeoutExpired):
27
+ return None
28
+ return done.stdout.strip() if done.returncode == 0 else None
29
+
30
+
31
+ def _linux() -> list[Check]:
32
+ from cc_ghostty.ghostty.linux import DBUS_NAME, pane_config_included
33
+
34
+ checks = []
35
+ for tool in ("ghostty", "gdbus"):
36
+ path = shutil.which(tool)
37
+ checks.append(Check(OK if path else FAIL, tool, path or "not found"))
38
+ if shutil.which("gdbus"):
39
+ reply = _run(
40
+ [
41
+ "gdbus", "call", "--session", "--dest", "org.freedesktop.DBus",
42
+ "--object-path", "/org/freedesktop/DBus",
43
+ "--method", "org.freedesktop.DBus.NameHasOwner", DBUS_NAME,
44
+ ]
45
+ ) # fmt: skip
46
+ running = reply == "(true,)"
47
+ detail = DBUS_NAME if running else f"{DBUS_NAME} not owned"
48
+ checks.append(Check(OK if running else FAIL, "Ghostty on D-Bus", detail))
49
+ included = pane_config_included()
50
+ checks.append(
51
+ Check(
52
+ OK if included else WARN,
53
+ "panes (split)",
54
+ "Ghostty includes cc-ghostty's pane config"
55
+ if included
56
+ else "run `cc-ghostty setup` once to let split open panes",
57
+ )
58
+ )
59
+ return checks
60
+
61
+
62
+ def _version(text: str | None) -> tuple[int, ...]:
63
+ match = re.match(r"(\d+)\.(\d+)", text or "")
64
+ return tuple(int(p) for p in match.groups()) if match else ()
65
+
66
+
67
+ def _macos() -> list[Check]:
68
+ from cc_ghostty.ghostty.macos import APP_PATHS
69
+
70
+ checks = []
71
+ app = next((p for p in APP_PATHS if p.exists()), None)
72
+ if app is None:
73
+ return [Check(FAIL, "Ghostty.app", "not found in /Applications")]
74
+ version = _run(
75
+ ["defaults", "read", str(app / "Contents/Info"), "CFBundleShortVersionString"]
76
+ )
77
+ recent = _version(version) >= MACOS_MIN_VERSION
78
+ checks.append(
79
+ Check(
80
+ OK if recent else FAIL,
81
+ "Ghostty.app",
82
+ f"{app}, version {version or '?'}"
83
+ + ("" if recent else " (AppleScript needs 1.3+)"),
84
+ )
85
+ )
86
+ if _run(["pgrep", "-x", "ghostty"]) is None:
87
+ checks.append(Check(WARN, "AppleScript", "Ghostty is not running: not checked"))
88
+ return checks
89
+ # May show macOS's Automation prompt once: that grant is what cc-ghostty needs.
90
+ reply = _run(["osascript", "-e", 'tell application "Ghostty" to get version'])
91
+ checks.append(
92
+ Check(
93
+ OK if reply else FAIL,
94
+ "AppleScript",
95
+ "Ghostty answers"
96
+ if reply
97
+ else "no answer: allow Automation for your terminal in System Settings "
98
+ "> Privacy & Security, and keep `macos-applescript` enabled",
99
+ )
100
+ )
101
+ return checks
102
+
103
+
104
+ def _inside_ghostty() -> Check:
105
+ inside = os.environ.get("TERM_PROGRAM") == "ghostty" or bool(
106
+ os.environ.get("GHOSTTY_SURFACE_ID")
107
+ )
108
+ return Check(OK if inside else WARN, "inside Ghostty", "yes" if inside else "no")
109
+
110
+
111
+ def _claude() -> list[Check]:
112
+ here = claude.executable()
113
+ shell = os.environ.get("SHELL") or "bash"
114
+ login = _run([shell, "-lc", "command -v claude"])
115
+ detail = here
116
+ if login and login != here:
117
+ detail += f" (a login shell finds {login}; new tabs use {here})"
118
+ return [Check(OK if shutil.which("claude") else FAIL, "claude", detail)]
119
+
120
+
121
+ def _accounts() -> list[Check]:
122
+ live = sessions.live()
123
+ checks = []
124
+ for config_dir in sessions.known_config_dirs():
125
+ directory = claude.resolve_config_dir(config_dir)
126
+ if not directory.is_dir():
127
+ continue
128
+ email = claude.account_email(config_dir)
129
+ count = sum(1 for s in live if s.config_dir == config_dir)
130
+ checks.append(
131
+ Check(
132
+ OK if email else WARN,
133
+ f"config {directory}",
134
+ f"{email or 'no account'}, {count} running session(s)",
135
+ )
136
+ )
137
+ return checks
138
+
139
+
140
+ def _registry() -> list[Check]:
141
+ records = registry.all_records()
142
+ if not records:
143
+ return [Check(WARN, "hook records", "none yet: is the plugin installed?")]
144
+ latest = max(r.started_at for r in records)
145
+ when = datetime.fromtimestamp(latest).strftime("%Y-%m-%d %H:%M")
146
+ detail = f"{len(records)} under {registry.sessions_dir()}, last start {when}"
147
+ return [Check(OK, "hook records", detail)]
148
+
149
+
150
+ def run(args: argparse.Namespace) -> int:
151
+ del args
152
+ platform = _macos() if sys.platform == "darwin" else _linux()
153
+ checks = [
154
+ *platform,
155
+ _inside_ghostty(),
156
+ *_claude(),
157
+ *_accounts(),
158
+ *_registry(),
159
+ ]
160
+ width = max(len(c.label) for c in checks)
161
+ for c in checks:
162
+ print(f"[{c.status:<4}] {c.label:<{width}} {c.detail}")
163
+ return 1 if any(c.status == FAIL for c in checks) else 0
@@ -0,0 +1,104 @@
1
+ import argparse
2
+ import os
3
+ import signal
4
+ import subprocess
5
+ import sys
6
+ import threading
7
+ import time
8
+ from types import FrameType
9
+
10
+ from cc_ghostty import claude, procs, runs, sessions
11
+
12
+ FOLLOW_INTERVAL_SECONDS = 2.0
13
+
14
+
15
+ def _claude_session(child_pid: int) -> claude.LiveSession | None:
16
+ """The Claude session running under the tab's shell, if any."""
17
+ for live in claude.live_sessions(sessions.known_config_dirs()):
18
+ pid: int | None = live.pid
19
+ while pid is not None and pid > 1:
20
+ if pid == child_pid:
21
+ return live
22
+ found = procs.info(pid)
23
+ pid = found.parent if found else None
24
+ return None
25
+
26
+
27
+ def _follow_claude(record: runs.RunRecord, child: subprocess.Popen[bytes]) -> None:
28
+ """Keep the record on the session running in the tab (its id changes on
29
+ `/clear`)."""
30
+ while child.poll() is None:
31
+ session = _claude_session(child.pid)
32
+ current = record.reload()
33
+ if current.end_reason is not None:
34
+ return
35
+ if session is not None:
36
+ if (current.session_id, current.config_dir) != (
37
+ session.session_id,
38
+ session.config_dir,
39
+ ):
40
+ current.session_id = session.session_id
41
+ current.config_dir = session.config_dir
42
+ current.save()
43
+ time.sleep(FOLLOW_INTERVAL_SECONDS)
44
+
45
+
46
+ def run(args: argparse.Namespace) -> int:
47
+ record = runs.get(args.run_id)
48
+ if record is None:
49
+ print(f"cc-ghostty: no run {args.run_id}", file=sys.stderr)
50
+ return 1
51
+ started: list[subprocess.Popen[bytes]] = []
52
+
53
+ def interrupted(signum: int, frame: FrameType | None) -> None:
54
+ del frame
55
+ current = record.reload()
56
+ if current.end_reason is None:
57
+ current.ended_at, current.end_reason = time.time(), runs.INTERRUPTED
58
+ current.save()
59
+ runs.settle_later()
60
+ for child in started:
61
+ child.send_signal(signum)
62
+ sys.exit(128 + signum)
63
+
64
+ # Before the record says the tab runs: a signal from then on is recorded.
65
+ for signum in (signal.SIGHUP, signal.SIGTERM):
66
+ signal.signal(signum, interrupted)
67
+ # Ctrl-C is for the command, in the same process group.
68
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
69
+ record.pid = os.getpid()
70
+ record.proc_start = procs.proc_start(record.pid)
71
+ record.ghostty_surface_id = os.environ.get("GHOSTTY_SURFACE_ID")
72
+ ghostty = procs.terminal_of(record.pid)
73
+ record.ghostty_pid, record.ghostty_start = ghostty or (None, None)
74
+ record.ended_at = record.end_reason = None
75
+ record.save()
76
+
77
+ sys.stdout.write(f"\033]2;{runs.TITLE_PREFIX}{record.name}\a")
78
+ sys.stdout.flush()
79
+ shell = os.environ.get("SHELL") or "/bin/bash"
80
+ try:
81
+ os.chdir(record.cwd)
82
+ except OSError as error:
83
+ print(f"cc-ghostty: {error}", file=sys.stderr)
84
+ child = subprocess.Popen([shell, "-lc", record.command])
85
+ started.append(child)
86
+
87
+ if record.kind == "claude":
88
+ threading.Thread(
89
+ target=_follow_claude, args=(record, child), daemon=True
90
+ ).start()
91
+ code = child.wait()
92
+ current = record.reload()
93
+ if current.end_reason is None:
94
+ current.ended_at, current.end_reason = time.time(), runs.EXITED
95
+ current.save()
96
+ if record.kind == "claude" and code == 0:
97
+ # Claude was quit (`/exit`): its tab goes with it.
98
+ return 0
99
+ # Over, nothing left to restore: the tab becomes a plain shell, so a command's
100
+ # output, or Claude's error, can still be read.
101
+ for signum in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT):
102
+ signal.signal(signum, signal.SIG_DFL)
103
+ os.execvp(shell, [shell])
104
+ return 0 # never reached: execvp replaces the process
@@ -0,0 +1,18 @@
1
+ import argparse
2
+ import sys
3
+
4
+ from cc_ghostty import ghostty
5
+ from cc_ghostty.commands._pick import one_session
6
+
7
+
8
+ def run(args: argparse.Namespace) -> int:
9
+ session = one_session(args.session)
10
+ if session is None:
11
+ return 1
12
+ if not ghostty.backend().focus(session):
13
+ print(
14
+ f"cc-ghostty: no Ghostty terminal found for '{args.session}'",
15
+ file=sys.stderr,
16
+ )
17
+ return 1
18
+ return 0
@@ -0,0 +1,33 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from cc_ghostty import layout, registry, runs
6
+
7
+ RECORD_RETENTION_SECONDS = 14 * 24 * 3600
8
+ # A new tab changes the layout: snapshot it sooner than after a turn.
9
+ START_SNAPSHOT_INTERVAL = 3.0
10
+
11
+
12
+ def run(args: argparse.Namespace) -> int:
13
+ # A hook must never break the Claude session: swallow every error.
14
+ try:
15
+ hook_input = json.loads(sys.stdin.read() or "{}")
16
+ if args.event == "session-start":
17
+ registry.record_start(hook_input)
18
+ registry.prune(RECORD_RETENTION_SECONDS)
19
+ runs.prune(RECORD_RETENTION_SECONDS)
20
+ if registry.is_interactive_session():
21
+ runs.settle_closed_tabs()
22
+ layout.snapshot_soon(START_SNAPSHOT_INTERVAL)
23
+ elif args.event == "session-end":
24
+ ended = registry.record_end(hook_input)
25
+ if ended is not None and ended.end_reason == registry.SIGNALLED:
26
+ runs.settle_later()
27
+ elif registry.is_interactive_session():
28
+ registry.record_turn(hook_input)
29
+ runs.settle_closed_tabs()
30
+ layout.snapshot_soon()
31
+ except Exception as error:
32
+ print(f"cc-ghostty: {error}", file=sys.stderr)
33
+ return 0
@@ -0,0 +1,37 @@
1
+ import argparse
2
+ import json
3
+ from dataclasses import asdict
4
+
5
+ from cc_ghostty.commands import _selection
6
+
7
+
8
+ def run(args: argparse.Namespace) -> int:
9
+ candidates = _selection.candidates(args)
10
+ summaries = _selection.summaries(args, candidates)
11
+ if args.json:
12
+ payload = [
13
+ {
14
+ **vars(c),
15
+ "account": c.account,
16
+ **(
17
+ {"summary": asdict(summaries[c.session_id])}
18
+ if summaries is not None
19
+ else {}
20
+ ),
21
+ }
22
+ for c in candidates
23
+ ]
24
+ print(json.dumps(payload, indent=2))
25
+ return 0
26
+ if not candidates:
27
+ print("No interrupted session found.")
28
+ return 0
29
+ for c in candidates:
30
+ print(
31
+ f"{_selection.format_time(c.interrupted_at)} {c.session_id} "
32
+ f"{c.account or '?'} {c.title or '-'} {c.cwd}"
33
+ )
34
+ if summaries is not None:
35
+ for line in _selection.summary_lines(summaries[c.session_id]):
36
+ print(f" {line}")
37
+ return 0
@@ -0,0 +1,221 @@
1
+ import argparse
2
+ import fcntl
3
+ import shlex
4
+ import sys
5
+ import time
6
+ from collections.abc import Iterator, Sequence
7
+ from contextlib import contextmanager
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from cc_ghostty import delegate, ghostty, registry, runs
12
+
13
+ TAB_START_TIMEOUT = 15.0
14
+
15
+
16
+ def new_tab_record(args: argparse.Namespace) -> runs.RunRecord | None:
17
+ """The record of the tab or pane to open: a new Claude session, or `--run`."""
18
+ directory = Path(args.directory).expanduser().resolve()
19
+ if not directory.is_dir():
20
+ print(f"cc-ghostty: {directory} is not a directory", file=sys.stderr)
21
+ return None
22
+ # A dry run records nothing: no tab will run it.
23
+ save = not args.dry_run
24
+ if args.run:
25
+ return runs.create("command", directory, args.run, args.name, save=save)
26
+ name = args.name or delegate.session_name_for(directory)
27
+ command = delegate.claude_command(name, args.prompt)
28
+ return runs.create("claude", directory, command, name, save=save)
29
+
30
+
31
+ def describe(record: runs.RunRecord) -> str:
32
+ what = "Claude" if record.kind == "claude" else f"`{record.command}`"
33
+ return f"{what} '{record.name}' in {record.cwd}"
34
+
35
+
36
+ @contextmanager
37
+ def opening_lock() -> Iterator[None]:
38
+ """One tab, and its pane, at a time: a tab opened meanwhile would take the
39
+ focus the pane's split relies on."""
40
+ lock = registry.state_dir() / "open-tab.lock"
41
+ lock.parent.mkdir(parents=True, exist_ok=True)
42
+ with lock.open("w") as handle:
43
+ fcntl.flock(handle, fcntl.LOCK_EX)
44
+ yield
45
+
46
+
47
+ def _started(record: runs.RunRecord) -> runs.RunRecord | None:
48
+ """The record once its tab's launcher has recorded itself."""
49
+ deadline = time.monotonic() + TAB_START_TIMEOUT
50
+ while time.monotonic() < deadline:
51
+ current = record.reload()
52
+ if current.pid is not None:
53
+ return current
54
+ time.sleep(0.1)
55
+ return None
56
+
57
+
58
+ Direction = ghostty.SplitDirection
59
+
60
+
61
+ BESIDE_TAB, BESIDE_PREVIOUS = "tab", "previous"
62
+
63
+
64
+ class PlanError(Exception):
65
+ pass
66
+
67
+
68
+ @dataclass
69
+ class PaneSpec:
70
+ """A pane as asked: what it runs, and optionally its name, its direction and
71
+ which terminal it splits (`tab`, `previous`, or an earlier pane's name)."""
72
+
73
+ command: str
74
+ name: str | None = None
75
+ direction: Direction | None = None
76
+ beside: str | None = None
77
+
78
+
79
+ @dataclass
80
+ class PanePlan:
81
+ record: runs.RunRecord
82
+ direction: Direction
83
+ beside: str
84
+
85
+
86
+ @dataclass
87
+ class TabPlan:
88
+ """A tab to open, and the panes to open in it in turn."""
89
+
90
+ tab: runs.RunRecord
91
+ panes: list[PanePlan]
92
+
93
+ @property
94
+ def records(self) -> list[runs.RunRecord]:
95
+ return [self.tab, *(pane.record for pane in self.panes)]
96
+
97
+
98
+ def plan_panes(
99
+ specs: Sequence[PaneSpec], cwd: str | Path, save: bool
100
+ ) -> list[PanePlan]:
101
+ """Checks the panes, then records them. A pane with no direction or no
102
+ `beside` takes the previous pane's (`right` and `previous` for the first); one
103
+ with no name is named after its command (a name is how `focus` and `close`, and
104
+ a later pane's `beside`, find it)."""
105
+ resolved = []
106
+ names: list[str] = []
107
+ direction: Direction = "right"
108
+ beside = BESIDE_PREVIOUS
109
+ for i, spec in enumerate(specs, 1):
110
+ name = spec.name or runs.default_name(spec.command)
111
+ if name in (BESIDE_TAB, BESIDE_PREVIOUS):
112
+ raise PlanError(f"pane {i}: `{name}` is reserved, name the pane otherwise")
113
+ direction = spec.direction or direction
114
+ beside = spec.beside or beside
115
+ if beside not in (BESIDE_TAB, BESIDE_PREVIOUS, *names):
116
+ raise PlanError(
117
+ f"pane {i}: beside {beside!r}: neither `tab`, `previous` nor an "
118
+ "earlier pane of this tab"
119
+ )
120
+ names.append(name)
121
+ resolved.append((spec.command, name, direction, beside))
122
+ return [
123
+ PanePlan(runs.create("command", cwd, command, name, save=save), side, at)
124
+ for command, name, side, at in resolved
125
+ ]
126
+
127
+
128
+ def pane_specs(args: argparse.Namespace) -> list[PaneSpec]:
129
+ """The panes of the command line: each --pane-* option goes with the
130
+ --pane-run before it."""
131
+ specs: list[PaneSpec] = []
132
+ fields = {
133
+ "pane_name": "name",
134
+ "pane_direction": "direction",
135
+ "pane_beside": "beside",
136
+ }
137
+ for dest, value in args.pane_options:
138
+ flag = "--" + dest.replace("_", "-")
139
+ if dest == "pane_run":
140
+ specs.append(PaneSpec(value))
141
+ elif not specs:
142
+ raise PlanError(f"{flag} before any --pane-run")
143
+ elif getattr(specs[-1], fields[dest]) is not None:
144
+ raise PlanError(f"{flag} given twice for the pane `{specs[-1].command}`")
145
+ else:
146
+ setattr(specs[-1], fields[dest], value)
147
+ return specs
148
+
149
+
150
+ def _open_pane(
151
+ terminal: ghostty.Backend,
152
+ beside: runs.RunRecord,
153
+ pane: runs.RunRecord,
154
+ direction: Direction,
155
+ ) -> bool:
156
+ started = _started(beside)
157
+ if started is None:
158
+ print(f"cc-ghostty: '{beside.name}' did not start", file=sys.stderr)
159
+ return False
160
+ target = ghostty.Beside(started.ghostty_surface_id, started.name)
161
+ try:
162
+ terminal.split(runs.tab_command(pane), direction, target)
163
+ except ghostty.Unsupported as error:
164
+ print(f"cc-ghostty: {error}.", file=sys.stderr)
165
+ return False
166
+ return True
167
+
168
+
169
+ def open_planned(
170
+ terminal: ghostty.Backend, plan: TabPlan, target: ghostty.Target
171
+ ) -> bool:
172
+ """Opens the tab, then each pane once the terminal it goes beside has started;
173
+ on failure, the panes left unopened are marked closed."""
174
+ terminal.open_tabs([runs.tab_command(plan.tab)], target)
175
+ where = "window" if target == "new-window" else "tab"
176
+ print(f"Opened a Ghostty {where} running {describe(plan.tab)}.")
177
+ opened: dict[str, runs.RunRecord] = {}
178
+ previous = plan.tab
179
+ for i, pane in enumerate(plan.panes):
180
+ beside = {BESIDE_TAB: plan.tab, BESIDE_PREVIOUS: previous}.get(pane.beside)
181
+ beside = beside or opened[pane.beside]
182
+ if not _open_pane(terminal, beside, pane.record, pane.direction):
183
+ for left_out in plan.panes[i:]:
184
+ runs.mark_closed(left_out.record)
185
+ return False
186
+ print(
187
+ f"Opened a pane ({pane.direction} of '{beside.name}') running "
188
+ f"{describe(pane.record)}."
189
+ )
190
+ opened[pane.record.name] = previous = pane.record
191
+ if len(plan.panes) > 1:
192
+ terminal.equalize_splits(ghostty.Beside(None, plan.tab.name))
193
+ return True
194
+
195
+
196
+ def print_plans(plans: list[TabPlan]) -> None:
197
+ for plan in plans:
198
+ for record in plan.records:
199
+ print(f"cd {shlex.quote(record.cwd)} && {record.command}")
200
+
201
+
202
+ def run(args: argparse.Namespace) -> int:
203
+ try:
204
+ specs = pane_specs(args)
205
+ plan_panes(specs, ".", save=False)
206
+ except PlanError as error:
207
+ print(f"cc-ghostty: {error}", file=sys.stderr)
208
+ return 1
209
+ record = new_tab_record(args)
210
+ if record is None:
211
+ return 1
212
+ plan = TabPlan(record, plan_panes(specs, record.cwd, save=not args.dry_run))
213
+ terminal = ghostty.backend()
214
+ if args.dry_run or not terminal.available():
215
+ print_plans([plan])
216
+ return 0
217
+ with opening_lock():
218
+ opened = open_planned(
219
+ terminal, plan, "new-window" if args.window else "current-window"
220
+ )
221
+ return 0 if opened else 1